如何在MediaPipe人脸检测中提取人脸的X、Y整数坐标?
MediaPipe实时人脸检测:提取人脸坐标、数量及置信度
核心解决方案
MediaPipe的FaceDetection检测结果包含了你需要的所有信息,只需对输出的归一化数据做简单转换即可拿到整数坐标,同时直接读取对应的属性就能获取人脸数量和置信度。
代码实现(Python)
import cv2 import mediapipe as mp # 初始化MediaPipe人脸检测和绘图工具 mp_face_detection = mp.solutions.face_detection mp_drawing = mp.solutions.drawing_utils # 打开摄像头 cap = cv2.VideoCapture(0) with mp_face_detection.FaceDetection( model_selection=0, # 0适用于近距离人脸,1适用于远距离 min_detection_confidence=0.5) as face_detection: while cap.isOpened(): success, image = cap.read() if not success: print("忽略空帧") continue # 转换图像为RGB(MediaPipe要求输入格式) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = face_detection.process(image_rgb) # 获取当前帧的尺寸 img_height, img_width = image.shape[:2] # 处理检测结果 if results.detections: # 1. 获取检测到的人脸数量 face_count = len(results.detections) print(f"检测到人脸数量: {face_count}") for detection in results.detections: # 2. 获取人脸置信度 confidence = detection.score[0] print(f"当前人脸置信度: {confidence:.2f}") # 3. 获取并转换人脸坐标为整数 # 读取归一化边界框数据 bbox = detection.location_data.relative_bounding_box # 转换为图像像素坐标(整数) x_min = int(bbox.xmin * img_width) y_min = int(bbox.ymin * img_height) bbox_width = int(bbox.width * img_width) bbox_height = int(bbox.height * img_height) # 计算人脸中心坐标(适合舵机追踪) face_center_x = x_min + bbox_width // 2 face_center_y = y_min + bbox_height // 2 print(f"人脸中心坐标(X,Y): ({face_center_x}, {face_center_y})") # 可选:绘制检测结果到图像上 mp_drawing.draw_detection(image, detection) # 显示画面(翻转后更符合直觉) cv2.imshow('人脸检测', cv2.flip(image, 1)) if cv2.waitKey(5) & 0xFF == 27: break cap.release() cv2.destroyAllWindows()
关键细节说明
- 人脸数量:直接通过
len(results.detections)获取,detections是所有检测到的人脸对象的列表。 - 置信度:每个
detection对象的score属性是一个包含单个浮点值的列表,取值范围0-1,值越高表示检测结果越可靠,取score[0]即可。 - 坐标转换:MediaPipe输出的是相对图像尺寸的归一化坐标(0到1之间),需要乘以图像实际的宽和高,再转换为整数。如果用于舵机追踪,推荐使用人脸中心坐标,避免边界框偏移导致追踪不准。
内容的提问来源于stack exchange,提问作者Fadi EID
相关产品推荐
相关产品推荐

