Skip to content

Instantly share code, notes, and snippets.

@jstadler
Created July 9, 2014 05:57
Show Gist options
  • Select an option

  • Save jstadler/c47861f3d86c40b82d4c to your computer and use it in GitHub Desktop.

Select an option

Save jstadler/c47861f3d86c40b82d4c to your computer and use it in GitHub Desktop.
Implementation of the Bhattacharyya distance in Python
# bhattacharyya test
import numpy
import math
h1 = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
h2 = [ 6, 5, 4, 3, 2, 1, 0, 0 ];
h3 = [ 8, 7, 6, 5, 4, 3, 2, 1 ];
h4 = [ 1, 2, 3, 4, 4, 3, 2, 1 ];
h5 = [ 8, 8, 8, 8, 8, 8, 8, 8 ];
h = [ h1, h2, h3, h4, h5 ];
def mean( hist ):
mean = 0.0;
for i in hist:
mean += i;
mean/= len(hist);
return mean;
def bhatta ( hist1, hist2):
# calculate mean of hist1
h1_ = mean(hist1);
# calculate mean of hist2
h2_ = mean(hist2);
# calculate score
score = 0;
for i in range(8):
score += math.sqrt( hist1[i] * hist2[i] );
# print h1_,h2_,score;
score = math.sqrt( 1 - ( 1 / math.sqrt(h1_*h2_*8*8) ) * score );
return score;
# generate and output scores
scores = [];
for i in range(len(h)):
score = [];
for j in range(len(h)):
score.append( bhatta(h[i],h[j]) );
scores.append(score);
for i in scores:
print i
@alajmo
Copy link
Copy Markdown

alajmo commented Aug 5, 2014

Seeing as you import numpy, you might as well use its mean function. np.average(hist).

@groundzyy
Copy link
Copy Markdown

Why not directly convert the hist1, hist2 to the percentage by dividing the sum of each instead of calculating the mean, then divide by the mean * 8?

@myroncama12
Copy link
Copy Markdown

Very useful. I have a quiestion. Why you do the for in range of 8? 8 is the size of each histogram? if this is the case, can i change 8 by len(h1) for example?. Thanks

@3rd3
Copy link
Copy Markdown

3rd3 commented May 5, 2017

def bhattacharyya(h1, h2):
  '''Calculates the Byattacharyya distance of two histograms.'''

  def normalize(h):
    return h / np.sum(h)

  return 1 - np.sum(np.sqrt(np.multiply(normalize(h1), normalize(h2))))

@harry098
Copy link
Copy Markdown

harry098 commented Nov 4, 2017

if we want to use bhattacharyya distance for an image with more number of bands ( which will be a 3d numpy array) what modifications we have to do in order to use above code for that image.

@szufix
Copy link
Copy Markdown

szufix commented Jan 15, 2019

You implemented Hellinger distance which is different from Bhattacharyya distance.

@agusgun
Copy link
Copy Markdown

agusgun commented Mar 2, 2019

@harry098 maybe using flatten so your array will be 1D array (?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment