To compare two images for similarity or equality using the Python 3 OpenCV
and NumPy
libraries, you can follow these steps:
Step 1: Install the opencv-python
and numpy
libraries using pip.
pip install opencv-python
`
pip install numpy
Step 2: Create a new Python script and import the necessary modules.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import cv2 import numpy as np def compare_images(image1_path, image2_path): # Read the images image1 = cv2.imread(image1_path) image2 = cv2.imread(image2_path) # Check if the images have the same shape if image1.shape != image2.shape: return False # Compute the absolute difference between the images difference = cv2.absdiff(image1, image2) difference = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY) # Set a threshold to consider images as equal or similar threshold = 30 similarity = np.mean(difference) <= threshold return similarity |
In the above code, we define the compare_images
function that takes the paths of two images as input. It reads the images using cv2.imread
and checks if they have the same shape. Then it calculates the absolute difference between the images using cv2.absdiff
and converts it to grayscale. Finally, it computes the mean of the difference and compares it to a threshold to determine if the images are similar or equal.
Step 4: Call the compare_images
function with the paths of the two images you want to compare.
1 2 3 4 5 6 7 8 9 |
image1_path = 'image1.jpg' image2_path = 'image2.jpg' result = compare_images(image1_path, image2_path) if result: print("The images are similar.") else: print("The images are not similar.") |