Prerequisites: Python OpenCV
Suppose we have two data images and a test image. Let’s find out which data image is more similar to the test image using python and OpenCV library in Python.
Let’s first load the image and find out the histogram of images.
Importing library
import cv2
Importing image data
image = cv2.imread('test.jpg')
Converting to gray image
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Finding Histogram
histogram = cv2.calcHist([gray_image], [0],
None, [256], [0, 256])
Example:
Images used:
data1.jpg

data2.jpg

test.jpg

Python3
import cv2
image = cv2.imread( 'cat.jpg' )
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram = cv2.calcHist([gray_image], [ 0 ],
None , [ 256 ], [ 0 , 256 ])
image = cv2.imread( 'cat.jpeg' )
gray_image1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram1 = cv2.calcHist([gray_image1], [ 0 ],
None , [ 256 ], [ 0 , 256 ])
image = cv2.imread( 'food.jpeg' )
gray_image2 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram2 = cv2.calcHist([gray_image2], [ 0 ],
None , [ 256 ], [ 0 , 256 ])
c1, c2 = 0 , 0
i = 0
while i< len (histogram) and i< len (histogram1):
c1 + = (histogram[i] - histogram1[i]) * * 2
i + = 1
c1 = c1 * * ( 1 / 2 )
i = 0
while i< len (histogram) and i< len (histogram2):
c2 + = (histogram[i] - histogram2[i]) * * 2
i + = 1
c2 = c2 * * ( 1 / 2 )
if (c1<c2):
print ( "data1.jpg is more similar to test.jpg as compare to data2.jpg" )
else :
print ( "data2.jpg is more similar to test.jpg as compare to data1.jpg" )
|
Output :
data1.jpg is more similar to test.jpg as compare to data2.jpg
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2023
Like Article
Save Article