##10 电脑摄像头检测人脸与眼睛
import cv2
#检测图片
def detect(frame):
#灰度化图片,减少运算量
#img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img = frame
#加载特征数据,人脸、人眼
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + ‘haarcascade_frontalface_default.xml‘)
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + ‘haarcascade_eye.xml‘)
#检测人脸
faces = face_cascade.detectMultiScale(img,1.3 , 3)
for (x,y,w,h) in faces:
#画出人脸框
img = cv2.rectangle(img, (x, y, x+w, y+h), (255,0,0), 2)
#选定人脸区域,进行人眼识别
face_area = img[y:y+h, x:x+w]
#检测人眼
eyes = eye_cascade.detectMultiScale(face_area, 1.3, 15)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(face_area, (ex, ey, ex+ew, ey+eh), (0,255,0),1)
#返回检测后的图片
return img
if __name__ == ‘__main__‘:
#调用摄像头,参数:0;调用视频,参数为视频路径
cap = cv2.VideoCapture(0)
while True:
#读取视频中的每一帧,frame
flag,frame = cap.read()
#
if not flag:
break
#检测帧,返回图片
result = detect(frame)
cv2.imshow(‘Face and Eye‘, result)
#退出循环,按‘ESC’
if cv2.waitKey(5) == 27:
break
#释放cap
cap.release()
#关闭窗口
cv2.destroyAllWindows()