我使用 Tensorflow 构建了一个图像分类器,并使用 Android Tensorflow 库在 Android 上运行。我的问题是,在 Android 上对图像进行分类时,预测的类别完全错误。但是,当使用具有相同模型的 Python 对图像进行分类时,预测的类别是正确的。
下面的方法是我如何将位图转换为 RGB 像素值数组。(我从 sample-tensorflow-imageclassifier 和 here 获取)。
public static float[] getPixels(Bitmap bitmap) {
final int IMAGE_SIZE = 168;
int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];
float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];
if (bitmap.getWidth() != IMAGE_SIZE || bitmap.getHeight() != IMAGE_SIZE) {
// rescale the bitmap if needed
bitmap = ThumbnailUtils.extractThumbnail(bitmap, IMAGE_SIZE, IMAGE_SIZE);
}
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < intValues.length; ++i) {
final int val = intValues[i];
// bitwise shifting - without our image is shaped [1, 168, 168, 1] but we need [1, 168, 168, 3]
floatValues[i * 3] = Color.red(val);
floatValues[i * 3 + 1] = Color.green(val);
floatValues[i * 3 + 2] = Color.blue(val);
}
return floatValues;
}
我尝试将从 getPixels(bitmap:Bitmap) 接收到的浮点像素数组转换回位图,并注意到颜色有所不同,所以我猜测这就是问题所在?有没有办法在不丢失颜色信息的情况下转换像素?
附件是原始图像和我应用上述函数后转换回来的图像。
Image converted with above method
任何帮助将不胜感激。
最佳答案
事实证明,RGB channel 被 Bitmap.getPixels 反转,因此更改为 BGR 有效。
floatValues[i * 3 + 2] = Color.red(val);
floatValues[i * 3 + 1] = Color.green(val);
floatValues[i * 3] = Color.blue(val);
关于Android/Tensorflow 将 Bitmap.getPixels 转换为 RGB 像素值会导致颜色不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571112/