Solving OpenCV VideoCapture error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

Solving OpenCV VideoCapture error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ is a common error which occurs when you are using OpenCV and cvtColor the wrong way.

In this blog post we will try to solve the OpenCV VideoCapture error and see why it occurs in the first place, we will present multiple solutions so you can find the one which suits your particular case.

Explaining OpenCV VideoCapture error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

First of all, let us check out how the message of the error looks like.

                                                                       #
File "cam.py", line 75, in <module>
   main()
 File "cam.py", line 71, in main
   show_webcam(mirror=True)
....
 cv2.error: OpenCV(3.4.4) C:\projects\opencv- 
   python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion 
   failed) !_src.empty() in function 'cv::cvtColor'
                                                                       #

The error occurs because None gets passed on cv2.cvtColor.

Bellow is a number of tested solutions that I have tried and have worked for me.

Solution 1 : check your hardware

First, this solution may sound simple or lazy as it does not need any change of code or command, but just make sure you try it, sometimes the issue is not in your code but in your material.

The solution is to check if the camera is connected, disconnect the camera and connect it.

See if the camera is being used somewhere else, like in a video capture software or something…

If that did not work, let us try solving the error by using code.

Solution 2 : check that img is not None

The error usually happens after ret, img = cap.read() usually None gets passed on cv2.cvtColor.

cap.read() usually fails but it usually starts giving valid output images.

                                                                       #
cap = cv2.VideoCapture(0)
while True:
    ret, img = cap.read()
    img, contours, thresh = get_img_contour_thresh(img)
    ans = ''
                                                                       #

Another way is to check if not ret: break but that is outside the scope of this blog post.

The error above was hard to deal with, I spent hours looking for a proper solution or set of solutions. I hope my effort solved your issue or at least guided you in the right direction.

Summing-up

This is one of those errors that are hard to explain or spot, sometimes this error comes with other problems with your code or Python which makes solving the issue even more complicated.

I hope my article helped you solve this common issue, keep coding and learning, cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/