GrayscaleImage.py 1.9 KB

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