generate_reconstructed_data.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed Jun 19 11:47:42 2019
  5. @author: jbuisine
  6. """
  7. # main imports
  8. import sys, os, argparse
  9. import numpy as np
  10. # images processing imports
  11. from PIL import Image
  12. from ipfml.processing.segmentation import divide_in_blocks
  13. # modules imports
  14. sys.path.insert(0, '') # trick to enable import of main folder module
  15. import custom_config as cfg
  16. from modules.utils.data import get_scene_image_quality
  17. from modules.classes.Transformation import Transformation
  18. # getting configuration information
  19. zone_folder = cfg.zone_folder
  20. min_max_filename = cfg.min_max_filename_extension
  21. # define all scenes values
  22. scenes_list = cfg.scenes_names
  23. scenes_indices = cfg.scenes_indices
  24. path = cfg.dataset_path
  25. zones = cfg.zones_indices
  26. seuil_expe_filename = cfg.seuil_expe_filename
  27. features_choices = cfg.features_choices_labels
  28. output_data_folder = cfg.output_data_folder
  29. generic_output_file_svd = '_random.csv'
  30. def generate_data(transformation, _scenes):
  31. """
  32. @brief Method which generates all .csv files from scenes
  33. @return nothing
  34. """
  35. scenes = os.listdir(path)
  36. # remove min max file from scenes folder
  37. scenes = [s for s in scenes if min_max_filename not in s]
  38. # go ahead each scenes
  39. for id_scene, folder_scene in enumerate(scenes):
  40. if folder_scene in _scenes:
  41. print(folder_scene)
  42. scene_path = os.path.join(path, folder_scene)
  43. # construct each zones folder name
  44. zones_folder = []
  45. features_folder = []
  46. zones_threshold = []
  47. # get zones list info
  48. for index in zones:
  49. index_str = str(index)
  50. if len(index_str) < 2:
  51. index_str = "0" + index_str
  52. current_zone = "zone"+index_str
  53. zones_folder.append(current_zone)
  54. zone_path = os.path.join(scene_path, current_zone)
  55. with open(os.path.join(zone_path, cfg.seuil_expe_filename)) as f:
  56. zones_threshold.append(int(f.readline()))
  57. # custom path for feature
  58. feature_path = os.path.join(zone_path, transformation.getName())
  59. if not os.path.exists(feature_path):
  60. os.makedirs(feature_path)
  61. # custom path for interval of reconstruction and feature
  62. feature_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  63. features_folder.append(feature_interval_path)
  64. if not os.path.exists(feature_interval_path):
  65. os.makedirs(feature_interval_path)
  66. # create for each zone the labels folder
  67. labels = [cfg.not_noisy_folder, cfg.noisy_folder]
  68. for label in labels:
  69. label_folder = os.path.join(feature_interval_path, label)
  70. if not os.path.exists(label_folder):
  71. os.makedirs(label_folder)
  72. # get all images of folder
  73. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  74. number_scene_image = len(scene_images)
  75. # for each images
  76. for id_img, img_path in enumerate(scene_images):
  77. current_img = Image.open(img_path)
  78. img_blocks = divide_in_blocks(current_img, cfg.sub_image_size)
  79. current_quality_index = int(get_scene_image_quality(img_path))
  80. for id_block, block in enumerate(img_blocks):
  81. ##########################
  82. # Image computation part #
  83. ##########################
  84. # pass block to grey level
  85. output_block = transformation.getTransformedImage(block)
  86. output_block = np.array(output_block, 'uint8')
  87. # current output image
  88. output_block_img = Image.fromarray(output_block)
  89. label_path = features_folder[id_block]
  90. # get label folder for block
  91. if current_quality_index > zones_threshold[id_block]:
  92. label_path = os.path.join(label_path, cfg.not_noisy_folder)
  93. else:
  94. label_path = os.path.join(label_path, cfg.noisy_folder)
  95. # Data augmentation!
  96. rotations = [0, 90, 180, 270]
  97. img_flip_labels = ['original', 'horizontal', 'vertical', 'both']
  98. horizontal_img = output_block_img.transpose(Image.FLIP_LEFT_RIGHT)
  99. vertical_img = output_block_img.transpose(Image.FLIP_TOP_BOTTOM)
  100. both_img = output_block_img.transpose(Image.TRANSPOSE)
  101. flip_images = [output_block_img, horizontal_img, vertical_img, both_img]
  102. # rotate and flip image to increase dataset size
  103. for id, flip in enumerate(flip_images):
  104. for rotation in rotations:
  105. rotated_output_img = flip.rotate(rotation)
  106. output_reconstructed_filename = img_path.split('/')[-1].replace('.png', '') + '_' + zones_folder[id_block] + cfg.post_image_name_separator
  107. output_reconstructed_filename = output_reconstructed_filename + img_flip_labels[id] + '_' + str(rotation) + '.png'
  108. output_reconstructed_path = os.path.join(label_path, output_reconstructed_filename)
  109. rotated_output_img.save(output_reconstructed_path)
  110. print(transformation.getName() + "_" + folder_scene + " - " + "{0:.2f}".format(((id_img + 1) / number_scene_image)* 100.) + "%")
  111. sys.stdout.write("\033[F")
  112. print('\n')
  113. print("%s_%s : end of data generation\n" % (transformation.getName(), transformation.getParam()))
  114. def main():
  115. parser = argparse.ArgumentParser(description="Compute and prepare data of feature of all scenes using specific interval if necessary")
  116. parser.add_argument('--features', type=str,
  117. help="list of features choice in order to compute data",
  118. default='svd_reconstruction, ipca_reconstruction',
  119. required=True)
  120. parser.add_argument('--params', type=str,
  121. help="list of specific param for each feature choice (See README.md for further information in 3D mode)",
  122. default='100, 200 :: 50, 25',
  123. required=True)
  124. parser.add_argument('--size', type=str,
  125. help="specific size of image",
  126. default='100, 100',
  127. required=True)
  128. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  129. args = parser.parse_args()
  130. p_features = list(map(str.strip, args.features.split(',')))
  131. p_params = list(map(str.strip, args.params.split('::')))
  132. p_size = args.size
  133. p_scenes = args.scenes.split(',')
  134. # getting scenes from indexes user selection
  135. scenes_selected = []
  136. for scene_id in p_scenes:
  137. index = scenes_indices.index(scene_id.strip())
  138. scenes_selected.append(scenes_list[index])
  139. # list of transformations
  140. transformations = []
  141. for id, feature in enumerate(p_features):
  142. if feature not in features_choices or feature == 'static':
  143. raise ValueError("Unknown feature, please select a correct feature (`static` excluded) : ", features_choices)
  144. transformations.append(Transformation(feature, p_params[id], p_size))
  145. print("Scenes used", scenes_selected)
  146. # generate all or specific feature data
  147. for transformation in transformations:
  148. generate_data(transformation, scenes_selected)
  149. if __name__== "__main__":
  150. main()