I am creating a simple script to check if images are the same or different.
My code works for the jpg files but not for the png files.
For some reason, my code below thinks that the below png:
is the same as below png
from PIL import Image, ImageChops
img1 = Image.open('./1.png')
img2 = Image.open('./2.png')
img3 = Image.open('./A.jpg')
img4 = Image.open('./B.jpg')
diff1 = ImageChops.difference(img3, img4)
diff = ImageChops.difference(img2, img1)
print(diff.getbbox())
if diff.getbbox():
diff.show() # does not work for me. should show image if they are different
print(diff1.getbbox())
if diff1.getbbox():
diff1.show() # this works not sure why the PNG files do not
I am running this on Ubuntu. I am not sure what I am doing wrong. Any help would be great thanks!
Working code after @Mark's help: https://github.com/timothy/image_diff/blob/master/test.py
Not 100% certain what's going on here, but if you take your two images and split them into their channels and lay the channels out side-by-side, with ImageMagick:
magick 1.png -separate +append 1ch.png
You can see the Red, Green and Blue channels all contain shapes but there is a superfluous alpha channel (the rightmost area) serving no purpose - other than to confuse PIL!
If you change your code to drop the alpha channel like this, it then works:
img1 = Image.open('1.png').convert('RGB')
img2 = Image.open('2.png').convert('RGB')
diff = ImageChops.difference(img2, img1)
diff.getbbox()
(28, 28, 156, 156)
Difference image:
I note also that the ImageChops.difference documentation says "one of the images must be "1" mode" and have no idea if that is an issue.
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