OpenCV中的CascadeClassifier生成错误

8

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

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

(注意:旋转是必需的,因为使用函数后,输出图像会逆时针旋转90度。)
我遇到了以下错误:
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

你在代码的哪一行遇到了什么错误? - paisanco
1个回答

10

错误信息的原因是图像 gray 的类型为 float64,而 face_cascade.detectMultiScale 函数需要的是无符号整数。修复方法是在调用 `face_cascade.detectMultiScale` 之前将图像转换为 uint8 类型:

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

还有其他问题。首先,cv2.rectangle不会返回一个图像,而是修改传递给它的图像。以下代码对我有效:

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

我没有发现图像旋转的问题,因此我删除了旋转代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接