Python OpenCV - 检测眼睛并保存

Python OpenCV - Detect eyes and save

我是 OpenCV 新手。我需要使用 opencv 检测眼睛并将它们保存在文件夹中以供进一步分类。我为此编写了以下脚本:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)
while True:
     ret, img = cap.read()
     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     faces = face_cascade.detectMultiScale(gray, 1.3, 5)
     count=1
     for (x,y,w,h) in faces:
         cv2.rectangle(img,(x,y),(x+w,y+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:
             crop_img = roi_color[ey: ey + eh, ex: ex + ew]
             cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
             s="{0}.jpg"
             s1='/home/kushal/Pictures/Webcam/'+s.format(count)
             count=count+1
             cv2.imwrite(s1,crop_img)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
    break

cap.release()
cv2.destroyAllWindows()

我想保存尽可能多的眼睛图像。但我只保存了 3-4 张眼睛图像。是否有可能每秒获取一帧或一张图像?这段代码应该做哪些修改?

count=1 移到 while-loop 之外。

count = 1
while True:
    pass
    #your code

cv2.imshow 的缩进不太正确。

import numpy as np
import cv2

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

cap = cv2.VideoCapture(0)
count=1

while True:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+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:
            print(count)
            crop_img = roi_color[ey: ey + eh, ex: ex + ew]
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
            s1='tmp/{}.jpg'.format(count)
            count=count+1
            cv2.imwrite(s1,crop_img)

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

参考之前的回答,你也可以尝试改变haar-cascade滑动的比例因子window。

此时您可能已经发现您的图库中存在误报,即非眼睛图像被 haar-cascade 检测为眼睛。所以我建议尝试 D-lib,因为它可以获得更准确的结果。大家可以尝试从d-lib库提供的68个人脸界标点裁剪感兴趣区域。为了你的reference.