PROJECTS / SPOT THE DIFFERENCES
2021
Languages:
Spot the differences between two images using Python and OpenCV.
Feel free to check the following video or use Youtube for a better and visual understanding of this project and it's concepts.
This program can spot-find the differences between two images.
The user loads to the program 2 images that are mostly the same but also have some small differences. By running the program user gets both images side by side with their differences highlighted.
We will check two methods. For the first method we will use images city1.jpg and city2.jpg (Photo by Fede Roveda from Pexels) and for the second one we will use images camels1.jpg and camels2.jpg (Photo by Travel Photography from Pexels)
At the beggining we are going to load the neccessary packages.
import cv2 # To use OpenCV
import imutils # To calculate contours
import numpy as np # For mathematical functions
First we are loading the two images.
img1 = cv2.imread('path_to_image_1')
img2 = cv2.imread('path_to_image_2')
Then we are converting both images to grayscale format.
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
Now it's time to find the absolute difference between the two images (arrays).
diff = cv2.absdiff(gray1, gray2)
cv2.imshow("diff(img1, img2)", diff)
Apply threshold. Apply both THRESH_BINARY and THRESH_OTSU.
thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv2.imshow("Threshold", thresh)
We are going to use 2 iterations of dilation in order to increase the white region in threshold.
kernel = np.ones((5,5), np.uint8)
dilate = cv2.dilate(thresh, kernel, iterations=2)
cv2.imshow("Dilate", dilate)
Finally we are calculating the contours and draw rectangles in both images which are corresponding to the differences between the 2 images.
contours = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
The results are the following :
Let's load our two images.
We are following the steps of the First Method with some small changes. Instead of cv2.absdiff, now we are computing the full structural similarity (similar) between the two gray images. Also we must convert diff array in range [0, 255].
(simalr, diff) = compare_ssim(gray1, gray2, full=True)
diff = (diff*255).astype("uint8")
After deleting the dilation part from first method we are calculating the contours as before.
The results are the following :
For a better and visual understanding of this project and it's concepts, watch the video on Youtube.