7

我正在尝试开发一个简单的应用程序来检测给定图像中的人脸和眼睛:

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()

(注:旋转是必须的,因为使用该cvtColor功能后,输出图像是逆时针旋转90度生成的。)

我收到以下错误:

回溯(最近一次通话最后):文件“/home/namit/Codes/wow.py”,第 10 行,在 faces = face_cascade.detectMultiScale(gray, 1.3, 5, 0) 错误:/home/namit/OpenCV/opencv -2.4.9/modules/objdetect/src/cascadedetect.cpp:1081: 错误: (-215) scaleFactor > 1 && image.depth() == CV_8U in function detectMultiScale

4

1 回答 1

10

错误消息gray的原因是图像需要无符号整数。解决方法是在调用 `face_cascade.detectMultiScale` 之前将图像转换为:float64face_cascade.detectMultiScaleuint8

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

还有其他问题。一方面,cv2.rectangle不返回图像;相反,它会修改您传递给它的图像。以下对我有用:

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()

我没有观察到图像旋转的问题,所以我删除了旋转代码。

于 2014-07-26T21:50:18.397 回答