How can I compare two images? I found Python's PIL library, but I do not really understand how it works.
Asked
Active
Viewed 3.1k times
23
-
2Please precise your question : what are you trying to compare ? What did you try ? – CoMartel Feb 03 '16 at 12:11
-
2well this doesn't make any sense, that's why I asked. An image is basically an array (2D or 3D, depends if you are in RGB/grayscale), and there a multiple ways to compare 2 images : if you need to see if they are identical, image1-image2 will give you the information. If you need to find the transformation between 2 images, that's another thing. – CoMartel Feb 03 '16 at 14:10
4 Answers
27
To check does jpg files are exactly the same use pillow library:
from PIL import Image
from PIL import ImageChops
image_one = Image.open(path_one)
image_two = Image.open(path_two)
diff = ImageChops.difference(image_one, image_two)
if diff.getbbox():
print("images are different")
else:
print("images are the same")
Viktor Ilyenko
- 620
- 7
- 14
12
based on Victor Ilyenko's answer, I needed to convert the images to RGB as PIL fails silently when the .png you're trying to compare contains a alpha channel.
image_one = Image.open(path_one).convert('RGB')
image_two = Image.open(path_two).convert('RGB')
tha_tux
- 121
- 1
- 4
-
3Doesn’t that mean that an image with an alpha channel and another with no such channel would be seen as the same even if they’re not? – bfontaine Dec 16 '20 at 10:32
-
Yes, this excludes the alpha channel from comparison. I would recommend using imagemagick: `compare -metric AE $file1 $file2 /dev/null`. – mara004 Oct 03 '21 at 11:03
4
It appears that Viktor's implementation can fail when the images are different sizes.
This version also compares alpha values. Visually identical pixels are (I think) treated as identical, such as (0, 0, 0, 0) and (0, 255, 0, 0).
from PIL import ImageChops
def are_images_equal(img1, img2):
equal_size = img1.height == img2.height and img1.width == img2.width
if img1.mode == img2.mode == "RGBA":
img1_alphas = [pixel[3] for pixel in img1.getdata()]
img2_alphas = [pixel[3] for pixel in img2.getdata()]
equal_alphas = img1_alphas == img2_alphas
else:
equal_alphas = True
equal_content = not ImageChops.difference(
img1.convert("RGB"), img2.convert("RGB")
).getbbox()
return equal_size and equal_alphas and equal_content
Toren Darby
- 41
- 1
- 3
4
Another implementation of Viktor's answer using Pillow:
from PIL import Image
im1 = Image.open('image1.jpg')
im2 = Image.open('image2.jpg')
if list(im1.getdata()) == list(im2.getdata()):
print("Identical")
else:
print ("Different")
Michael Adams
- 544
- 2
- 27