【问题标题】:Why Does OpenCV Won't Detect Eyes With Haar Cascades In Python?为什么 OpenCV 不会在 Python 中使用 Haar 级联检测眼睛?
【发布时间】:2014-08-05 21:51:26
【问题描述】:

我正在尝试检测矩形内的一对眼睛,如果使用 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)

但是,没有输出出现。
如果人脸检测有效,那么眼睛检测应该有效,或者至少进入眼睛循环。我可能想到了一个错误的算法。如何检测眼睛?

任何帮助将不胜感激。 :)

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    您需要做的是搜索脸部的眼睛,而不是整个图像 您可以通过裁剪图像并仅获取面部来做到这一点,然后尝试在该图像中找到眼睛

    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)
    

    【讨论】:

    • 你从哪里得到的 sub_frame?当我运行它时,它说ysub_face = miniframe[y:y + h, x: x + w] 中未定义。
    • 哎呀,该行应该是sub_face = miniframe[fy:fy+fh, fx:fx+fw] sub_frame 实际上是原始迷你帧的裁剪部分,其中仅包含面部您需要这样做,因为您只提供面部作为 detectMultiScale 函数的输入
    猜你喜欢
    • 2023-03-25
    • 2015-05-24
    • 2012-08-27
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2013-01-03
    • 2011-05-02
    • 2013-03-02
    相关资源
    最近更新 更多