Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageChops.difference not working with simple png images

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:

enter image description here

is the same as below png

enter image description here

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

like image 271
Tim Avatar asked Dec 17 '22 13:12

Tim


1 Answers

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

enter image description here

enter image description here

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:

enter image description here

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.

like image 180
Mark Setchell Avatar answered Dec 20 '22 03:12

Mark Setchell