我想简单地加载一个视频文件,将其转换为灰度,并显示它。下面是我的代码:
import numpy as np
import cv2
cap = cv2.VideoCapture('cars.mp4')
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
#print frame.shape
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
这个视频一直播放到最后。然后它冻结,窗口变得没有响应,我在终端中得到以下错误:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/clive/Downloads/OpenCV/opencv-2.4.9/modules/imgproc/src/color.cpp, line 3737
Traceback (most recent call last):
File "cap.py", line 13, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/clive/Downloads/OpenCV/opencv-2.4.9/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
我取消了对语句print frame.shape的注释。它一直在打印720,1028,3。但在视频播放到结束后,它会冻结,一段时间后它会关闭并返回
print frame.shape
AttributeError: 'NoneType' object has no attribute 'shape'
我知道这个断言失败消息通常意味着我正在尝试转换一个空图像。在开始使用if(ret):语句处理图像之前,我添加了对空图像的检查。(有没有其他方法??)
import numpy as np
import cv2
cap = cv2.VideoCapture('cars.mp4')
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
#print frame.shape
if(ret): #if cam read is successfull
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
这一次,视频一直播放到最后,窗口仍然冻结并在几秒钟后关闭。这一次,我没有得到任何错误。但是为什么窗口会冻结呢?我怎么才能修复它呢?
发布于 2014-12-02 19:40:57
waitKey()部分不应依赖于帧的有效性,请将其移出条件:
import numpy as np
import cv2
cap = cv2.VideoCapture('cars.mp4')
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
#print frame.shape
if(ret): #if cam read is successfull
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
else:
break
# this should be called always, frame or not.
if cv2.waitKey(1) & 0xFF == ord('q'):
break
https://stackoverflow.com/questions/27248068
复制相似问题