4. 使用TensorFlow Lite for Microcontrollers的A

任务目标

本案例要求编写一段完整的C++代码,调用TensorFlow Lite for Microcontrollers(TFLM)的公开API,完成以下闭环:加载一个已转换的TFLite模型、设置输入张量、执行一次推理、读取输出张量。代码需可直接编译运行于PC仿真环境(Linux/macOS),不依赖特定硬件平台。

环境与依赖

  • TensorFlow Lite Micro源码(含示例模型):git clone https://github.com/tensorflow/tflite-micro.git
  • CMake ≥ 3.16,以及C++11编译器
  • 模型文件:使用TFLM仓库自带的models/person_detect.tflite(无需额外下载)

关键完整代码

以下代码位于tflite-micro/examples/person_detection/main.cc,为最小可运行实现。它使用TFLM的MicroInterpreter加载模型,分配张量内存,执行推理并读取输出分数。

#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/system_setup.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "models/person_detect_model_data.h"

constexpr int kTensorArenaSize = 200 * 1024;
uint8_t tensor_arena[kTensorArenaSize];

// 模拟输入:全零图像(8x8灰度,共64像素)
constexpr int kInputSize = 64;
uint8_t input_data[kInputSize] = {0};

void setup() {
  tflite::InitializeTarget();
}

void loop() {
  // 1. 加载模型
  const tflite::Model* model = tflite::GetModel(g_person_detect_model_data);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    return;
  }

  // 2. 注册算子(此处使用全部算子,便于演示)
  static tflite::AllOpsResolver resolver;

  // 3. 构建解释器
  static tflite::MicroInterpreter static_interpreter(
      model, resolver, tensor_arena, kTensorArenaSize);
  tflite::MicroInterpreter* interpreter = &static_interpreter;

  // 4. 分配张量内存
  if (interpreter->AllocateTensors() != kTfLiteOk) {
    return;
  }

  // 5. 获取输入张量并填充数据
  TfLiteTensor* input = interpreter->input(0);
  memcpy(input->data.uint8, input_data, kInputSize);

  // 6. 执行推理
  if (interpreter->Invoke() != kTfLiteOk) {
    return;
  }

  // 7. 读取输出(person_detect模型输出2个分数:无人物/有人物)
  TfLiteTensor* output = interpreter->output(0);
  uint8_t no_person_score = output->data.uint8[0];
  uint8_t person_score = output->data.uint8[1];

  // 8. 打印结果(仅用于验证)
  printf("no_person: %u, person: %u\n", no_person_score, person_score);

  // 演示用:只执行一次
  while (true) {}
}

编译与运行

cd tflite-micro
mkdir -p build && cd build
cmake -DTFLM_COPY_HOST_TEST_DATA=ON ..
make person_detection
./examples/person_detection/person_detection

验证方法与判定标准

  • 编译通过:上述cmake/make命令无错误退出。
  • 运行输出:程序打印一行no_person: X, person: Y,其中X和Y为0~255的整数。
  • 功能正确性判定:由于输入为全零图像,模型输出应满足person_score < no_person_score(即模型判断图像中没有人)。若输出符合此逻辑,说明API调用链路(加载→分配→推理→读取)完整工作。

常见问题

  • 链接错误:若提示找不到person_detect_model_data.h,需确认已执行git submodule update --init拉取模型子模块。
  • 张量内存不足:若AllocateTensors返回错误,增大kTensorArenaSize至256KB。
  • 算子缺失:若使用MicroMutableOpResolver替代AllOpsResolver,需手动添加AddConv2D()、AddDepthwiseConv2D()等模型所需算子。