java:获取两个图像之间的差异

时间:2014-05-08 09:23:07

标签: java image-processing bufferedimage

我试图在两张图片(相同尺寸)之间找到差异,我找到了这段代码:

            BufferedImage img1 = null;
            BufferedImage img2 = null;

            try{            
                URL url1 = new URL("http://rosettacode.org/mw/images/3/3c/Lenna50.jpg");
                URL url2 = new URL("http://rosettacode.org/mw/images/b/b6/Lenna100.jpg");
                img1 = ImageIO.read(url1);
                img2 = ImageIO.read(url2);
             } catch (IOException e) {
                e.printStackTrace();
             }
             int width1 = img1.getWidth(null);
             int width2 = img2.getWidth(null);
             int height1 = img1.getHeight(null);
             int height2 = img2.getHeight(null);

             if ((width1 != width2) || (height1 != height2)) {
                 System.err.println("Error: Images dimensions mismatch");
                 System.exit(1);
             }

             long diff = 0;
             for (int i = 0; i < height1; i++) {
                 for (int j = 0; j < width1; j++) {
                     int rgb1 = img1.getRGB(i, j);
                     int rgb2 = img2.getRGB(i, j);
                     int r1 = (rgb1 >> 16) & 0xff;
                     int g1 = (rgb1 >>  8) & 0xff;
                     int b1 = (rgb1      ) & 0xff;
                     int r2 = (rgb2 >> 16) & 0xff;
                     int g2 = (rgb2 >>  8) & 0xff;
                     int b2 = (rgb2      ) & 0xff;
                     diff += Math.abs(r1 - r2);
                     diff += Math.abs(g1 - g2);
                     diff += Math.abs(b1 - b2);
                 }
             }
             double n = width1 * height1 * 3;
             double p = diff / n / 255.0;
             System.out.println("diff percent: " + (p * 100.0));    `

它适用于网址中给出的两个图像,但是当我更改给定的图像时,我得到了这个例外:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:299)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:871)
at Main.main(Main.java:77)

我将代码更改为:

          File sourceimage1 = new File("C:\\lo.jpg");
          File sourceimage2 = new File("C:\\lo1.jpg");
          img1 = ImageIO.read(sourceimage1);
          img2 = ImageIO.read(sourceimage2);

这两个图像是黑白的,它们的尺寸小于之前的两幅图像(lenna50 and lenna100) lo.jpg和lo1.jpg是测试算法的相同图像,它们也是黑白的 如何更改代码以使其适用于任何图像尺寸?

2 个答案:

答案 0 :(得分:7)

  

切换i和j

在下面的代码中,如下所示:

int rgb1 = img1.getRGB(j, i);
int rgb2 = img2.getRGB(j, i);

答案 1 :(得分:1)

你的错误清楚地表明,当读取rgb点作为行img1.getRGB(i, j);中的代码时,它将脱离Array for image RGB。检查i&amp;的值j在你的内部for循环中,检查你做错了什么。正如Hirak指出的那样,你可能没有正确地初始化你的变量,所以它的高度或宽度超出了原因。