张量流精简版中的灰度

时间:2020-07-16 14:45:52

标签: android tensorflow keras tensorflow2.0 tensorflow-lite

我正在尝试在具有灰度输入的android设备中实现tensorflow lite模型,但是我发现的大多数文档都使用rgb输入。是否有任何示例如何在带有灰度图像的android中使用tflite文件?还​​是不支持该文件?

1 个答案:

答案 0 :(得分:0)

这是我将RGB位图直接转换为相应的灰度字节缓冲区的方式:

private ByteBuffer getByteBuffer(Bitmap bitmap){
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    ByteBuffer mImgData = ByteBuffer
            .allocateDirect(4 * width * height);
    mImgData.order(ByteOrder.nativeOrder());
    int[] pixels = new int[width*height];
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int pixel : pixels) {
        mImgData.putFloat((float) Color.red(pixel));
    }
    return mImgData;
}

如果需要归一化的值[0,1],请除以255.0:

float value = (float) Color.red(pixel)/255.0f;
mImgData.putFloat(value);

然后您可以在解释器中使用以下代码:

ByteBuffer input = getByteBuffer(bitmap);
tflite.run(input, outputValue);

P.S。我也得到BufferOverflowException,因为我正在从可绘制对象解码28x28图像,由于dpi转换,该图像已被调整为56x56。我将其放在drawable-nodpi中,然后它可以正常工作。确保您的图片尺寸合适。