Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the percentage of difference between two images using Python and OpenCV?

Tags:

python

opencv

I am trying to write a program in Python (with OpenCV) that compares 2 images, shows the difference between them, and then informs the user of the percentage of difference between the images. I have already made it so it generates a .jpg showing the difference, but I can't figure out how to make it calculate a percentage. Does anyone know how to do this?

Thanks in advance.

like image 753
Axel Stone Avatar asked Jul 11 '18 15:07

Axel Stone


People also ask

How do you find the percentage difference in Python?

To calculate the percentage between two numbers, divide one number by the other and multiply the result by 100, e.g. (30 / 75) * 100 . This shows what percent the first number is of the second.

How can I quantify difference between two images?

The difference between two images is calculated by finding the difference between each pixel in each image, and generating an image based on the result.

How do you calculate percentage difference between two values?

Percentage Difference Formula The percentage difference between two values is calculated by dividing the absolute value of the difference between two numbers by the average of those two numbers. Multiplying the result by 100 will yield the solution in percent, rather than decimal form.


1 Answers

Here is a simple idea you can adapt. But always ensure the images being compared are of the same shape.

Code:

img1 = cv2.imread('dog.jpg', 0)
img2 = cv2.imread('cat.jpg', 0)

#--- take the absolute difference of the images ---
res = cv2.absdiff(img1, img2)

#--- convert the result to integer type ---
res = res.astype(np.uint8)

#--- find percentage difference based on number of pixels that are not zero ---
percentage = (numpy.count_nonzero(res) * 100)/ res.size
  • If img1 and img2 are similar most of the pixels in res would be 0 resulting in a lower percentage.
  • If img1 and img2 are different this percentage would be higher.

Note: I have shown for a single channel image and the same can be extended for multi-channel images.

like image 155
Jeru Luke Avatar answered Sep 18 '22 22:09

Jeru Luke