Languages
[Edit]
EN

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

11 points
Created by:
Explosssive
559

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 with inversion on two images. Let's suppose we have 2 images: A and B. The result image (C image) may be calculated using fomula: 255 - |B - A| = C.

Operation visualization:

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

Result interpretation:

White colors mean: pixels do not have difference. Black colors mean: pixels are totally different. Middle colors mean: there is some difference (smaller in direction to white, bigger in direction to black).

 

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(255 - Math.abs(bColor.getRed() - aColor.getRed()), 255 - Math.abs(bColor.getGreen() - aColor.getGreen()), 255 - 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 (absolute difference)

Alternative titles

  1. Java - subtract two images (inverted absolute subtraction)
  2. Java - subtract two images (negative absolute subtraction)
  3. Java - find differences on two images (negative absolute difference)
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