You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

image.py 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Image Transform Processing."""
  2. import os
  3. import sys
  4. import hashlib
  5. from config import Config as Conf
  6. from processing import Processing
  7. from processing.utils import select_phases
  8. from processing.worker import run_worker
  9. from utils import camel_case_to_str, write_image
  10. from loader import Loader
  11. class ImageProcessing(Processing):
  12. """Image Processing Class."""
  13. def _setup(self, *args):
  14. """
  15. Process Image Constructor.
  16. :param args: <dict> args parameter to run the image transformation (default use Conf.args)
  17. """
  18. self.__phases = select_phases(self._args)
  19. self.__input_path = self._args['input']
  20. self.__output_path = self._args['output']
  21. self.__altered_path = self._args.get('altered')
  22. self.__starting_step = self._args['steps'][0] if self._args.get('steps') else 0
  23. self.__ending_step = self._args['steps'][1] if self._args.get('steps') else None
  24. Conf.log.debug("All Phases : {}".format(self.__phases))
  25. Conf.log.debug("To Be Executed Phases : {}".format(self.__phases[self.__starting_step:self.__ending_step]))
  26. imagename_no_ext = os.path.splitext(os.path.basename(self.__input_path))[0]
  27. if (self._args.get('folder_altered')):
  28. folder_name = imagename_no_ext + '_' + str(hashlib.md5(open(self.__input_path, 'rb').read()).hexdigest())
  29. folder_path = os.path.join(self._args['folder_altered'], folder_name)
  30. if (not os.path.isdir(folder_path)):
  31. os.makedirs(folder_path, exist_ok=True)
  32. self._args['folder_altered'] = folder_path
  33. path = self._args['folder_altered']
  34. self.__image_steps = [self.__input_path] + [
  35. os.path.join(path, "{}.png".format(p().__class__.__name__))
  36. for p in self.__phases[:self.__starting_step]
  37. ]
  38. elif (self.__altered_path):
  39. folder_name = imagename_no_ext + '_' + str(hashlib.md5(open(self.__input_path, 'rb').read()).hexdigest())
  40. folder_path = os.path.join(self.__altered_path, folder_name)
  41. if (not os.path.isdir(folder_path)):
  42. os.makedirs(folder_path, exist_ok=True)
  43. self.__altered_path = folder_path
  44. path = self.__altered_path
  45. self.__image_steps = [self.__input_path] + [
  46. os.path.join(path, "{}.png".format(p().__class__.__name__))
  47. for p in self.__phases[:self.__starting_step]
  48. ]
  49. else:
  50. # TODO: refactor me, please!
  51. self.__image_steps = [self.__input_path] + [
  52. self.__input_path
  53. for p in self.__phases[:self.__starting_step]
  54. ]
  55. Conf.log.info("Processing on {}".format(str(self.__image_steps)))
  56. try:
  57. self.__image_steps = [
  58. (Loader.get_loader(x)).load(x) if isinstance(x, str) else x for x in self.__image_steps
  59. ]
  60. except (FileNotFoundError, AttributeError) as e:
  61. Conf.log.error(e)
  62. Conf.log.error("{} is not able to resume because it not able to load required images. "
  63. .format(camel_case_to_str(self.__class__.__name__)))
  64. Conf.log.error("Possible source of this error is that --altered argument is not a correct "
  65. "directory path that contains valid images.")
  66. sys.exit(1)
  67. def _execute(self, *args):
  68. """
  69. Execute all phases on the image.
  70. :return: None
  71. """
  72. # todo: refactor me, please!
  73. # with this we force the auto-resize for dreamtime, but it is far from ideal
  74. #if self.__starting_step == 5:
  75. # r = run_worker(self.__phases[0], self.__image_steps, config=self._args)
  76. # self.__image_steps.append(r)
  77. for step,p in enumerate(x for x in self.__phases[self.__starting_step:self.__ending_step]):
  78. r = run_worker(p, self.__image_steps, config=self._args)
  79. self.__image_steps.append(r)
  80. # todo: refactor me, please!
  81. if self._args.get('export_step'):
  82. export_step = self._args.get('export_step')
  83. if self._args.get('overlay'):
  84. export_step += 2
  85. #Conf.log.debug("Fixing overlay export_step = {}".format(export_step))
  86. if self._args.get('auto_rescale') or self._args.get('auto_resize') or self._args.get('auto_resize_crop'):
  87. export_step += 1
  88. #Conf.log.debug("Fixing scale export_step = {}".format(export_step))
  89. if export_step == (step-1):
  90. step_path = self._args.get('export_step_path') or os.path.abspath(os.path.join(self.__output_path, '..', 'export.png'))
  91. if self._args.get('overlay'):
  92. r = run_worker(self.__phases[-1], self.__image_steps, config=self._args)
  93. write_image(r, step_path)
  94. Conf.log.debug("Export Step Image Of {} Execution: {}".format(
  95. camel_case_to_str(p.__name__),
  96. step_path
  97. ))
  98. if self.__altered_path:
  99. if (self._args.get('folder_altered')):
  100. path = self._args['folder_altered']
  101. else:
  102. path = self.__altered_path
  103. write_image(r, os.path.join(path, "{}.png".format(p.__name__)))
  104. Conf.log.debug("{} Step Image Of {} Execution".format(
  105. os.path.join(path, "{}.png".format(p.__name__)),
  106. camel_case_to_str(p.__name__),
  107. ))
  108. write_image(self.__image_steps[-1], self.__output_path)
  109. Conf.log.info("{} Created".format(self.__output_path))
  110. Conf.log.debug("{} Result Image Of {} Execution"
  111. .format(self.__output_path, camel_case_to_str(self.__class__.__name__)))
  112. return self.__image_steps[-1]