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

Android运行TFLite模型报错:字节缓冲区大小与形状不匹配

问题根源

你遇到的字节缓冲区与形状不匹配报错,核心是三个错误逻辑导致的:

  • 你通过bitmap.compress得到的是PNG压缩格式的二进制数据,并非模型要求的逐像素原始RGB浮点值。你的模型输入要求为[1,180,180,3]的FLOAT32张量,对应的字节数固定为 1*180*180*3*4 = 388800 字节,压缩后的PNG字节数远小于该值,必然不匹配。
  • 你加载的原始Bitmap未做尺寸缩放,无法保证尺寸为180*180。
  • 你没有对像素值做归一化处理,你使用的图像分类训练教程中,训练数据是将像素值除以255归一化到0~1区间后输入模型的,直接传入原始像素值会导致推理精度完全错误。

修复方案

推荐使用TensorFlow Lite Support库提供的TensorImage工具类处理图片输入,避免手动写转换逻辑出错,修正后的代码如下:

val model = ConvertedModel.newInstance(requireContext())
val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 180, 180, 3), DataType.FLOAT32)

// 加载Bitmap并缩放至180*180,统一转成ARGB_8888格式
val originalBitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, data?.data!!))
val resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, 180, 180, true)
    .copy(Bitmap.Config.ARGB_8888, false)

// 使用TensorImage做格式转换和归一化
val tensorImage = TensorImage(DataType.FLOAT32)
tensorImage.load(resizedBitmap)
val floatArray = tensorImage.tensorBuffer.floatArray
// 归一化到0~1区间,和训练逻辑对齐
for (i in floatArray.indices) {
    floatArray[i] = floatArray[i] / 255f
}
inputFeature0.loadArray(floatArray)

val outputs = model.process(inputFeature0)
val outputFeature0 = outputs.outputFeature0AsTensorBuffer
model.close()

如果你的项目没有引入TFLite Support库,需要在模块级build.gradle中添加依赖:

dependencies {
    implementation 'org.tensorflow:tensorflow-lite-support:0.4.4'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:39:03