gpt4 book ai didi

python - openCV cvtColor 函数错误 : Assertion failed (scn == 3 || scn == 4)

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:00 24 4
gpt4 key购买 nike

我只想加载一个视频文件,将其转换为灰度并显示它。这是我的代码:

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()

这次视频播放到最后,窗口仍然卡住并在几秒钟后关闭。这次我没有收到任何错误。但是为什么窗口会卡住?我该如何解决?

最佳答案

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

关于python - openCV cvtColor 函数错误 : Assertion failed (scn == 3 || scn == 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com