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

在Coral Micro API中如何同时返回摄像头帧与检测结果?

实现方案:在Coral Micro camera_streaming_http示例中同时返回图像与运动检测结果

完全可行,你可以通过以下几种方式实现UriHandler同时返回图像帧和检测结果:

方法1:将检测结果嵌入图像后返回(可视化方案)

这种方式适合需要直接在画面中看到检测结果的场景,步骤如下:

  • 在获取摄像头帧后,先调用tensorflow::GetDetectionResults得到运动检测结果
  • 使用Coral Micro提供的图像绘制工具(或自行实现简单图形绘制逻辑),将检测框、结果文本直接绘制到当前帧的图像数据上
  • 最后将处理后的图像以原示例中的HttpServer::Content(JPEG格式)返回即可

示例代码片段:

HttpServer::Content MyUriHandler(HttpServer::Request request) {
  // 获取摄像头帧
  auto frame = GetCameraFrame();
  if (!frame) {
    return HttpServer::Content("text/plain", "Failed to get frame");
  }

  // 运行运动检测模型
  auto results = tensorflow::GetDetectionResults(frame->data, frame->width, frame->height);

  // 将检测结果绘制到图像上
  DrawDetectionResults(frame, results); // 需自行实现或调用现有绘制函数

  // 编码为JPEG并返回
  std::vector<uint8_t> jpeg_data;
  EncodeJpeg(frame, &jpeg_data);
  return HttpServer::Content("image/jpeg", jpeg_data);
}

方法2:返回包含图像Base64和检测结果的JSON(数据接口方案)

如果需要单独获取图像数据和结构化检测结果,可将两者打包成JSON返回:

  • 获取摄像头帧后,先运行检测模型得到结果
  • 将图像帧编码为JPEG,再转成Base64字符串
  • 把检测结果(如检测框坐标、置信度等)和Base64图像字符串组合成JSON结构
  • 返回application/json类型的HttpServer::Content

示例代码片段:

HttpServer::Content MyUriHandler(HttpServer::Request request) {
  auto frame = GetCameraFrame();
  if (!frame) {
    return HttpServer::Content("text/plain", "Failed to get frame");
  }

  // 运行检测模型
  auto results = tensorflow::GetDetectionResults(frame->data, frame->width, frame->height);

  // 图像转Base64
  std::vector<uint8_t> jpeg_data;
  EncodeJpeg(frame, &jpeg_data);
  std::string base64_image = Base64Encode(jpeg_data); // 需实现Base64编码函数

  // 构建JSON
  std::string json_str = "{\"image\":\"" + base64_image + "\",\"detection_results\":[";
  for (const auto& result : results) {
    json_str += "{\"x\":" + std::to_string(result.x) + ",\"y\":" + std::to_string(result.y) +
                ",\"width\":" + std::to_string(result.width) + ",\"height\":" + std::to_string(result.height) +
                ",\"confidence\":" + std::to_string(result.confidence) + "},";
  }
  if (!results.empty()) json_str.pop_back(); // 移除最后一个逗号
  json_str += "]}";

  return HttpServer::Content("application/json", json_str);
}

方法3:返回Multipart混合内容(适合多类型数据分离)

通过HTTP的multipart格式,将图像和检测结果作为两个独立的部分返回:

  • 构建multipart边界字符串,分别添加图像部分(image/jpeg类型)和检测结果部分(application/json类型)
  • 将组合后的multipart数据作为multipart/form-data类型的HttpServer::Content返回

注意:这种方式需要处理multipart的格式细节,比如边界分隔、内容头设置,适合对HTTP协议熟悉的场景。

关键注意事项

  • 确保在同一帧上运行检测和返回图像,避免帧更新导致数据不匹配
  • 注意内存使用:Coral Micro资源有限,处理图像和模型推理时要避免内存泄漏
  • 根据实际需求选择合适的返回格式,可视化方案适合前端直接展示,JSON方案适合后端数据处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:52:36