0

Im trying to make face detection with Python's OpenCV lib. I have seen the code from the web but for some reason I always get the same error. My haarcascades, .py and my image are in the same folder called FaceDetection. This is the line of error and the error:

faces = frontal_face_cascade.detectMultiScale(gray, 1.3, 5)

cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

I have tried different approaches that I saw on this website but I always get the same error. What am I doing wrong?

import numpy as np
import cv2

# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
# loading cascades for detection

frontal_face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# I have also tried this: r'C:\Users\Pc\Desktop\FaceDetection\haarcascade_frontalface_default.xml'

print(frontal_face_cascade)

my_image = r'C:\Users\Pc\Desktop\FaceDetection\barcelona.jpg'

img = cv2.imread(my_image, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

print(gray)
cv2.imshow('img',img)

faces = frontal_face_cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
for (x,y,w,h) in faces:

    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

cv2.imshow('img',img)
taga
  • 3,537
  • 13
  • 53
  • 119

1 Answers1

0

Error means your CascadeClassifier is not instantiated correctly. print(frontal_face_cascade) will always print a CascadeClassifier object, instead use:

frontal_face_cascade.empty()

If this returns true, either
1- Your path to xml file is incorrect.
2- Your xml file is incorrect
3- For some reason xml file could not be loaded?

If you are sure file and path is correct, try loading it again with:

frontal_face_cascade.load('haarcascade_frontalface_default.xml')
unlut
  • 3,525
  • 2
  • 14
  • 23