'OpenCV-Python Error (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

Consider the following code:

import cv2

# define a video capture object
vid = cv2.VideoCapture(0, cv2.IMREAD_UNCHANGED)
classifier = cv2.CascadeClassifier(cv2.data.haarcascades +
                                       'haarcascade_frontalface_default.xml')

while True:
    # Capture the video frame
    # by frame
    ret, frame = vid.read()
    faces = classifier.detectMultiScale(frame)
    for face in faces:
        # extract
        x, y, width, height = face
        x2 = x + width
        y2 = y + height
        # draw a rectangle over the pixels
        cv2.rectangle(frame, (x, y), (x2, y2), (0, 0, 255), 1)

        # show the image
        cv2.imshow('frame', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # keep the window open until we press a key
    cv2.waitKey(0)
    # close the window
    cv2.destroyAllWindows()

There is a problem that when I run this line of code

faces = classifier.detectMultiScale(frame)

I always get the same error:

cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-c2l3r8zm\opencv\modules\objdetect\src\cascadedetect.cpp:1689: 
error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

As you can see, I have the two files in the same folder

I've tried all the solutions that I've seen, like giving the whole path for the classifier, but nothing seems to be working.



Solution 1:[1]

Those files being in the same folder means nothing.

Relative paths are resolved relative to the current working directory, not the directory the script resides in.

Further, your code uses cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' which is likely an absolute path.

You should check if a file exists at that location.

Then... always error-check.

You are missing several error checks.

  1. Right after classifier = cv2.CascadeClassifier... you must check if that succeeded:
assert not classifier.empty()

That is likely the issue here. The violated assertion (error message) checked for this condition.

  1. Right after vid = cv2.VideoCapture... you must check if that succeeded:
assert vid.isOpened()
  1. After reading each frame (ret, frame = vid.read()), you must check if that succeeded:
if not ret: break

Solution 2:[2]

Probably your file is not available in the path you specified. Try printing the path to check. Also check if classifier.empty() returns true to know if the file is empty.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ouflak