本文实例为大家分享了python动态人脸检测的具体代码,供大家参考,具体内容如下
直接上代码: 按Q退出
import cv2
import numpy as np
cv2.namedWindow("test")
cap = cv2.VideoCapture(0) #加载摄像头录制
# cap = cv2.VideoCapture("test.mp4") #打开视频文件
success, frame = cap.read()
# classifier = cv2.CascadeClassifier("/Users/yuki/anaconda/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml")
# 确保此xml文件与该py文件在一个文件夹下,否则将这里改为绝对路径
#haarcascade_frontalface_default.xml
classifier = cv2.CascadeClassifier("/Users/yuki/anaconda/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
# 确保此xml文件与该py文件在一个文件夹下,否则将这里改为绝对路径
while success:
success, frame = cap.read()
size = frame.shape[:2]
image = np.zeros(size, dtype=np.float16)
image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.equalizeHist(image, image)
divisor = 8
h, w = size
minSize = (w // divisor, h // divisor)
faceRects = classifier.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize)
if len(faceRects) > 0:
for faceRect in faceRects:
x, y, w, h = faceRect
cv2.rectangle(frame,(x,y),(x+h,y+w),(0,255,0),2)
#锁定 眼和嘴巴
#cv2.circle(frame, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8), (255, 0, 0)) # 左眼
#cv2.circle(frame, (x + 3 * w //4, y + h // 4 + 30), min(w // 8, h // 8), (255, 0, 0)) #右眼
#cv2.rectangle(frame, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), (255, 0, 0))#嘴巴
cv2.imshow("test", frame)
key = cv2.waitKey(10)
c = chr(key & 255)
if c in ['q', 'Q', chr(27)]:
break
cv2.destroyWindow("test")
您可能感兴趣的文章:Python基于OpenCV实现人脸检测并保存OpenCV-Python 摄像头实时检测人脸代码实例Python OpenCV利用笔记本摄像头实现人脸检测python opencv人脸检测提取及保存方法python版opencv摄像头人脸实时检测方法Python3.6.0+opencv3.3.0人脸检测示例Python基于OpenCV实现视频的人脸检测Python+OpenCV人脸检测原理及示例详解python利用OpenCV2实现人脸检测python结合opencv实现人脸检测与跟踪python中使用OpenCV进行人脸检测的例子Python OpenCV调用摄像头检测人脸并截图