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.
First we load the original and then the duplicate.
You can download here the images I’m using for this tutorial.
import cv2 import numpy as np original = cv2.imread("imaoriginal_golden_bridge.jpg") duplicate = cv2.imread("images/duplicate.jpg")
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.
# 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")
If we want to display the images we can use the code below:
cv2.imshow("Original", original) cv2.imshow("Duplicate", duplicate) cv2.waitKey(0) cv2.destroyAllWindows()
This site uses Akismet to reduce spam. Learn how your comment data is processed.
- Detecting colors (Hsv Color Space) – Opencv with Python
- Write using your Eyes – Gaze controlled keyboard with Python and Opencv p.10
- Play sounds – Gaze controlled keyboard with Python and Opencv p.9
- Press a key by blinking eyes – Gaze controlled keyboard with Python and Opencv p.8
- Virtual Keyboard 3 – Gaze controlled keyboard with Python and Opencv p.7