Face detection using Cascade Classifier in opencv python

Refer to this line of code, it failed on checking that cascade is non empty. Please check path to XML files with trained cascades. You may need to specify full path to XML's like this:

face_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\opencv\data\haarcascades\haarcascade_eye.xml')

Or just put this files to directory containig your script.


You do NOT need to download or copy the .xml files. According to the OpenCV-Python PyPi page, you can simply use the packaged path to the installed cascades - cv2.data.haarcascades:

import cv2

# Globals
FACE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
EYE_CLASSIFIER = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
SCALE_FACTOR = 1.3
BLUE_COLOR = (255, 0, 0)
MIN_NEIGHBORS = 5

# Then use it however you'd like
try:
    faces = FACE_CLASSIFIER.detectMultiScale(gray, SCALE_FACTOR, MIN_NEIGHBORS)
    for (x, y, w, h) in faces:
        cv2.rectangle(self.roi_frame, (x, y), (x+w, y+h), BLUE_COLOR, HAAR_LINE_THICKNESS)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = self.roi_frame[y:y+h, x:x+w]
        eyes = EYE_CLASSIFIER.detectMultiScale(roi_gray)
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), GREEN_COLOR, HAAR_LINE_THICKNESS)
except Exception as e:
    warnings.warn('{}.show_haar_features: got exception {}'.format(__name__, e))

I just happened to see this post when I faced a similar issue. I successfully resolved the error by executing the below 2 lines:

face_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_frontalface.xml')

eye_cascade = cv2.CascadeClassifier('opencv-3.0.0/data/harcascades/haarcascade_eye.xml')

Maybe, it will help others in resolving the same!