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 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 a value of 0).
A colored image has 3 channels (blue, green, and red), so the cv2.subtract() operation makes the subtraction for every 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()
Hi there, I’m the founder of Pysource.
I’m a Computer Vision Consultant, developer and Course instructor.
I help Companies and Freelancers to easily and efficiently build Computer Vision Software.
Learn to build Computer Vision Software easily and efficiently.
This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.Sign UP for FREE
Detect and Track any Object (Full Videocourse)
You can Build Software to detect and track any Object even if you have a basic programming knowledge.