Reputation: 41
I am trying to calculate euclidean distances of two hue image histograms, I have found cv2.compareHist method but it does not give an option for euclidean distance. Any help is highly appreciated.
Upvotes: 2
Views: 2400
Reputation: 53081
Here is how to do that in Python/OpenCV.
Input:
import cv2
import math
# Load the images
img1 = cv2.imread('lena.jpg')
img2 = cv2.imread('zelda1.jpg')
# convert to gray
gray1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
# Calculate the histograms, and normalize them
hist1 = cv2.calcHist([gray1], [0], None, [256], [0, 256])
#cv2.normalize(hist1, hist1, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)
hist2 = cv2.calcHist([gray2], [0], None, [256], [0, 256])
#cv2.normalize(hist2, hist2, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)
# compute euclidean distance
sum = 0
for i in range (0,256):
sum = sum + (hist1[i][0]-hist2[i][0])**2
dist = math.sqrt(sum)
print('euclidean distance:', dist)
# above is equivalent to cv2.norm()
dist2 = cv2.norm(hist1, hist2, normType=cv2.NORM_L2)
print('euclidean distance2:', dist2)
Results:
euclidean distance : 2319.6163475885405
euclidean distance2: 2319.6163475885405
If the images do not have the same dimensions (total pixels=width*height), then one probably should normalize the histograms by dividing every bin by the total pixels in the image.
Upvotes: 2