问题描述
我正在尝试从视频中提取图像(帧)并将它们保存在特定位置。我编写了以下代码,它可以很好地提取彩色图像。
extractFrames(srcPath,dstPathColor)
然而,当我想提取灰度图像(extractFrames(srcPath,dstPathColor,gray=True
)时,只有一张图像被写入目标文件夹并且代码停止
import numpy as np
import cv2
print('OpenCV version: '+cv2.__version__)
import matplotlib as plt
def extractFrames(srcPath,dstPath,gray=False):
# gray = true writes only grayscale images of the video
cap = cv2.VideoCapture(srcPath)
# check if camera opened successfully
if (cap.isOpened() == False):
print("Error reading video file")
try:
frameCount = 1
while(cap.isOpened()):
ret,frame = cap.read()
if ret == True:
if gray==True:
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imwrite(dstPath+'grayframe'+str(frameCount)+'.jpg',gray)
else:
cv2.imwrite(dstPath+'colorframe'+str(frameCount)+'.jpg',frame)
frameCount += 1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly,ret is True
else:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
except:
print("Video has ended.")
cap.release()
cv2.destroyAllWindows()
vidName = 'scale_calib2.avi'
srcPath = vidName;
dstPathColor = 'Extracted Images\\Color\\'
dstPathGray = 'Extracted Images\\Gray\\'
#extractFrames(srcPath,dstPathColor)
#print('Finished extracting color images from video')
extractFrames(srcPath,dstPathGray,gray=True)
print('Finished extracting gray images from video')
输出:
Video has ended.
Finished extracting gray images from video
我该如何解决这个问题?
解决方法
终于发现是命名错误的问题。我将 gray
用于灰度图像的图像容器和函数 extractFrames