1

I used the following code to calculate the similarity between images 1 and 2 (i1 and i2). 1=exactly similar while 0=very different. I'd like to know what method this algorithm is using (i.e. Euclidian distance or..?) Thank you.

import math
i1=all_images_saved[0][1]
i2=all_images_saved[0][2]
i1_norm = i1/np.sqrt(np.sum(i1**2))
i2_norm = i2/np.sqrt(np.sum(i2**2))
np.sum(i1_norm*i2_norm)
srv_77
  • 547
  • 1
  • 8
  • 20

2 Answers2

1

Looks like cosine similarity. You can check it gives the same results as:

from scipy import spatial 
cosine_distance = spatial.distance.cosine(i1.flatten(), i2.flatten()) 
cosine_similarity = 1 - cosine_distance
filippo
  • 5,197
  • 2
  • 21
  • 44
0

I don't believe it's a distance, otherwise 0 would mean identical. This looks like the dot product of 2 normalized vectors in which case I would say about the original vectors that they are (with the range of values from -1 to 1 being in between the thresholds describe below):

  • 1 = co-directional
  • 0 = orthogonal
  • -1 = opposite direction

And given the geometric definition of the dot product, if you have the dot product and the magnitude of your vectors you can derive the angle between the 2:

a . b = ||a|| ||b|| cos θ

Or have I completely missed something here?

Max
  • 12,794
  • 30
  • 90
  • 142
  • Someone recommended this metric to tell how similar two images are. Is it not doing that? – srv_77 Mar 08 '21 at 09:57
  • Mathematically it gives similarity of images seen as matrices. But if you mean how humans perceive images it might not be suitable (eg take 1 image, crop 2 smaller images from it with a small offset between the 2: the images will look similar to a human, but mathematically all pixels are off thus the math might say they are dissimilar. Normalization might help (eg centering/reshape for specific images: https://stackoverflow.com/questions/44914035/how-to-centralize-and-resize-digits-using-opencv) but usually with images you get better results using neural nets thx to flexibility of convolution – Max Mar 08 '21 at 10:22