【发布时间】:2014-12-02 11:17:01
【问题描述】:
我想简单地加载一个视频文件,将其转换为灰度并显示它。这是我的代码:
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()
这次视频播放到最后,窗口仍然冻结并在几秒钟后关闭。这次我没有收到任何错误。但是为什么窗口会冻结?我该如何解决?
【问题讨论】:
-
也许
cap.release()需要一些时间才能完成。如果你在最后交换两行,窗口仍然冻结吗? -
@Arnaud P 是的
-
好的。作为最后的疯狂猜测:如果你是多线程的,如果它不在主线程上运行,opencv 图像显示效果不佳。
-
@Arnaud P 什么是多线程?如何“在主线程上运行”?
-
Multithreading on wikipedia,基本上就是并行的意思。如果您正在运行一个“简单的”python 脚本并且不知道使用过线程,那么您很可能已经在主线程上运行。如果你被集成到一个框架中,问题是开放的。