I run my code in Pycharm Community Edition 2020.1.1 x64 and I add my haar_face.xml and this py file in the same folder. I also tried to google and add some stuffs like cv.data.haarcascade+ or copy the complete path of the xml file but it still shows me the error below.
CODE
import cv2 as cv
from cv2 import imshow
import numpy as np
img = cv.imread('lily.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray People', gray)
haar_cascade= cv.CascadeClassifier(cv.data.haarcascades+r'C:\Users\mycomp\Desktop\CODE\OPENCV\haar_face.xml')
print(haar_cascade.empty()) #True
faces_rect = haar_cascade.detectMultiScale(img)#gray, scaleFactor=1.1, minNeighbors=1)
print(f'Number of faces found = {len(faces_rect)}')
for (x,y,w,h) in faces_rect:
cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)
cv.imshow('Detected Faces', img)
cv.waitKey(0)
RESULT
Traceback (most recent call last):
File "C:/Users/mycomp/Desktop/CODE/OPENCV/face_detection.py", line 12, in <module>
faces_rect = haar_cascade.detectMultiScale(img)#gray, scaleFactor=1.1, minNeighbors=1)
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-duilijvh\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
The path is wrong in this line:
haar_cascade= cv.CascadeClassifier(
cv.data.haarcascades+r'C:\Users\mycomp\Desktop\CODE\OPENCV\haar_face.xml')
Replace this with:
haar_cascade=cv.CascadeClassifier(
cv.haarcascades+"haarcascade_frontalface_default.xml")