LocalBinaryPatternizer.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from Histogram import Histogram
  2. from math import ceil
  3. class LocalBinaryPatternizer:
  4. def __init__(self, image, cell_size=16):
  5. self.cell_size = cell_size
  6. self.image = image
  7. self.setup_histograms()
  8. def setup_histograms(self):
  9. cells_in_width = int(ceil(self.image.width / float(self.cell_size)))
  10. cells_in_height = int(ceil(self.image.height / float(self.cell_size)))
  11. self.features = []
  12. for i in xrange(cells_in_height):
  13. self.features.append([])
  14. for j in xrange(cells_in_width):
  15. self.features[i].append(Histogram(256,0,256))
  16. def create_features_vector(self):
  17. ''' Walk around the pixels in clokwise order, shifting 1 bit less
  18. at each neighbour starting at 7 in the top-left corner. This gives a
  19. 8-bit feature number of a pixel'''
  20. for y, x, value in self.image:
  21. pattern = (self.is_pixel_darker(y - 1, x - 1, value) << 7) \
  22. | (self.is_pixel_darker(y - 1, x , value) << 6) \
  23. | (self.is_pixel_darker(y - 1, x + 1, value) << 5) \
  24. | (self.is_pixel_darker(y , x + 1, value) << 4) \
  25. | (self.is_pixel_darker(y + 1, x + 1, value) << 3) \
  26. | (self.is_pixel_darker(y + 1, x , value) << 2) \
  27. | (self.is_pixel_darker(y + 1, x - 1, value) << 1) \
  28. | (self.is_pixel_darker(y , x - 1, value) << 0)
  29. cy, cx = self.get_cell_index(y, x)
  30. self.features[cy][cx].add(pattern)
  31. return self.get_features_as_array()
  32. def is_pixel_darker(self, y, x, value):
  33. return self.image.in_bounds(y, x) and self.image[y, x] > value
  34. def get_cell_index(self, y, x):
  35. return (y / self.cell_size, x / self.cell_size)
  36. def get_features_as_array(self):
  37. return [h.bins for h in [h for sub in self.features for h in sub]][0]