1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| """ Created on Tue Jul 2 16:22:12 2019 识别摄像头中的人脸、眼镜并框出 @author: Kevin """ import cv2 import numpy as np #调用人脸识别、眼睛检测库 face_cascade = cv2.CascadeClassifier("C:\Python\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml") eye_cascade = cv2.CascadeClassifier("C:\Python\opencv\sources\data\haarcascades\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.1,5) #检测人脸 if len(faces)>0: #若检测到人脸,则绘图,并检测眼睛 for faceRect in faces: x,y,w,h = faceRect cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #框出面部 roi_gray = gray[y:y+h//2,x:x+w] roi_color = img[y:y+h//2,x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray,1.1,1,cv2.CASCADE_SCALE_IMAGE,(2,2)) #检测眼睛 for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) #框出眼镜 cv2.imshow("img",img) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
|