OpenCV VideoCapture and (-215:Assertion failed) !_src.empty() in function 'cvtColor'

14.6k views Asked by At

This code originally worked fine. But when I run it again, the following error appears. I searched a lot about the error, but couldn't find a solution. Any help would be appreciated.

cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-frffvd08/opencv-python/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

The code below is the Python code I wrote.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height

while(True):
#while(cap.isOpened()):
    ret, frame = cap.read()
    frame = cv2.flip(frame, -1) # Flip camera vertically
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame', frame)
    cv2.imshow('gray', gray)

    k = cv2.waitKey(30) & 0xff
    if k == 27: # press 'ESC' to quit
        break
cap.release()
cv2.destroyAllWindows()
1

There are 1 answers

1
chandni goyal On

!_src.empty() means you have empty frame.

When cv2 can't get frame from camera/file/stream then it doesn't show error but it set None in frame and False in ret - and you have to check one of these values

if frame is not None: 
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # ... other code ...
else:
    print("empty frame")
    exit(1)

or

if ret:  # if ret is True:
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      # ... other code ...
else:
      print("empty frame")
      exit(1)

Sometimes cv2 has problem to find haarcascades file. And there is special variable with path to folder with .xml - cv2.data.haarcascades - and you may need

faceCascade = cv2.CascadeClassifier( os.path.join(cv2.data.haarcascades, "haarcascade_frontalface_default.xml") )