Skip to content

Instantly share code, notes, and snippets.

@lwerdna
Created August 10, 2019 00:12
Show Gist options
  • Save lwerdna/01a3def38fade5fa62fb26cf62390f36 to your computer and use it in GitHub Desktop.
Save lwerdna/01a3def38fade5fa62fb26cf62390f36 to your computer and use it in GitHub Desktop.
chi-squared comparison
#!/usr/bin/env python
def chi_square(a, b):
# https://github.com/opencv/opencv/blob/master/modules/imgproc/src/histogram.cpp
# sum(i=1,n, (x_i - y_i)^2 / (x_i+y_i) )
assert len(a)==len(b)
result = 0;
for i in range(len(a)):
numerator = a[i]-b[i]
denominator = a[i] + b[i]
if denominator != 0:
result += 1.0 * (a[i]-b[i])**2 / (a[i]+b[i])
return result
def normalize(a):
s = float(sum(a))
return list(map(lambda x: x/s, a))
def cmp_histograms(a, b):
return chi_square(normalize(a), normalize(b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment