GrayscaleImage.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from pylab import imshow, imread, show
  2. from scipy.misc import imresize
  3. from matplotlib.pyplot import hist
  4. from scipy.misc import imresize, imsave
  5. class GrayscaleImage:
  6. def __init__(self, image_path = None, data = None):
  7. if image_path:
  8. self.data = imread(image_path)
  9. extension = image_path.split('.',3)[-1]
  10. if extension == "jpg":
  11. self.data = self.data[::-1]
  12. self.convert_to_grayscale()
  13. elif data:
  14. self.data = data
  15. def __iter__(self):
  16. self.__i_x = -1
  17. self.__i_y = 0
  18. return self
  19. def next(self):
  20. self.__i_x += 1
  21. if self.__i_x == self.width:
  22. self.__i_x = 0
  23. self.__i_y += 1
  24. if self.__i_y == self.height:
  25. raise StopIteration
  26. return self.__i_y, self.__i_x, self[self.__i_y, self.__i_x]
  27. def __getitem__(self, position):
  28. return self.data[position]
  29. def convert_to_grayscale(self):
  30. if len(self.data.shape) > 2:
  31. self.data = self.data[:,:,:3].sum(axis=2) / 3
  32. def crop(self, rectangle):
  33. self.data = self.data[rectangle.y : rectangle.y + rectangle.height,
  34. rectangle.x : rectangle.x + rectangle.width]
  35. def show(self):
  36. imshow(self.data, cmap="gray")
  37. #show()
  38. def make_histogram(self):
  39. return hist(self.data)
  40. # size is of type tuple of integers (DEFAULT = (50, 50))
  41. def resize(self, size):
  42. print size
  43. def resize(self, size): # size is of type float
  44. self.data = imresize(self.data, size)
  45. def get_shape(self):
  46. return self.data.shape
  47. shape = property(get_shape)
  48. def get_width(self):
  49. return self.get_shape()[1]
  50. width = property(get_width)
  51. def get_height(self):
  52. return self.get_shape()[0]
  53. height = property(get_height)
  54. def in_bounds(self, y, x):
  55. return x >= 0 and x < self.width and y >= 0 and y < self.height
  56. def save(self, path):
  57. imsave(path, self.data)