测试 video playback example 时根据 OpenCV 介绍性视频教程,我的视频(.m4v 和 .mov)在完成后总是卡住一点,然后抛出此错误消息:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-33-6ff11ed068b5> in <module>()
15
16 # Our operations on the frame come here
---> 17 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
18
19 # Display the resulting frame
error: /home/user/opencv-2.4.9/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
我的解释是,这是因为最后一个帧
将为空并且缺少cvtColor()
期望的 channel ,因此图像无法显示。如果我稍微修改示例代码并将 while(True)
替换为在视频最后一帧之后结束的 for 循环,则我不会收到此类消息,并且视频窗口会关闭而不是卡住。
但是,我认为这不是 OpenCV 中的默认行为是有原因的,而且我担心我的修改会在未来进一步搞砸一些事情(对于 OpenCV 来说是全新的)。所以现在我想了解一些事情:
- 为什么
while(True)
是显示视频的默认值,因为它卡住并抛出错误消息(如果这不是我的设置所独有的)? - 使用 for 循环是否安全,还是应该坚持使用
while(True)
并在每次播放视频时等待错误消息? - 有没有一种首选方法可以让 OpenCV 优雅地退出视频播放?
我已尝试过建议here他们确实帮助不完全卡住内核,但视频仍然卡住并且错误消息仍然显示。 for 循环替代方案似乎更流畅。
我在 Ubuntu 14.04 上使用带有 Python 2.7.9 和 OpenCV 2.4.9 的 Ipython Notebook。下面是我正在执行的代码。
import cv2
video_name = '/path/to/video'
cap = cv2.VideoCapture(video_name)
# while(True): #causes freeze and throws error
for num in range(0,int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))):
# Capture frame-by-frame
ret, frame = cap.read()
# 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()
最佳答案
由于我最终想在某些情况下循环播放视频,因此以下内容被证明是对我来说最好的解决方案。
import numpy as np
import cv2
cap = cv2.VideoCapture('/path/to/vid.mp4')
frame_counter = 0
loop = True
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
frame_counter += 1
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
if loop == True:
frame_counter = 0
cap = cv2.VideoCapture(video_name)
else:
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
如果您不需要循环播放视频,只需使用
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
break
或 Padraic 的解决方案(稍作修改)
try:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
except cv2.error:
break
try/except 语句确实会产生短暂的延迟,视频在关闭之前会卡住。 if 语句在播放完成后立即关闭它。
我仍然很感兴趣是否有人可以解释为什么首先遇到错误消息,因为 padraic 说他的机器上不是这种情况。
编辑:所以我注意到我误读了教程,应该使用 while(cap.isOpened())
而不是 while(True)
,但我仍然遇到与 while(cap.isOpened())
相同的错误。
关于python - 为什么 OpenCV 介绍性视频教程中的示例会抛出错误?首选解决方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27881819/