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

如何在ESP32 Cam的CameraWebServer示例中获取人脸检测坐标?

获取ESP32 Cam CameraWebServer示例中的人脸坐标

核心修改思路

CameraWebServer示例的人脸识别依赖ESP-IDF内置的face_detect组件,要获取人脸坐标,需直接解析检测结果结构体,并在正确的上下文里读取数据。

具体实现步骤

  1. 定位人脸检测核心逻辑
    找到示例中负责人脸检测的任务函数(通常是face_detect_task),或者在摄像头帧处理的代码段中,找到调用face_detect_run的位置——这是获取检测结果的入口。

  2. 解析人脸坐标结构体
    face_detect_run会返回face_detect_result_t类型的结果,其中包含:

    • face_count:检测到的人脸数量
    • faces:face_box_t数组,每个元素的x、y是人脸左上角坐标,width、height是人脸的宽和高
  3. 读取并输出坐标
    在检测到人脸的代码块中,添加坐标读取逻辑:

    face_detect_result_t detect_result;
    memset(&detect_result, 0, sizeof(detect_result));
    face_detect_run(&detect_result);
    
    if (detect_result.face_count > 0) {
        for (int i = 0; i < detect_result.face_count; i++) {
            int face_x = detect_result.faces[i].x;
            int face_y = detect_result.faces[i].y;
            int face_w = detect_result.faces[i].width;
            int face_h = detect_result.faces[i].height;
            
            // 串口打印坐标
            ESP_LOGI("FACE_INFO", "Face %d: x=%d, y=%d, w=%d, h=%d", i, face_x, face_y, face_w, face_h);
        }
    }
    
  4. 解决常见失效问题

    • 不要在WebServer的HTTP处理函数中直接调用face_detect_run,会阻塞响应线程;应在独立的人脸检测任务中,把坐标存入带互斥锁保护的全局变量,Web端读取全局变量即可。
    • 确保在摄像头帧(camera_fb_t)被释放前完成坐标解析,否则会出现内存非法访问导致的错误数据。
  5. Web端获取坐标(可选)
    新增一个HTTP接口返回坐标数据:

    // 全局变量+互斥锁
    int g_face_x = 0, g_face_y = 0, g_face_w = 0, g_face_h = 0;
    SemaphoreHandle_t face_mutex;
    
    // HTTP处理函数
    static esp_err_t face_coords_handler(httpd_req_t *req) {
        char resp_buf[128];
        xSemaphoreTake(face_mutex, portMAX_DELAY);
        snprintf(resp_buf, sizeof(resp_buf), 
                 "{\"x\":%d,\"y\":%d,\"width\":%d,\"height\":%d}", 
                 g_face_x, g_face_y, g_face_w, g_face_h);
        xSemaphoreGive(face_mutex);
    
        httpd_resp_set_type(req, "application/json");
        return httpd_resp_send(req, resp_buf, strlen(resp_buf));
    }
    
    // 注册接口
    httpd_uri_t face_coords_uri = {
        .uri       = "/face-coords",
        .method    = HTTP_GET,
        .handler   = face_coords_handler,
        .user_ctx  = NULL
    };
    httpd_register_uri_handler(server, &face_coords_uri);
    

内容的提问来源于stack exchange,提问作者Idan Mazor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:47:38