CascadeClassifier in OpenCV generates error
Asked Answered
P

1

8

I am trying to develop a simple application to detect faces as well as eyes in a given image:

from cv2 import *
face_cascade = CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = CascadeClassifier('haarcascade_eye.xml')

img = imread("123.jpg")
gray = cvtColor(img, COLOR_BGR2GRAY)
rows,cols = gray.shape
gray = getRotationMatrix2D((cols/2,rows/2),-90,1)

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

for (x,y,w,h) in faces:
    img = rectangle(img, (x,y), ((x+w),(x+h)), (255,0,0), 2)
    #gray = rectangle(gray, (x,y), ((x+w), (x+y)), (0, 255, 0), 4)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_grey)
    for (ex,ey, ew, eh) in eyes:
        roi_color = rectangle(roi_color, (x,y), ((x+w), (y+h)), (50, 50, 50), 3)

imshow("img", img)
waitKey(9)
destroyAllWindows()

(Note: The rotation is necessary, as after using the cvtColor function, the output image is generated with a rotation of 90 degrees counter clockwise.)

I am getting the following error:

Traceback (most recent call last): File "/home/namit/Codes/wow.py", line 10, in faces = face_cascade.detectMultiScale(gray, 1.3, 5, 0) error: /home/namit/OpenCV/opencv-2.4.9/modules/objdetect/src/cascadedetect.cpp:1081: error: (-215) scaleFactor > 1 && image.depth() == CV_8U in function detectMultiScale

Preindicate answered 26/7, 2014 at 19:36 Comment(1)
What error are you encountering at what line(s) of the code?Smuggle
T
10

The cause of the error message was that the image gray was float64 while face_cascade.detectMultiScale requires unisigned integer. The fix for that is to convert the image to uint8 before calling `face_cascade.detectMultiScale``:

import numpy as np
gray = np.array(gray, dtype='uint8')

There were other issues. For one, cv2.rectangle does not return an image; instead it modifies the image that you pass to it. The following works for me:

from cv2 import *
import numpy as np
face_cascade = CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = CascadeClassifier('haarcascade_eye.xml')

fname='123.jpg'
img = imread(fname)
gray = imread(fname, CV_LOAD_IMAGE_GRAYSCALE)
rows,cols = gray.shape

gray = np.array(gray, dtype='uint8')
faces = face_cascade.detectMultiScale(gray, 1.3, 5, 0)
print 'faces=', faces

for (x,y,w,h) in faces:
    rectangle(img, (x,y), ((x+w),(x+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:
        rectangle(roi_color, (x,y), ((x+w), (y+h)), (50, 50, 50), 3)
    imshow('eyes=%s' % (eyes,), roi_color)

imshow("img", img)
waitKey(0)
destroyAllWindows()

I did not observe a problem with image rotation, so I removed the rotation code.

Toluol answered 26/7, 2014 at 21:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.