[PYTHON] cv :: CascadeClassifier :: detectMultiScale solution

Introduction

I will introduce the error that occurred when face detection with OpenCV and the solution.

problem

I got an error with the following code.

python


#Reading cascade classifier
cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

#Searching for the face area
face = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30))

error contents

python


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

Cause

It seems that the path specification of the classifier XML file is incorrect.

Solution

First, find out the path that contains OpenCV.

python


user>python
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 16:30:00) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import cv2
>>>cv2.__file__

'C:\\Users\\user\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python37\\site-packages\\cv2\\cv2.cp37-win_amd64.pyd'

Then find out the location of the XML file. path.jpg

In my case it was in / data.

Therefore, I modified the code as follows.

python


#Reading cascade classifier
cascade = cv2.CascadeClassifier("C:/Users/user/AppData/Local/Packages/PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0/LocalCache/local-packages/Python37/site-packages/cv2/data/haarcascade_frontalface_default.xml")

#Searching for the face area
face = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30))

in conclusion

result.jpg

I was able to detect it safely.

reference

https://qiita.com/K_M95/items/f1a3e7c47800adb94095

Recommended Posts

cv :: CascadeClassifier :: detectMultiScale solution