How compare function marks differences on resulting picture?
Posted: 2012-09-15T16:28:10-07:00
I am trying to write a function in Java that would perform basic image comparison and produce resulting image similar to the one produced by compare.exe. I want my function to be simple, covering the functionality of "compare.exe 1.png 2.png result.png". So nothing complicated. Actually I have the code already but I cannot figure out how the color of red pixels (difference marks) is calculated. I tried going through IM source code but I couldn't understand it. :/ Here's what I've got so far:
Can anyone point me how to calculate newrgb value when a difference is found? I would like to achieve similar (doesn't have to be identical) to original ImageMagick's compare.exe. If possible I would like to avoid RGB->HSL->RGB conversions.
Also I would appreciate any comments on how to optimize the above code. It's already faster than original compare but maybe there is some room for additional tweaks.
Code: Select all
public void compare(String path1, String path2, String resultPath) throws Exception
{
File file1 = new File(path1);
File file2 = new File(path2);
File file3 = new File(resultPath);
BufferedImage image1 = ImageIO.read(file1);
BufferedImage image2 = ImageIO.read(file2);
int columns = image1.getWidth();
int rows = image1.getHeight();
BufferedImage image3 = new BufferedImage(columns, rows, BufferedImage.TYPE_INT_RGB);
int rgb; int rgb2; int newrgb; int r; int g; int b;
for (int row=0; row<rows; row++)
{
for (int col=0; col<columns; col++)
{
rgb = image1.getRGB(col, row);
rgb2= image2.getRGB(col, row);
r = (rgb >> 16) & 0x000000FF;
g = (rgb >> 8) & 0x000000FF;
b = rgb & 0x000000FF;
if (rgb == rgb2)
{
r += (int)((255 - r) * 0.8);
g += (int)((255 - g) * 0.8);
b += (int)((255 - b) * 0.8);
newrgb = (r << 16) | (g << 8) | b;
}
else
{
newrgb = 0x00FF0000 | rgb; //THE PROBLEM IS HERE. HOW SHOULD I CALCULATE IT?
}
image3.setRGB(col, row, newrgb);
}
}
ImageIO.write(image3, "png", file3);
}
Also I would appreciate any comments on how to optimize the above code. It's already faster than original compare but maybe there is some room for additional tweaks.