Current position:  Home > Default > How can I improve performance (image searching)

How can I improve performance (image searching)

Time:October 11
Advertisement
Hello,
My program makes many calls to a method that compares two images. It does this by using nested for-loops (one for x-pixel and one for y-pixel) to search through a BufferedImage image and use getRGB() to compare pixel-by-pixel to see if the two images are the same.
I've added a little bit of "optimisation" that first compares the central 5-pixles (the 5 pixels in an "X" shape in the middle of each image), and will only continue to search pixel-by-pixel if those are shown to be the same.
Of course, both searches (the optimisation-pre-search and the pixel-by-pixel search) will quit out of the loops and return false as soon as one non-matching pixel is found.
The problem is that it has to do this millions of times. For every single pixel in the source image, it has to go through one-by-one and compare, starting with the "optimised" speedy-compare and then moving on.
Advertisement
Try this:
public static boolean areImagesIdentical(File file1, File file2) throws IOException {
          // Safe to do this?
          if(file1.getAbsolutePath().equals(file2.getAbsolutePath())) {
               System.out.println("files are same - same path");
               return true;
          if(file1.length() != file2.length()) {
               System.out.println("files are different, different file size");
               return false;
          BufferedImage image1 = ImageIO.read(file1);
          BufferedImage image2 = ImageIO.read(file2);
          if(image1.getHeight() != image2.getHeight() || image1.getWidth() != image2.getWidth()) {
               System.out.println("files are different, different height or width");
               return false;
          // Take 10 pixels from anywhere in each image
          for(int i=0; i<10; i++) {
               int x = (int) (Math.random() * image1.getWidth());
               int y = (int) (Math.random() * image1.getHeight());
               if(image1.getRGB(x, y) != image2.getRGB(x, y)) {
                    return false;
          int[] image1AllRGBs = image1.getRGB(0, 0, image1.getWidth(), image1.getHeight(), null, 0, image1.getWidth());
          int[] image2AllRGBs = image2.getRGB(0, 0, image2.getWidth(), image2.getHeight(), null, 0, image2.getWidth());
          return Arrays.equals(image1AllRGBs, image2AllRGBs);
     }