• For any query, contact us at
  • +91-9872993883
  • +91-8283824812
  • info@ris-ai.com

Measure similarity between images using Python-OpenCV

This is the model in which we predict the images according to their similarities.

In [2]:
# test image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('/home/webtunix/Downloads/p.jpg')
imgplot = plt.imshow(img)
plt.show()
image similarity measurement
In [3]:
img = mpimg.imread('/home/webtunix/Downloads/peacock.jpg')
imgplot = plt.imshow(img)
plt.show()
image similarity measurement
In [4]:
img = mpimg.imread('/home/webtunix/Downloads/pegion.jpg')
imgplot = plt.imshow(img)
plt.show()
image similarity measurement
In [7]:
import cv2
# test image
image = cv2.imread('/home/webtunix/Downloads/p.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
   
# data1 image
image = cv2.imread('/home/webtunix/Downloads/peacock.jpg')
gray_image1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram1 = cv2.calcHist([gray_image1], [0], None, [256], [0, 256])
   
# data2 image
image = cv2.imread('/home/webtunix/Downloads/pegion.jpg')
gray_image2 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram2 = cv2.calcHist([gray_image2], [0], None, [256], [0, 256])
   
c1, c2 = 0, 0
   
# Euclidean Distace between data1 and test
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")
    img1 = mpimg.imread('/home/webtunix/Downloads/p.jpg')
    imgplot1 = plt.imshow(img1)
    plt.show()

    img = mpimg.imread('/home/webtunix/Downloads/peacock.jpg')
    imgplot = plt.imshow(img)
    plt.show()
else:
    print("data2.jpg is more similar to test.jpg as compare to data1.jpg")
    img1 = mpimg.imread('/home/webtunix/Downloads/p.jpg')
    imgplot1 = plt.imshow(img1)
    plt.show()

    img = mpimg.imread('/home/webtunix/Downloads/pegion.jpg')
    imgplot = plt.imshow(img)
    plt.show()
data2.jpg is more similar to test.jpg as compare to data1.jpg
image similarity measurement
image similarity measurement
In [ ]: