Tim
Tim

Reputation: 1826

Comparing two similar PIL images using numpy arrays not working

I am trying to compare two images and see how similar they are to one another.

Image one:

image one

Image two:

enter image description here

I have tried two different ways to compare the images but both ways say they are not even close.

First, try at comparing:

from PIL import Image, ImageChops
t1 = Image.open('./t1.png').convert("RGB")
t2 = Image.open('./t2.png').convert("RGB")
diff = ImageChops.difference(t1, t2)

if diff.getbbox():
    print("images are different") # This is the result each time
else:
    print("images are the same")

I thought maybe they are only a few pixels off so I tried to compare with numpy:

import numpy as np
np_t1 = np.array(t1)
np_t2 = np.array(t2)
print(np.mean(np_t1 == np_t2)) # This should return something around .90 or above but instead it returns 0

Not sure what I am doing wrong. Here is a link to my code: https://github.com/timothy/image_diff/blob/master/test.py

Any help is much appreciated!

Upvotes: 1

Views: 1020

Answers (1)

Ehsan
Ehsan

Reputation: 12397

They are different shapes:

t1.shape
(81, 81, 3)
t2.shape
(81, 80, 3)

print(np.mean(t1[:,:-1,:] == t2))
0.9441358024691358

When you use t1 == t2, because the arrays are of different sizes, it returns a single False, whereas in t1[:,:-1,:] == t2, since the arrays are of same shape, it returns an array of same shape with element-wise comparison.

Upvotes: 3

Related Questions