GrayscaleImage.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. for y in xrange(self.data.shape[0]):
  16. for x in xrange(self.data.shape[1]):
  17. yield y, x, self.data[y, x]
  18. #self.__i_x = -1
  19. #self.__i_y = 0
  20. #return self
  21. #def next(self):
  22. # self.__i_x += 1
  23. # if self.__i_x == self.width:
  24. # self.__i_x = 0
  25. # self.__i_y += 1
  26. # if self.__i_y == self.height:
  27. # raise StopIteration
  28. # return self.__i_y, self.__i_x, self[self.__i_y, self.__i_x]
  29. def __getitem__(self, position):
  30. return self.data[position]
  31. def convert_to_grayscale(self):
  32. if len(self.data.shape) > 2:
  33. self.data = self.data[:,:,:3].sum(axis=2) / 3
  34. def crop(self, rectangle):
  35. self.data = self.data[rectangle.y : rectangle.y + rectangle.height,
  36. rectangle.x : rectangle.x + rectangle.width]
  37. def show(self):
  38. imshow(self.data, cmap="gray")
  39. show()
  40. def make_histogram(self):
  41. return hist(self.data)
  42. def resize(self, size): # size is of type float
  43. self.data = imresize(self.data, size)
  44. def get_shape(self):
  45. return self.data.shape
  46. shape = property(get_shape)
  47. def get_width(self):
  48. return self.get_shape()[1]
  49. width = property(get_width)
  50. def get_height(self):
  51. return self.get_shape()[0]
  52. height = property(get_height)
  53. def in_bounds(self, y, x):
  54. return x >= 0 and x < self.width and y >= 0 and y < self.height
  55. def save(self, path):
  56. imsave(path, self.data)