【发布时间】:2018-08-25 18:57:07
【问题描述】:
我正在尝试在我的 android 应用程序中使用 tflite 模型。当我必须从位图创建一个 ByteBuffer 并将其用作模型的输入时,就会出现问题。
问题:位图是 ARGB_8888(32 位),而我需要(8 位)灰度图像。
Bitmap转ByteBuffer的方法:
mImgData = ByteBuffer
.allocateDirect(4 * 28 * 28 * 1);
private void convertBitmapToByteBuffer(Bitmap bitmap) throws NullPointerException {
if (mImgData == null) {
throw new NullPointerException("Error: ByteBuffer not initialized.");
}
mImgData.rewind();
for (int i = 0; i < DIM_IMG_SIZE_WIDTH; i++) {
for (int j = 0; j < DIM_IMG_SIZE_HEIGHT; j++) {
int pixelIntensity = bitmap.getPixel(i, j);
unpackPixel(pixelIntensity, i, j);
Log.d(TAG, String.format("convertBitmapToByteBuffer: %d -> %f", pixelIntensity, convertToGrayScale(pixelIntensity)));
mImgData.putFloat(convertToGrayScale(pixelIntensity));
}
}
}
private float convertToGrayScale(int color) {
return (((color >> 16) & 0xFF) + ((color >> 8) & 0xFF) + (color & 0xFF)) / 3.0f / 255.0f;
}
但是,所有像素值都是 -1 或 -16777216。请注意,here 提到的 unpackPixel 方法不起作用,因为无论如何所有值都具有相同的 int 值。 (张贴以下更改以供参考。)
private void unpackPixel(int pixel, int row, int col) {
short red,green,blue;
red = (short) ((pixel >> 16) & 0xFF);
green = (short) ((pixel >> 8) & 0xFF);
blue = (short) ((pixel >> 0) & 0xFF);
}
【问题讨论】: