# python – Efficient Comparison Of Two Images Using Numpy

I want to compare 2 images using `numpy`. This is what I have got so far.
One of the outputs should be a white image with black pixels where pixels are different.

I am sure it’s possible to make it more efficient by better use of numpy, e.g. the `for` loop can be avoided. Or maybe there is a function/package that has implemented something similar already?

`````` import gc
import PIL
import numpy as np

def compare_images(image_to_test_filename, image_benchmark_filename):

print('comparing', image_to_test_filename, 'and', image_benchmark_filename)

assert image_to_test.shape(0) == image_benchmark.shape(0) and image_to_test.shape(1) == image_benchmark.shape(1)

diff_pixel = np.array((0, 0, 0), np.uint8)
true_array =  np.array((True, True, True, True))
diff_black_white = np.zeros((image_benchmark.shape(0), image_benchmark.shape(1), 3), dtype=np.uint8) + 255
is_close_pixel_by_pixel = np.isclose(image_to_test, image_benchmark)
nb_different_rows = 0
for r, row in enumerate(is_close_pixel_by_pixel):
diff_indices = (c for c, elem in enumerate(row) if not np.all(elem == true_array))
if len(diff_indices):
diff_black_white(r)(diff_indices) = diff_pixel
nb_different_rows += 1

dist = np.linalg.norm(image_to_test - image_benchmark) / (image_to_test.shape(0) * image_to_test.shape(1))

if nb_different_rows > 0:
print("IS DIFFERERENT! THE DIFFERENCE IS (% OF ALL PIXELS)", dist * 100)
im = PIL.Image.fromarray(diff_black_white)
im.save(image_to_test_filename+'_diff.png')
del im

del image_benchmark
del image_to_test
del diff_black_white

gc.collect()

return dist, None
``````

Posted on Categories Articles