Search code examples
pythonopencvface-detection

cv2.CascadeClassifier.detectMultiScale() failing with -215:Assertion failed


I'm using Python v3.8.3 and OpenCV v4.5.1 on Windows 10. All I'm trying to do is verify that OpenCV is working by attempting to detect a face. Here is the input image. I've seen this answer but that doesn't solve my problem.

import cv2

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
print(f"face: {face_cascade}")

# Read the input image
img = cv2.imread('./images/female_frontal.jpg')
print(f"img: {img}")

# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(f"gray: {gray}")

# Detect faces
faces = face_cascade.detectMultiScale(gray)
print(f"faces: {faces}")

Output:

$ python profile_dectector.py
face: <CascadeClassifier 019F3220>
img: [[[197 174 128]
  [196 173 127]
  [196 173 127]
  ...
  [105  61  37]
  [108  64  40]
  [114  66  42]]]

gray: [[163 162 162 ... 171 168 166]
 ...
 [166 156 153 ...  59  62  64]]
Traceback (most recent call last):
  File "profile_dectector.py", line 18, in <module>
    faces = face_cascade.detectMultiScale(gray)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-xeqjxthj\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

Solution

  • Using this line of code instead solved my issue:

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