Find the difference between two images using Python
Finding the Difference Between Two Images with Python
In this article, we will discuss how to find the difference between two given images using Python. To accomplish this task, we will use the ImageChops.difference() method from the Pillow module.
Syntax: ImageChops.difference(image1, image2)
Parameters:
- image1: The first image
- image2: The second image
Returns: It returns an image.
Steps
Step 2: So, today we’re going to build this amazing tool using Python, and it’s only going to take 8 lines of code. However, before we can do that, we must install the Pillow Python package using the following command:
pip install pillow
Step 2: Now, after installing this, we must obtain two images. Make sure both images are in the same folder where you saved this Python program, otherwise you will have to provide the paths to the images.
Step 3: Call the ImageChops.difference() method, passing the two images as arguments.
Step 4: Use the show() method to generate the difference between the two images.
Implementation:
Input:
# import module
from PIL import Image, ImageChops
# assign images
img1 = Image.open("1img.jpg")
img2 = Image.open("2img.jpg")
# finding the difference
diff = ImageChops.difference(img1, img2)
# showing the difference
diff.show()
Output:
Notice that the output image is primarily black, but some areas of the image are colored. These colored areas represent the spotty differences between the two input images. In this case, the output image shows a total of six major differences.