在Android中缩小位图



我正在尝试创建一个具有TensorFlow Lite模型的应用程序,用于识别手写数字。我创建了一个简单的画布供用户绘制,它返回用户绘制的任何内容的位图。位图的初始大小为523 x 1024,我正试图将其缩小到28 x 28以作为模型的输入。然而,缩小后的图像几乎到了无法识别的地步。

我甚至试着用https://stackoverflow.com/a/7468636/6712486但无济于事。附上屏幕截图以供参考缩小图像。未压缩图像

如有任何见解,我们将不胜感激。感谢

fun classify(bitmap: Bitmap) {
check(isInterpreterInitialized) {"TFLite interpreter is not initialised"}
val resizedImage = Bitmap.createScaledBitmap(bitmap, inputImageWidth, inputImageHeight, true)
val bitmapByteBuffer = resizedImage?.toByteBuffer()
getCompressedBitmap(bitmap)
bitmapByteBuffer?.let {
interpreter?.run(it, resultArray)
}
}

您在不保留可能导致问题的纵横比的情况下缩小了它。28*28像素真的是非常低分辨率的图像,所以你可能无法识别它。

我确信这是因为纵横比的缘故。保持纵横比-另外,试着逐渐减小宽度,直到无法辨认为止。下面是相应的java代码,试试这个:-

public static Bitmap resizeBitmapWithPreservedAspectRatio(Bitmap bmp,
int desiredWidth, int desiredHeight) {
Matrix mat = new Matrix();
float sx = (float) desiredWidth / bmp.getWidth();
float sy = (float) desiredHeight / bmp.getHeight();
if(desiredWidth>desiredHeight){
mat.postScale(sx, sx);
}else{
mat.postScale(sy, sy);
}
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(),
mat, false);
return bmp;
}
public static Bitmap resizeBitmapWithoutPreservingAspectRatio(Bitmap bmp,
int desiredWidth, int desiredHeight) {
Matrix mat = new Matrix();
float sx = (float) desiredWidth / bmp.getWidth();
float sy = (float) desiredHeight / bmp.getHeight();
mat.postScale(sx, sy);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(),
mat, false);
return bmp;
}

最新更新