python opencv3 摄像头人脸检测


git:https://github.com/linyi0604/Computer-Vision

 1 # coding:utf8
 2 
 3 import cv2  4 
 5 
 6 def detect():  7     # 创建人脸检测的对象
 8     face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml")  9     # 创建眼睛检测的对象
10     eye_cascade = cv2.CascadeClassifier("../data/haarcascade_eye.xml") 11     # 连接摄像头的对象 0表示摄像头的编号
12     camera = cv2.VideoCapture(0) 13 
14     while True: 15         # 读取当前帧
16         ret, frame = camera.read() 17         # 转为灰度图像
18         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 19         # 检测人脸 返回列表 每个元素都是(x, y, w, h)表示矩形的左上角和宽高
20         faces = face_cascade.detectMultiScale(gray, 1.3, 5) 21         # 画出人脸的矩形
22         for (x, y, w, h) in faces: 23             # 画矩形 在frame图片上画, 传入左上角和右下角坐标 矩形颜色 和线条宽度
24             img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) 25             # 把脸单独拿出来
26             roi_gray = gray[y: y+h, x: x+w] 27             # 在脸上检测眼睛 (40, 40)是设置最小尺寸,再小的部分会不检测
28             eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, 0, (40, 40)) 29             # 把眼睛画出来
30             for(ex, ey, ew, eh) in eyes: 31                 cv2.rectangle(img, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2) 32 
33         cv2.imshow("camera", frame) 34         if cv2.waitKey(5) & 0xff == ord("q"): 35             break
36 
37  camera.release() 38  cv2.destroyAllWindows() 39 
40 
41 if __name__ == '__main__': 42     detect()

 

我很丑哦 不要笑啊

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM