import cv2
# 加载分类器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 开启摄像头
video_capture = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = video_capture.read()
# 检查是否成功读取了视频帧
if not ret:
print("无法读取视频帧")
break
# 将视频帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# 在人脸周围绘制矩形框
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示视频帧
cv2.imshow('Video', frame)
# 如果按下 q 键,退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头资源
video_capture.release()
cv2.destroyAllWindows()
标签:视频,capture,检测,frame,cv2,实时,人脸,video
From: https://www.cnblogs.com/tiansz/p/17362924.html