问题
I need to calculate pixel difference between two images in java on Android. The problem is that I have code that return inaccurate result.
E.g. I have 3 very similar pictures but it returns significantly different results for comparison of each of them: pic1 vs pic2 = 1.71%; pic1 vs pic3 = 0.0045%; pic2 vs pic3 = 36.7%.
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
opt.inSampleSize = 5;
Bitmap mBitmap1 = BitmapFactory.decodeFile("/sdcard/pic1.jpg", opt);
Bitmap mBitmap2 = BitmapFactory.decodeFile("/sdcard/pic2.jpg", opt);
int intColor1 = 0;
int intColor2 = 0;
for (int x = 0; x < mBitmap1.getWidth(); x++) {
for (int y = 0; y < mBitmap1.getHeight(); y++) {
intColor1 = mBitmap1.getPixel(x, y);
intColor2 = mBitmap2.getPixel(x, y);
//System.out.print(" ("+ x + ","+ y +") c:" + intColor1);
}
String resultString = String.valueOf(intColor1);
}
//now calculate percentage difference
double razlika = (((double)intColor1 - intColor2)/intColor2)*100;
}
I think that I need to compare each pixel for both images (intColor1(x,y) vs intColor2(x,y)), but how I can do that, and to later calculate percentage difference?
回答1:
The percentage formula that you're using is wrong. For example, #333333 is almost identical to #333332 (and your formula shows they're 0.003% different). Also #323333 is almost identical to #333333, but your formula shows they're 3% different.
You should extract each composing bit of each color pixel (Color.red() , Color.green(), Color.blue() ), calculate the difference of each of them, and then get the combined difference percentage.
While this method of getting the difference of the two images is simple and efficient, it has a big caveat: if the images are identical in content but shifted by one pixel (to the right for example), your method will show them as completely different.
来源:https://stackoverflow.com/questions/9170488/android-java-percentage-bitmap-pixel-difference-between-two-images