位图仅保留整数值(0-255)。我需要将每个像素值除以255。将位图转换为TensorImage,然后在将其传递到预测输出的解释器时调用getBuffer()。(tflite.run())在中间的某个地方,我必须将每个RGB像素除以255。恐怕还有另一个缺点,因为getBuffer()函数返回一个字节缓冲区。我找不到有关TensorFlow精简功能的大量文档。所以我不确定tflite.run()是否只能接受字节缓冲区。我正在用Java编程,对Android AppD还是陌生的。请帮助,因为此归一化对于预测正确的值至关重要。
这里是在调整大小后将位图转换为张量图像的代码。在这里,我需要将每个像素值除以255,但很困难。
private TensorImage resizePic(Bitmap bp) {
ImageProcessor imageProcessor =
new ImageProcessor.Builder()
.add(new ResizeOp(60, 60, ResizeOp.ResizeMethod.BILINEAR))
.build();
TensorImage tImage = new TensorImage(DataType.FLOAT32);
tImage.load(bp);
tImage = imageProcessor.process(tImage);
return tImage;
}
这里是运行模型的行
tflite.run(tImage.getBuffer(), probabilityBuffer.getBuffer());
probabilityBuffer保存输出。
我能够使用以下链接构造合适的功能-
第二个链接在Kotlin中。这是代码:
private ByteBuffer convertBitmapToByteBuffer(Bitmap bp) {
ByteBuffer imgData = ByteBuffer.allocateDirect(Float.BYTES*60*60*3);
imgData.order(ByteOrder.nativeOrder());
Bitmap bitmap = Bitmap.createScaledBitmap(bp,60,60,true);
int [] intValues = new int[60*60];
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the image to floating point.
int pixel = 0;
for (int i = 0; i < 60; ++i) {
for (int j = 0; j < 60; ++j) {
final int val = intValues[pixel++];
imgData.putFloat(((val>> 16) & 0xFF) / 255.f);
imgData.putFloat(((val>> 8) & 0xFF) / 255.f);
imgData.putFloat((val & 0xFF) / 255.f);
}
}
return imgData;
}
这里,我输入的图像高度和宽度是60。另外,此方法不需要使用TensorImage。因此,tflite.run()的最终调用如下所示:
tflite.run(convertBitmapToByteBuffer(bp), probabilityBuffer.getBuffer());
这里,bp是位图图像。