Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Python 3 Script to Compare Two Images For Similarity or Equality Using OpenCV and Numpy Library

Posted on May 16, 2023

 

 

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.

 

Python
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.

 

 

Python
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.")

 

Recent Posts

  • Node.js Express Project to Remove Background of Images Using Rembg & Formidable Library in Browser
  • Node.js Tutorial to Remove Background From Image Using Rembg & Sharp Library in Command Line
  • Python 3 Flask Project to Remove Background of Multiple Images Using Rembg Library in Browser
  • Python 3 Rembg Library Script to Bulk Process Multiple Images and Remove Background in Command Line
  • Python 3 Rembg Library Script to Remove Background From Image in Command Line
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme