Search code examples
pythonopencvhaar-classifiercascade-classifier

Python OpenCV error with CascadeClassifier


import cv2
import imageio

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

def detect(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for(x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        gray_face = gray[y:y+h, x:x+w]
        color_face = frame[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(gray_face, 1.1, 3)
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(color_face, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
    return frame

reader = imageio.get_reader('1.mp4')
fps = reader.get_meta_data()['fps']
writer = imageio.get_writer('output.mp4', fps=fps)
for i, frame in enumerate(reader):
    frame = detect(frame)
    writer.append_data(frame)
    print(i)
writer.close()

the error I received is this;

Traceback (most recent call last):
  File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 23, in <module>
    frame = detect(frame)
  File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 9, in detect
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

Solution

  • xml files are not in current folder but in some folder of cv2 module and you have to use full path to load them.

    Lucky there is special variabel with folder name - cv2.data.haarcascades

    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
    

    To make sure you can use os.path.join() instead of +

    face_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml'))
    eye_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_eye.xml'))
    

    If xml files are loaded then this should gives False

    print(face_cascade.empty())
    print(eye_cascade.empty())