OpenCV Error in cvtColor function: assertion failed (scn == 3 || scn == 4)
I just want to upload a video file, convert it to grayscale and display it. Here is my code:
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()
The video plays in grayscale until the end. Then it freezes and the window becomes unresponsive and I get the following error in the terminal:
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
I have uncommented the print frame.shape statement. It stores print 720,1028,3. But after the video is played to the end it freezes and after a while it closes and returns
print frame.shape
AttributeError: 'NoneType' object has no attribute 'shape'
I understand that this massage of assertion failure usually means that I am trying to transform an empty image. I added a check for an empty image before starting to process it with the if (ret): statement. (Any other way to do this?)
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()
This time, the video plays to the end, and the window still freezes and closes after a few seconds. This time I am not wrong. But why window freeze? How can I fix this?
source to share
the waitKey () part should not depend on the validity of the frame, deduce it from the condition:
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
source to share