ThatOneGuyInXNA
ThatOneGuyInXNA

Reputation: 111

Image difference in Java

public float calculateDifference(BufferedImage b1, BufferedImage b2){
    float error = 0;
    for(int y = 0; y < sizeY; y++){
        for(int x = 0; x < sizeX; x++){
            Color c1 = new Color(b1.getRGB(x, y));
            Color c2 = new Color(b2.getRGB(x, y));
            error += Math.abs(c1.getRed() - c2.getRed());
            error += Math.abs(c1.getGreen() - c2.getGreen());
            error += Math.abs(c1.getBlue() - c2.getBlue());
            error += Math.abs(c1.getAlpha() - c2.getAlpha());
        }
    }
    return error;
}

I have this function that compares two bufferedimages. It returns a higher error if the two images are more different. The only problem is it runs really slowly so is there any more efficient way to do this? Any way to lower the runtime would really help.

Upvotes: 0

Views: 71

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Yes you can optimize the internal for loop. Don't create new Color objects. Use directly the int value of RGB. This will limit the number of Objects created and the frequency of call to Garbage collection.

int color1 = b1.getRGB(x, y);
int alpha1 = (color1 >> 24) & 0xFF;
int red1 = (color1 >> 16) & 0xFF;
int green1 = (color1 >> 8) & 0xFF; 
int blue1 = (color1 >> 0) & 0xFF;

int color2 = b2.getRGB(x, y);
int alpha2 = (color2 >> 24) & 0xFF;
int red2 = (color2 >> 16) & 0xFF;
int green2 = (color2 >> 8) & 0xFF; 
int blue2 = (color2 >> 0) & 0xFF;

error += Math.abs(red1 - red2);
error += Math.abs(green1 - green2);
error += Math.abs(blue1 - blue2);
error += Math.abs(alpha1 - alpha2);

Upvotes: 1

Related Questions