我试图检测一对矩形内的一双眼睛,如果用OpenCV 2.4.x Python检测到一个脸,就会出现这种情况。这是我的代码:
FACE_DETECT = "lbpcascade_frontalface.xml"
EYE_DETECT = "haarcascade_eye.xml"
DOWNSCALE = 4
webcam = cv2.VideoCapture(0)
face_classifier = cv2.CascadeClassifier(FACE_DETECT)
eye_classifier = cv2.CascadeClassifier(EYE_DETECT)
if webcam.isOpened(): # try to get the first frame
rval, frame = webcam.read()
else:
rval = False
while rval:
minisize = (frame.shape[1] / DOWNSCALE,frame.shape[0] / DOWNSCALE)
miniframe = cv2.resize(frame, minisize)
faces = face_classifier.detectMultiScale(miniframe)
eyes = eye_classifier.detectMultiScale(miniframe)
for f in faces:
fx, fy, fw, fh = [fv * DOWNSCALE for fv in f]
cv2.rectangle(frame, (fx, fy), (fx + fw, fy + fh), (0, 0, 255))
for (ex,ey, ew, eh) in eyes:
cv2.rectangle(frame, (ex,ey), ((ex+ew), (ey+eh)), (50, 50, 50), 3)
cv2.imshow('eyes = %s' % (eyes,), frame)
cv2.imshow("cam", frame)
rval, frame = webcam.read()
key = cv2.waitKey(20)
if key in [27, ord('Q'), ord('q')]: # exit on ESC
break
我的面部检测代码在这一个工作,但眼睛检测部分没有(我只是包括面部检测代码,以防它可能是很好用)。我在眼睛的循环序列中添加了一些print()语句:
for (ex,ey, ew, eh) in eyes:
cv2.rectangle(frame, (ex,ey), ((ex+ew), (ey+eh)), (50, 50, 50), 3)
cv2.imshow('eyes = %s' % (eyes,), frame)
但是,没有输出。
如果面部检测有效,那么眼睛检测应该起作用或至少进入眼环。我可能想到了一个错误的算法。如何检测眼睛?
任何帮助将不胜感激。 :)
答案 0 :(得分:2)
你要做的是搜索脸部的眼睛,而不是整个图像 您可以通过裁剪图像并仅获取面部来完成,然后尝试在该图像中找到眼睛
sub_face = miniframe[fy:fy+fh, fx:fx+fw]
eyes = eye_classifier.detectMultiScale(sub_frame)
for (ex,ey, ew, eh) in eyes:
cv2.rectangle(frame, (fx+ex,fy+ey), ((fx+ex+ew), (fy+ey+eh)), (50, 50, 50), 3)