Highlight differences between images

前端 未结 2 1122
迷失自我
迷失自我 2020-12-31 17:28

There is this image comparison code I am supposed to modify to highlight/point out the difference between two images. Is there a way to modify this code so as to highlight t

2条回答
  •  星月不相逢
    2020-12-31 17:44

    This solution did the trick for me. It highlights differences, and has the best performance out of the methods I've tried. (Assumptions: images are the same size. This method hasn't been tested with transparencies.)

    Average time to compare a 1600x860 PNG image 50 times (on same machine):

    • JDK7 ~178 milliseconds
    • JDK8 ~139 milliseconds

    Does anyone have a better/faster solution?

    public static BufferedImage getDifferenceImage(BufferedImage img1, BufferedImage img2) {
        // convert images to pixel arrays...
        final int w = img1.getWidth(),
                h = img1.getHeight(), 
                highlight = Color.MAGENTA.getRGB();
        final int[] p1 = img1.getRGB(0, 0, w, h, null, 0, w);
        final int[] p2 = img2.getRGB(0, 0, w, h, null, 0, w);
        // compare img1 to img2, pixel by pixel. If different, highlight img1's pixel...
        for (int i = 0; i < p1.length; i++) {
            if (p1[i] != p2[i]) {
                p1[i] = highlight;
            }
        }
        // save img1's pixels to a new BufferedImage, and return it...
        // (May require TYPE_INT_ARGB)
        final BufferedImage out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        out.setRGB(0, 0, w, h, p1, 0, w);
        return out;
    }
    

    Usage:

    import javax.imageio.ImageIO;
    import java.io.File;
    
    ImageIO.write(
            getDifferenceImage(
                    ImageIO.read(new File("a.png")),
                    ImageIO.read(new File("b.png"))),
            "png",
            new File("output.png"));
    

    Some inspiration...

提交回复
热议问题