pushkin pushkin - 11 months ago 227
Python Question

OpenCV Python Error Assertion failed (scn == 3 || scn == 4)

I just started playing around with OpenCV in Python and am running into an assertion error.
I copied the following code from a tutorial, but it's not working for me.

import numpy as np
import cv2 as cv

cap = cv.VideoCapture(0) # use first webcam
if not cap.isOpened(): cap.open()

while True:
# capture frame-by-frame
ret, frame = cap.read()

# our operations on the frame come here
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)

# display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) & 0xFF == ord('q'):
# when everything is done, release the capture

When running, I get "OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor"...

When printing the variables ret and frame from above, I get (False,None), so it's not even capturing the frame correctly.

What exactly is the issue, and how can I resolve it?
Thank you.

Answer: needed to add
if not ret : continue
because sometimes the first frame is 'dead'

Answer Source

After ret, frame = cap.read(), add if not ret: continue.

Some cam-drivers return an invalid first frame.