2
votes

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'):
    break
# when everything is done, release the capture
cap.release()
cv.destroyAllWindows()

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.

1

1 Answers

3
votes

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

Some cam-drivers return an invalid first frame.