How to Create a Diff of an Image in Python
This article is a quick, hands-on example of comparing two images using Python and the Pillow library.
Join the DZone community and get the full member experience.Join For Free
for the past couple of years, i’ve been writing automated tests for my employer. one of the many types of tests that i do is comparing how an application draws. does it draw the same way every single time? if not, then we have a serious problem. an easy way to check that it draws the same each time is to take a screenshot and then compare it to future versions of the same drawing when the application gets updated.
the pillow library provides a handy tool for this sort of thing that is called imagechops . if you don’t already have pillow, you should go install it now so you can follow along with this short tutorial.
comparing two images
the first thing we need to do is find two images that are slightly different. you can create your own by using burst mode on your camera and taking a bunch of photos of animals as they move, preferably while using a tripod. or you can take an existing photo and just add some kind of overlay, such as text. i’m going to go with the latter method. here is my original photo of multnomah falls in oregon:
and here’s the modified version where i added some text to identify the location of the photo:
now let’s use imagechops to find the difference for us!
import image import imagechops def compare_images(path_one, path_two, diff_save_location): """ compares to images and saves a diff image, if there is a difference @param: path_one: the path to the first image @param: path_two: the path to the second image """ image_one = image.open(path_one) image_two = image.open(path_two) diff = imagechops.difference(image_one, image_two) if diff.getbbox() is none: # there is no difference between the images return else: diff.save(diff_save_location) if __name__ == '__main__': compare_images('/path/to/multnomah_falls.jpg', '/path/to/multnomah_falls_text.jpg', '/path/to/diff.jpg')
here we have a simple function that we can use to find differences in images. all you need to do is pass it three paths! the first two paths are for the images that we want to compare. the last path is where to save the diff image, if we find a diff. for this example, we should definitely find a diff and we did. here’s what i got when i ran this code:
the pillow package has many amazing features for working with images. i enjoy photography so it’s fun to be able to take photos and then use my favorite programming language to help me do neat things with the results. you should give this a try as well and read the pillow documentation to see what else you can do with this clever package!
Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.