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.
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.
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.
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.
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
img1
and img2
are similar most of the pixels in res
would be 0
resulting in a lower percentage.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With