You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过MediaPipe判断摄像头前是否存在多张人脸

解决MediaPipe人脸检测中多脸识别与坐标稳定问题

核心解决方案:直接获取人脸数量

你完全不需要靠坐标差值来判断是否有多张人脸——MediaPipe返回的results.detections是一个包含所有检测结果的列表,列表的长度就是当前画面中的人脸总数,这是最精准的判断方式,没有阈值界定的问题。

代码修改步骤

  1. 获取人脸数量:在检测到人脸的代码块中,先计算results.detections的长度;
  2. 分场景处理:
    • 当人脸数大于1时,向单片机发送多脸提示信号;
    • 当人脸数为1时,正常提取鼻子X坐标发送;
    • 可选优化:多脸时优先选择置信度最高的人脸,避免坐标来回波动。

修改后的完整代码

# face detection
import cv2
import mediapipe as mp

mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils

# capture video
cap = cv2.VideoCapture(0)

with mp_face_detection.FaceDetection(model_selection=1, min_detection_confidence=0.65) as face_detection:
    while True:
        success, image = cap.read()
        if not success:
            print("Ignoring empty camera frame.")
            break

        # Convert the BGR image to RGB.
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image.flags.writeable = False
        results = face_detection.process(image)

        # Draw the face detection annotations on the image.
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        
        if results.detections:
            # 获取当前人脸总数
            face_count = len(results.detections)
            print(f"当前人脸数量: {face_count}")

            # 绘制所有检测到的人脸
            for detection in results.detections:
                mp_drawing.draw_detection(image, detection)

            if face_count > 1:
                # 多脸场景:向单片机发送多脸提示(示例:打印标识,实际替换为串口发送代码)
                print("发送给单片机:多脸存在")
                
                # 可选:提取置信度最高的人脸坐标,避免波动
                sorted_detections = sorted(results.detections, key=lambda d: d.score[0], reverse=True)
                best_detection = sorted_detections[0]
                best_x = best_detection.location_data.relative_bounding_box.xmin
                print(f"同时发送最高置信度人脸X坐标: {best_x}")
            else:
                # 单脸场景:提取鼻子X坐标并发送
                detection = results.detections[0]
                x = detection.location_data.relative_bounding_box.xmin
                print(f"发送给单片机:单脸X坐标: {x}")

        cv2.imshow('BlazeFace Face Detection', image)
        if cv2.waitKey(5) & 0xFF == 27:
            break
cap.release()
cv2.destroyAllWindows()  # 补充释放窗口资源

关键说明

  • results.detections的长度直接对应人脸数量,完全可靠;
  • 多脸时按置信度排序选最优人脸,能避免坐标在不同人脸间跳变;
  • 串口发送部分只需把示例中的print替换为你的串口通信代码即可(比如使用pyserial库的serial.write())。

内容的提问来源于stack exchange,提问作者Fadi EID

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:31:06