Check if two images are equal with Opencv and Python
Finding if two images are equal with Opencv, is a quite simple operation.
There are 2 fundamental elements to consider:
- The images have both the same size and channels
- Each pixel has the same value
We’re going first to load the images. If you want to download the images I used, you can go at the end of this article to download the entire source code with the files.
First we load the original and then the duplicate.
import numpy as np
original = cv2.imread(“imaoriginal_golden_bridge.jpg”)
duplicate = cv2.imread(“images/duplicate.jpg”)[/python]
We loaded the two images we can start making the comparison.
First we check if they have the same size and channels. If they have the same size and channels, we continue further with the operation, if they don’t then that they’re not equal.
If they have the same sizes and channels, we proceed by subtracting them. The operation cv2.subtract(image1, image2) simply subtract from each pixel of the first image, the value of the corresponding pixel in the second image.
If for example the value of the pixel of the first image in the position (0, 0) is 255 and the value of the pixel in the corresponding position of the second image is also 255, it will be a simple subtraction: 255 – 255 which is equal to 0.
That’s why if the images are equal, the result will be a black image (which means each pixel will have value 0).
A colored image has 3 channels (blue, green and red), so the cv2.subtract() operation makes the subtraction for each single channel and we need to check if all the three channels are black.
If they are, we can say that the images are equal.
[python firstline=”6″]# 1) Check if 2 images are equals
if original.shape == duplicate.shape:
print(“The images have same size and channels”)
difference = cv2.subtract(original, duplicate)
b, g, r = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
print(“The images are completely Equal”)[/python]
If we want to display the images we can use the code below:
[python firstline=”15″]cv2.imshow(“Original”, original)
This site uses Akismet to reduce spam. Learn how your comment data is processed.