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

Android部署TensorFlow Lite模型遇ByteBuffer与形状不匹配错误求助

错误原因及解决办法

错误原因

你遇到的The size of byte buffer and the shape do not match异常,核心问题是输入TensorBuffer的数据类型与Bitmap转换后的TensorBuffer数据类型不匹配,导致字节总数计算不一致:

  • 你创建的inputFeature0是DataType.FLOAT32类型,每个元素占4字节,对应shape[1,416,416,3]的总字节数为 1*416*416*3*4 = 2076672
  • 而TensorImage.fromBitmap(bitmap)默认生成的是DataType.UINT8类型(每个元素占1字节),总字节数为 1*416*416*3*1 = 519168
    两者字节数相差4倍,加载时自然触发不匹配的异常。

解决办法

提供两种可行的修复方案,根据你的模型输入要求选择:

方案一:统一使用UINT8数据类型

直接将创建TensorBuffer的类型改为UINT8,和Bitmap转换后的格式保持一致:

// 修改TensorBuffer的数据类型为UINT8
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 416, 416, 3}, DataType.UINT8);

bitmap = Bitmap.createScaledBitmap(bitmap,416,416,true);
// 直接加载UINT8格式的buffer
inputFeature0.loadBuffer(TensorImage.fromBitmap(bitmap).getBuffer());

方案二:将Bitmap转换为FLOAT32格式并归一化

如果你的YOLOv4-tiny模型要求输入是归一化后的FLOAT32数据(通常是0-1或-1到1范围),需要先对TensorImage做格式转换和归一化处理:

TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 416, 416, 3}, DataType.FLOAT32);

bitmap = Bitmap.createScaledBitmap(bitmap,416,416,true);
TensorImage tensorImage = TensorImage.fromBitmap(bitmap);

// 添加归一化处理器,将UINT8的0-255转换为FLOAT32的0-1
ImageProcessor processor = new ImageProcessor.Builder()
        .add(new NormalizeOp(0.0f, 255.0f)) // 如果模型要求-1到1,改成NormalizeOp(127.5f, 127.5f)
        .build();
tensorImage = processor.process(tensorImage);

// 加载转换后的FLOAT32 buffer
inputFeature0.loadBuffer(tensorImage.getBuffer());

额外注意事项

  • 确认你的YOLOv4-tiny模型的输入要求:有些模型训练时用的是UINT8输入,有些是归一化后的FLOAT32,需要和训练时的预处理逻辑保持一致。
  • 每次点击按钮都重新创建模型实例Yolov4Tiny416.newInstance()会消耗较多资源,建议将模型实例移到按钮点击外部,初始化一次即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:09:29