LocalBinaryPatternizer.py 2.0 KB

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