I am using the inbuilt cascade classifier for the face detection. This is how the code is (OpenCV Python Tutorials):
import numpy as np
import cv2
face_casc
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.
In newer versions of opencv haarcascades also gets installed you just need the file location of haarcascades, to get it you can use cv2.data.haarcascades just like shown below
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
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!
This post is old, but here is my answer nevertheless. Using absolute path did not work. Turns out that the XML file that I had downloaded (using curl) was corrupt. I had to manually copy and paste the contents from the github folder after which everything started working. Zhanwen Chen's answer also works (which I believe is the right way to do it for in-built classifiers).
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))
Well If you are getting this error then you need to download those 2 .xml files, because python can't find them on pc. I had same problem, then I downloaded the .xml files and kept it in folder where my .py file is. and then I got the perfect output. For downloading the files, search the file name and download it from sourceforge.