环境:python2.7 运行后按q截取图片并保存两眼ROI区域,按w结束
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plot
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('haarcascade_eye.xml')
cap = cv.VideoCapture(0)
while(1):
# get a frame
ret, img = cap.read()
# show a frame
cv.imshow("capture", img)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# img = cv.imread('3-1.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv.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)
i = 1
for (ex,ey,ew,eh) in eyes:
cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
# roi_eyegray = gray[y:y + h, x:x + w]
# roi_eyegray = gray[ey:ey + eh, ex:ex + ew]
roi_eyegray = roi_color[ey:ey + eh, ex:ex + ew]
cv.imwrite(str(i)+"roi.png", roi_eyegray)
i = i + 1
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
if cv.waitKey(1) & 0xFF == ord('w'):
cap.release()
cv2.destroyAllWindows()