這個問題本身是不言自明的。在 Python 中,使用 tf.expand_dims(image, 0) 很容易做到這一點。我如何在 Android 中做同樣的事情?我在運行我準備的 tensorflow 模型時出錯。它說,
無法從具有Y位元組的 Java 緩沖區復制到具有X位元組的 TensorFlowLite 張量 (input_3) 。
我猜它來自影像的少一維。我已經運行了另一個作業正常的模型。所以我需要知道如何做到這一點。我的代碼片段:
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
}
uj5u.com熱心網友回復:
TensorFlow API 中有 JVM/Android 等效操作:https ://www.tensorflow.org/jvm/api_docs/java/org/tensorflow/op/core/ExpandDims 。
但是,如果您使用 TfLite Interpreter API 在預訓練模型上運行推理,那么您很可能希望在構建和保存模型時(即使用 Python)而不是在呼叫解釋器時處理陣列維度來自安卓代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371400.html
