【发布时间】:2022-01-06 05:13:03
【问题描述】:
问题本身是不言自明的。在 Python 中,使用 tf.expand_dims(image, 0) 非常简单。我怎样才能在 Android 中做同样的事情? 我在运行我准备的 tensorflow 模型时遇到错误。它说,
无法复制到具有 X 个字节的 TensorFlowLite 张量 (input_3) Y 个字节的 Java 缓冲区。
我猜它来自图像的少一维。我运行了另一个运行良好的模型。所以我需要知道如何做到这一点。 我的代码sn-p:
val contentArray =
ImageUtils.bitmapToByteBuffer(
scaledBitmap,
imageSize,
imageSize,
IMAGE_MEAN,
IMAGE_STD
)
val tfliteOptions = Interpreter.Options()
tfliteOptions.setNumThreads(4)
val tflite = Interpreter(tfliteModel, tfliteOptions)
tflite.run(contentArray, segmentationMasks)
fun bitmapToByteBuffer(
bitmapIn: Bitmap,
width: Int,
height: Int,
mean: Float = 0.0f,
std: Float = 255.0f
): ByteBuffer {
val bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height)
val inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4)
inputImage.order(ByteOrder.nativeOrder())
inputImage.rewind()
val intValues = IntArray(width * height)
bitmap.getPixels(intValues, 0, width, 0, 0, width, height)
var pixel = 0
for (y in 0 until height) {
for (x in 0 until width) {
val value = intValues[pixel++]
// Normalize channel values to [-1.0, 1.0]. This requirement varies by
// model. For example, some models might require values to be normalized
// to the range [0.0, 1.0] instead.
inputImage.putFloat(((value shr 16 and 0xFF) - mean) / std)
inputImage.putFloat(((value shr 8 and 0xFF) - mean) / std)
inputImage.putFloat(((value and 0xFF) - mean) / std)
}
}
inputImage.rewind()
return inputImage
}
【问题讨论】:
-
这里你用 ByteBuffer 喂食。您不需要扩展维度。请粘贴 ImageUtils.bitmapToByteBuffer 的代码以查看过程。
-
我已经编辑了这个问题。你能检查一下吗?
-
如您所见,字节缓冲区为 (1 * width * height * 3 * 4)。您不能在其中扩展维度。那么您的模型期望作为输入的是什么?您可以将其上传到某个地方以使用 netron.app 进行查看吗?
-
我发现我的模型需要图像列表作为输入。
标签: android tensorflow tensorflow-lite