Images.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. import os
  3. from image_features_extraction import Image
  4. from image_features_extraction import my_iterator
  5. from image_features_extraction import MyException
  6. class Images(my_iterator.my_iterator):
  7. """
  8. This class loads a collection of images for extraction of features
  9. :param folder_name: folder containing images
  10. :type folder_name: string
  11. :param image_file_ext: images file extensions (default=['tif','tiff'])
  12. :type folder_name: List of strings
  13. :returns: an instance of the object Images
  14. :rtype: object
  15. :example:
  16. >>> import image_features_extraction as fe
  17. >>> imgs = fe.Images('my_folder', image_file_ext=['tif','tiff','jpeg'])
  18. >>> num_images = imgs.count()
  19. """
  20. # to implement the class as a collection this object inherits the abstract class my_iterator
  21. def __init__(self, folder_name, image_file_ext=['tif', 'tiff']):
  22. super().__init__()
  23. #self.__iterator_init__() # initializes my_iterator
  24. self.__folder_name = folder_name
  25. self.__image_file_ext = image_file_ext
  26. self.__dicfiles = []
  27. try:
  28. # load the files image into a list
  29. self.__load()
  30. except MyException.MyException as e:
  31. print(e.args)
  32. def __load(self):
  33. """
  34. load the files image into a list
  35. """
  36. # check that the folder exists
  37. if os.path.isdir(self.__folder_name) == False:
  38. raise MyException.MyException("Error: folder name does not exist")
  39. # store the file names
  40. self.__dicfiles = []
  41. files = os.listdir(self.__folder_name)
  42. for f in files:
  43. if self.__is_imagefile(f):
  44. self.__dicfiles.append(f)
  45. self.count_update(len(self.__dicfiles))
  46. def __is_imagefile(self,file_name):
  47. """
  48. checks that the file is an image
  49. """
  50. # check the extension of the file
  51. ext0 = file_name.split(".")[-1]
  52. for ext1 in self.__image_file_ext:
  53. if ext1 == ext0:
  54. return True
  55. return False
  56. def item(self, i):
  57. """
  58. returns the i-th image
  59. :param i: the i-th image
  60. :type i: int
  61. :returns: :class:`Image`
  62. :rtype: object
  63. :example:
  64. >>> import image_features_extraction as fe
  65. >>> imgs = fe.Images(folder_name)
  66. >>> img = imgs.item(1)
  67. """
  68. try:
  69. if i >= self.count():
  70. raise MyException.MyException("error: index out of bound")
  71. return Image.Image(os.path.join(self.__folder_name, self.__dicfiles[i]))
  72. except MyException.MyException as e:
  73. print(e.args)