> 文章列表 > [python][mediapipe]摄像头人脸检测

[python][mediapipe]摄像头人脸检测

[python][mediapipe]摄像头人脸检测

import cv2
import mediapipe as mp# 导入BlazeFace模型
mp_face_detection = mp.solutions.face_detection
model = mp_face_detection.FaceDetection(min_detection_confidence=0.5,  # 置信度阈值,过滤掉小于置信度的预测框model_selection=1,  # 选择模型,0 适用于人脸离摄像头比较近(2米内),1 适用于比较远(5米以内)
)
# 导入可视化函数以及可视化样式
mp_drawing=mp.solutions.drawing_utils
# 关键点样式
keypoint_style=mp_drawing.DrawingSpec(thickness=5,circle_radius=3,color=(0,255,0))
# 人脸预测框样式
bbox_style=mp_drawing.DrawingSpec(thickness=5,circle_radius=3,color=(255,0,0))
cap = cv2.VideoCapture(0)# 获取视频帧速率 FPS
frame_fps = int(cap.get(cv2.CAP_PROP_FPS))
# 获取视频帧宽度和高度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print("video fps={},width={},height={}".format(frame_fps, frame_width, frame_height))
while True:ret, frame = cap.read()if not ret:break# BGR转RGBimg_RGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# 将RGB输入模型预测结果results = model.process(img_RGB)# 可视化人脸框和人脸关键点for detection in results.detections:mp_drawing.draw_detection(frame,detection,keypoint_drawing_spec=keypoint_style,bbox_drawing_spec=bbox_style)cv2.imshow('frame', frame)if cv2.waitKey(1) & 0xFF == ord('q'):break
cap.release()
cv2.destroyAllWindows()