简体   繁体   English

从 haarcascade 中提取眼睛

[英]Extract eyes from haarcascade

I know how to identify a face and the eyes, with opencv and haarcascade.我知道如何使用 opencv 和 haarcascade 识别面部和眼睛。 But how can I crop or get only the eyes from webcam capture?但是我怎样才能从网络摄像头捕捉中裁剪或只获取眼睛呢? Just one, or even the both, so I can use as a new frame in imshow...只有一个,甚至两者都有,所以我可以在 imshow 中用作新框架......

See on this post:请参阅此帖子:

How to crop an image in OpenCV using Python 如何使用 Python 在 OpenCV 中裁剪图像

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

Your "img[y:y+h, x:x+w]" is just the output from your haarcascade.您的 "img[y:y+h, x:x+w]" 只是您的 haarcascade 中的 output。 Maybe you recieve multiple output so you have to choose one.也许您收到多个 output 所以您必须选择一个。

After detect face you can do this.检测到人脸后,您可以执行此操作。

eyes = eye_cascade.detectMultiScale(roi_gray)
for ex, ey, ew, eh in eyes:
    roi = roi_color[ey:ey + ew, ex:ex + eh]

Then can show roi using cv2.imshow().然后可以使用 cv2.imshow() 显示 roi。

The haarcascade_eye.xml and haarcascade_frontalface_default.xml link file haarcascade_eye.xmlhaarcascade_frontalface_default.xml链接文件

import cv2

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

#load image saved in the same directory
img = cv2.imread("your_image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for f in faces:
    x, y, w, h = [ v for v in f ]
    cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
    alt_gray = gray[y:y+h, x:x+w]
    alt_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(alt_gray)

eye_crop = []
for f in eyes:
    x, y, w, h = [ v for v in f ]
    cv2.rectangle(alt_color, (x,y), (x+w, y+h), (255,0,0), 2)

    # Define the region of interest in the image  
    eye_crop.append(alt_gray[y:y+h, x:x+w])

for eye in eye_crop:
    cv2.imshow('eye',eye)
    cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM