# How to compare two images using Java OpenCV library?

JavaObject Oriented ProgrammingProgramming

To compare two images −

• Get the height and width of both of them to make sure they are equal.

• Get the pixel values and, get the RGB values of both of the images.

• Get the sum of the differences between the RGB values of these two images.

• Calculate the percentage of the difference using the following formula −

Average = difference/weight*height*3;
Percentage = (Average/255)*100;

## Example

import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class ComparingImages {
public static void main(String[] args) throws Exception {
int w1 = img1.getWidth();
int w2 = img2.getWidth();
int h1 = img1.getHeight();
int h2 = img2.getHeight();
if ((w1!=w2)||(h1!=h2)) {
System.out.println("Both images should have same dimwnsions");
} else {
long diff = 0;
for (int j = 0; j < h1; j++) {
for (int i = 0; i < w1; i++) {
//Getting the RGB values of a pixel
int pixel1 = img1.getRGB(i, j);
Color color1 = new Color(pixel1, true);
int r1 = color1.getRed();
int g1 = color1.getGreen();
int b1 = color1.getBlue();
int pixel2 = img2.getRGB(i, j);
Color color2 = new Color(pixel2, true);
int r2 = color2.getRed();
int g2 = color2.getGreen();
int b2= color2.getBlue();
//sum of differences of RGB values of the two images
long data = Math.abs(r1-r2)+Math.abs(g1-g2)+ Math.abs(b1-b2);
diff = diff+data;
}
}
double avg = diff/(w1*h1*3);
double percentage = (avg/255)*100;
System.out.println("Difference: "+percentage);
}
}
}

## Input1 ## Input2 ## Output

Difference: 92.54901960784314
{"ft_lang_label":"__label__en","ft_lang_prob":0.6475417,"math_prob":0.9921283,"size":3078,"snap":"2022-05-2022-21","text_gpt3_token_len":812,"char_repetition_ratio":0.18575147,"word_repetition_ratio":0.14028056,"special_character_ratio":0.2868746,"punctuation_ratio":0.16779661,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99805737,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,3,null,3,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-25T06:20:59Z\",\"WARC-Record-ID\":\"<urn:uuid:b3c71da9-e626-490f-b1a7-5b9c8976891b>\",\"Content-Length\":\"33156\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:afabe505-cc29-46c5-bf51-9b4a1ea0858c>\",\"WARC-Concurrent-To\":\"<urn:uuid:cd98afde-1601-4fa5-bb6c-5dd69507a21c>\",\"WARC-IP-Address\":\"192.229.210.176\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/how-to-compare-two-images-using-java-opencv-library\",\"WARC-Payload-Digest\":\"sha1:57IQKPUUWKZ7DAJD34F43C5WRWKXFVFE\",\"WARC-Block-Digest\":\"sha1:JPZ26TZGQLXA56O73OS4WUQ3MXNIM64L\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662580803.75_warc_CC-MAIN-20220525054507-20220525084507-00668.warc.gz\"}"}