When we are using python to control our phone, we may need to know two images are same or not. In this tutorial, we will introduce you how to do.
We will use python pillow library to implement it.
Import library
from PIL import Image from PIL import ImageChops
We will write a function to compare two images.
Compare two images
We will use function below to compare.
def compare_images(path_one, path_two): """ compare images :param path_one: first image :param path_two: second image :return: same is True, otherwise is False """ image_one = Image.open(path_one) image_two = Image.open(path_two) try: diff = ImageChops.difference(image_one, image_two) if diff.getbbox() is None: # same return True else: return False except ValueError as e: return False
Then we can start to compare images.
Test function
You can use function above as follows:
if __name__ == '__main__': compare_images( 'target.png', 'template.jpg', )
Moreover, if you want to get the different part of two images, you can refer:
Beginner Guide to Python Extract Different Region of Two Images with Pillow – Python Pillow Tutorial
isn’t this method too slow compared to ‘open(image_one, “rb”).read() == open(image_two, “rb”).read()’ ?