GrayscaleImage.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from pylab import imshow, imread, show
  2. from scipy.misc import imresize
  3. class GrayscaleImage:
  4. def __init__(self, image_path = None, data = None):
  5. if image_path != None:
  6. self.data = imread(image_path)
  7. self.convert_to_grayscale()
  8. elif data != None:
  9. self.data = data
  10. def __iter__(self):
  11. self.__i_x = -1
  12. self.__i_y = 0
  13. return self
  14. def next(self):
  15. self.__i_x += 1
  16. if self.__i_x == self.width:
  17. self.__i_x = 0
  18. self.__i_y += 1
  19. if self.__i_y == self.height:
  20. raise StopIteration
  21. return self.__i_y, self.__i_x, self[self.__i_y, self.__i_x]
  22. def __getitem__(self, position):
  23. return self.data[position]
  24. def convert_to_grayscale(self):
  25. self.data = self.data.sum(axis=2) / 3
  26. def crop(self, rectangle):
  27. self.data = self.data[rectangle.y : rectangle.y + rectangle.height,
  28. rectangle.x : rectangle.x + rectangle.width]
  29. def show(self):
  30. imshow(self.data, cmap="gray")
  31. show()
  32. # size is of type float
  33. def resize(self, size):
  34. self.data = imresize(self.data, size)
  35. def get_shape(self):
  36. return self.data.shape
  37. shape = property(get_shape)
  38. def get_width(self):
  39. return self.get_shape()[1]
  40. width = property(get_width)
  41. def get_height(self):
  42. return self.get_shape()[0]
  43. height = property(get_height)
  44. def in_bounds(self, y, x):
  45. return x >= 0 and x < self.width and y >= 0 and y < self.height