1)程序代码:
# 2.使用haarcascade_frontalface_default.xml分类器检测视频中的人脸,并框出人脸位置
import cv2# 加载人脸检测的 Haar 级联分类器
face_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml')# 打开摄像头
camera = cv2.VideoCapture(0)while True:ret, frame = camera.read()if ret:# 将当前帧转换为灰度图像gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)faces = face_cascade.detectMultiScale(gray)for (x, y, w, h) in faces:cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)cv2.imshow('camera', frame)else:breakif cv2.waitKey(1) == ord(' '):breakcamera.release()
cv2.destroyAllWindows()
2)代码分析: