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

Flutter实时目标检测:TFLite模型输出形状不匹配问题求助

解决Flutter中TFLite实时目标检测的输出形状不匹配问题

我在Flutter中使用tflite_flutter库实现实时目标检测,通过Teachable Machine训练图像并导出模型后,集成时出现如下错误:
E/flutter ( 8569): Invalid argument(s): Output object shape mismatch, interpreter returned output of shape: [1, 2] while shape of output provided as argument in run is: [1, 10, 4]

问题核心原因

当前代码是为SSD MobileNet这类目标检测模型编写的,但从Teachable Machine导出的是图像分类模型,两者输出结构完全不同:

  • SSD模型输出包含多组检测框坐标、类别ID、置信度等,对应代码中预设的[1,10,4]这类复杂形状
  • Teachable Machine导出的分类模型仅输出[1, N]形状的结果,N为训练的类别数量(此处为2类,因此输出形状是[1,2])

具体修改步骤

1. 调整模型输入预处理参数

Teachable Machine默认导出的分类模型输入尺寸为224x224,且需要将像素值归一化到[0,1]范围:

class _DetectorServer {
  // 替换原有的300为224
  static const int mlModelInputSize = 224;
  static const double confidence = 0.5;
  
  // ... 其他代码不变
  
  // 生成图像矩阵时添加归一化处理
  final imageMatrix = List.generate(
    imageInput.height,
    (y) => List.generate(
      imageInput.width,
      (x) {
        final pixel = imageInput.getPixel(x, y);
        // 将RGB值归一化到0-1区间
        return [pixel.r / 255.0, pixel.g / 255.0, pixel.b / 255.0];
      },
    ),
  );
}

2. 重写推理输出处理逻辑

完全替换原有的_runInference方法和输出解析代码,适配分类模型的单输出结构:

// 替换原有的_runInference方法
List<List<double>> _runInference(
  List<List<List<num>>> imageMatrix,
) {
  final input = [imageMatrix];
  // 分类模型仅一个输出,形状为[1, 类别数量]
  final output = List<List<double>>.filled(1, List<double>.filled(_labels!.length, 0));
  
  _interpreter!.run(input, output);
  return output;
}

// 替换analyseImage中从推理到生成recognitions的代码
Map<String, dynamic> analyseImage(
    image_lib.Image? image, int preConversionTime) {
  // ... 预处理代码不变
  
  final output = _runInference(imageMatrix);
  // 获取所有类别的置信度
  final confidenceScores = output.first;

  // 找出置信度最高的类别
  int topClassIndex = 0;
  double maxConfidence = 0;
  for (int i = 0; i < confidenceScores.length; i++) {
    if (confidenceScores[i] > maxConfidence) {
      maxConfidence = confidenceScores[i];
      topClassIndex = i;
    }
  }

  List<Recognition> recognitions = [];
  if (maxConfidence > confidence) {
    String label = _labels![topClassIndex];
    // 分类模型无检测框,此处用整个图像区域作为结果范围
    Rect fullImageRect = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
    recognitions.add(Recognition(0, label, maxConfidence, fullImageRect));
  }
  
  // ... 统计时间的代码不变
  return {
    "recognitions": recognitions,
    "stats": <String, String>{
      // ... 原有统计项不变
    },
  };
}

3. 验证标签文件一致性

确保labelmap.txt中的类别数量与模型输出维度一致,每行对应一个类别,示例:

猫
狗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:44:49