Face detection using Cascade Classifier in opencv python

praddy4 picture praddy4 · Jun 16, 2015 · Viewed 49.6k times · Source

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_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('ammma.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:
    cv2.Rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for(ex,ey,ew,eh) in eyes:
        cv2.Rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

But when I run the code I am getting the following error:

C:\Python27\python.exe C:/Users/DELL/Downloads/Amma/code/fd.py

OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp, line 1634 Traceback (most recent call last): File "C:/Users/DELL/Downloads/Amma/code/fd.py", line 10, in faces = face_cascade.detectMultiScale(img, 1.3, 5) cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp:1634: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale

Answer

akarsakov picture akarsakov · Jun 16, 2015

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.