Histogram.py 1014 B

123456789101112131415161718192021222324252627282930313233343536
  1. class Histogram:
  2. def __init__(self, bins, min, max):
  3. self.bins = [0] * bins
  4. self.min = min
  5. self.max = max
  6. def add(self, number):
  7. bin_index = self.get_bin_index(number)
  8. self.bins[bin_index] += 1
  9. def remove(self, number):
  10. bin_index = self.get_bin_index(number)
  11. self.bins[bin_index] -= 1
  12. def get_bin_index(self, number):
  13. return (number - self.min) / ((self.max - self.min) / len(self.bins))
  14. def normalize(self):
  15. minimum = min(self.bins)
  16. self.bins = map(lambda b: b - minimum, self.bins)
  17. maximum = float(max(self.bins))
  18. self.bins = map(lambda b: b / maximum, self.bins)
  19. def intersect(self, other):
  20. h1 = self.bins
  21. h2 = other.bins
  22. match = 0
  23. # Add the minimum of each bin to the result
  24. for b in xrange(len(self.bins)):
  25. match += min(h1[b], h2[b])
  26. # Normalize by dividing by the number of pixels
  27. return float(match) / sum(h2)