Languages
[Edit]
EN

Java - find differences on two images (absolute difference)

5 points
Created by:
Suzannah-Estrada
620

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:

Calculated absolute subtraction on two images using Java.
Calculated absolute subtraction on two images using Java.

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:

a.png file.

b.png file:

b.png file.

 

See also

  1. Java - find differences on two images (inverted absolute difference)

Alternative titles

  1. Java - subtract two images (absolute subtraction)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join