EN
Java - find differences on two images (absolute difference)
5
points
In this short article, we would like to show how to find differences on two images using Java.
To find differences on two images it is good to use absolute subtraction on two images. Let's suppose we have 2 images: A
and B
. The result image (C
image) may be calculated using fomula: |B - A| = C
.
Operation visualization:
Result interpretation:
Black colors mean: pixels do not have difference. White colors mean: pixels are totally different. Middle colors mean: there is some difference (smaller in direction to black, bigger in direction to white).
Note: to reverse colors (from white to black) we can use fomula:
255 - |B - A| = C
what was presented in this article.
Practical example:
package com.example;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Program {
public static void main(String[] args) throws IOException {
BufferedImage aImage = ImageIO.read(new File("a.png")); // A image (input image)
BufferedImage bImage = ImageIO.read(new File("b.png")); // B image (input image)
int aWidth = aImage.getWidth();
int aHeight = aImage.getHeight();
if (aWidth != bImage.getWidth() || aHeight != bImage.getHeight()) {
throw new IOException("Input images doesn't have the same size.");
}
BufferedImage cImage = new BufferedImage(aWidth, aHeight, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < aHeight; ++y) {
for (int x = 0; x < aWidth; ++x) {
Color aColor = new Color(aImage.getRGB(x, y));
Color bColor = new Color(bImage.getRGB(x, y));
Color cColor = new Color(Math.abs(bColor.getRed() - aColor.getRed()), Math.abs(bColor.getGreen() - aColor.getGreen()), Math.abs(bColor.getBlue() - aColor.getBlue()));
cImage.setRGB(x, y, cColor.getRGB());
}
}
ImageIO.write(cImage, "PNG", new File("c.png")); // C image (output image)
}
}
Used resources
a.png
file:
b.png
file: