OpenCV Error: Face detection python using OpenCV

I downloaded the xml file and file is correct.
But I am always getting the error
[ERROR:0@0.038] global persistence.cpp:505 cv::FileStorage::Impl::open Can’t open file: ‘haarcascade_frontalface_default.xml’ in read mode

Here is my code:
import cv2
face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
img = cv2.imread(‘test.jpg’)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)

for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

cv2.imshow(‘img’, img)
cv2.waitKey()

cv2.imwrite(“face_detected.jpg”, img)

The issue you’re describing is that OpenCV either can’t find or can’t open the file. Have you provided the correct path to that file? Is that file located in the local directory?

My file path is correct and it is located in my local directory

When I encounter errors like this I normally adapt my code to use absolute paths just to eliminate the possibility of anything weird happening on that front, sometimes things behave in weird ways that we don’t understand and we just need to narrow down the scope of the issue to make progress.
It’s possible that the XML file is corrupted. Try uninstalling/reinstalling and let me know if that works.
Otherwise make sure you’re using the XML file that matches your OpenCV version, as this could also cause errors.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.