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.
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.
You will need to calculate this on your own. You will need the count of diferent pixels and the size of your original image then a simple math: (diferentPixelsCount / (mainImage.width * mainImage.height))*100
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.