import cv2 |
# 需要下载人脸检测器,并将其路径添加到系统环境变量中。可以在OpenCV官网下载人脸检测器。 |
# 加载人脸检测器 |
detector = cv2.CascadeClassifier( "haarcascade_frontalface_default.xml" ) |
# 打开摄像头 |
capture = cv2.VideoCapture( 0 ) |
while True : |
# 读取摄像头画面 |
success, img = capture.read() |
# 使用人脸检测器检测人脸 |
faces = detector.detectMultiScale(img, 1.3 , 5 ) |
# 循环绘制人脸框 |
for (x, y, w, h) in faces: |
cv2.rectangle(img, (x, y), (x + w, y + h), ( 255 , 0 , 0 ), 2 ) |
# 显示画面 |
cv2.imshow( "Face Detection" , img) |
# 按下ESC键退出 |
if cv2.waitKey( 1 ) = = 27 : |
break |
|
# 关闭摄像头 |
capture.release() |
# 销毁窗口 |
cv2.destroyAllWindows() |