代码读取train1.mov
文件,显示cv2.imshow('res', res)
也保存名为output.avi
的文件。问题是,output.avi大约是40 kb并且是空的。但cv2.imshow('res', res)
显示整个视频。然后显示以下错误。
Python代码:
import numpy as np
import cv2
cap = cv2.VideoCapture('C:\\Users\\khan1\\Desktop\\python project\\color_threshold\\train1.mov')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:\\Users\\khan1\\Desktop\\python project\\color_threshold\\output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_green = np.array([40, 60, 60])
upper_green = np.array([80, 255, 255])
mask = cv2.inRange(hsv, lower_green, upper_green)
mask = cv2.GaussianBlur(mask, (7, 7), 0)
res = cv2.bitwise_and(frame, frame, mask=mask)
out.write(res)
cv2.namedWindow("res", cv2.WINDOW_NORMAL)
cv2.imshow('res', res)
if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
break
# Release everything if job is finished
out.release()
cap.release()
cv2.destroyAllWindows()
错误:
OpenCV Error: Assertion failed ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F)) in cv::cvtColor, file C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\color.cpp, line 9815
Traceback (most recent call last):
File "C:/Users/khan1/Desktop/python project/color_threshold/savevid.py", line 19, in <module>
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
cv2.error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\color.cpp:9815: error: (-215) (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) in function cv::cvtColor
Process finished with exit code 1
我该如何解决?
答案 0 :(得分:1)
很明显你的错误发生在最后一帧;这就是为什么你的imshow
一直在工作但它出错并且没有完成写while
循环后发生的视频的原因。
cap.read()
返回的第一个值是关于帧是否存在/被读取的布尔值。因此,您只需在代码中插入if-else
块即可在读取帧时执行处理,如果没有,则quit
while
循环,以便您可以完成帧的编写。
这应该修补你的代码:
import numpy as np
import cv2
cap = cv2.VideoCapture('C:\\Users\\khan1\\Desktop\\python project\\color_threshold\\train1.mov')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:\\Users\\khan1\\Desktop\\python project\\color_threshold\\output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_green = np.array([40, 60, 60])
upper_green = np.array([80, 255, 255])
mask = cv2.inRange(hsv, lower_green, upper_green)
mask = cv2.GaussianBlur(mask, (7, 7), 0)
res = cv2.bitwise_and(frame, frame, mask=mask)
out.write(res)
cv2.namedWindow("res", cv2.WINDOW_NORMAL)
cv2.imshow('res', res)
if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
break
else:
break
# Release everything if job is finished
out.release()
cap.release()
cv2.destroyAllWindows()
查看同一过程的示例here。