我想阅读现有视频,将其转换为灰度并播放灰度视频。代码如下
import cv2
import numpy as np
# read the video
cap = cv2.VideoCapture('input.avi')
while(True):
ret, frame = cap.read()
# convert it into grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
灰度视频播放到最后。播放完毕后,会弹出以下错误-
Traceback (most recent call last):
File "D:\L1.py", line 11, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
为什么显示此错误?有什么解决办法吗?
我正在使用python 3.6和opencv 3.4
答案 0 :(得分:2)
视频播放完后,循环将继续尝试获取帧。您可以检查cap
是否返回了图像,或者是否断裂,如下所示。另外,别忘了发布视频。
import cv2
import numpy as np
# read the video
cap = cv2.VideoCapture('input.avi')
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
# convert it into grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()