generate_dataset_file.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. import random
  11. # images processing imports
  12. from PIL import Image
  13. from ipfml.processing.segmentation import divide_in_blocks
  14. # modules imports
  15. sys.path.insert(0, '') # trick to enable import of main folder module
  16. import custom_config as cfg
  17. from modules.utils import data as dt
  18. from modules.classes.Transformation import Transformation
  19. # getting configuration information
  20. zone_folder = cfg.zone_folder
  21. learned_folder = cfg.learned_zones_folder
  22. min_max_filename = cfg.min_max_filename_extension
  23. # define all scenes values
  24. scenes_list = cfg.scenes_names
  25. scenes_indices = cfg.scenes_indices
  26. dataset_path = cfg.dataset_path
  27. zones = cfg.zones_indices
  28. seuil_expe_filename = cfg.seuil_expe_filename
  29. features_choices = cfg.features_choices_labels
  30. output_data_folder = cfg.output_datasets
  31. generic_output_file_svd = '_random.csv'
  32. def generate_data_model(_filename, _transformations, _dataset_folder, _selected_zones):
  33. output_train_filename = os.path.join(output_data_folder, _filename, _filename + ".train")
  34. output_test_filename = os.path.join(output_data_folder, _filename, _filename + ".test")
  35. # create path if not exists
  36. if not os.path.exists(os.path.join(output_data_folder, _filename)):
  37. os.makedirs(os.path.join(output_data_folder, _filename))
  38. train_file_data = []
  39. test_file_data = []
  40. # specific number of zones (zones indices)
  41. zones = np.arange(16)
  42. # go ahead each scenes
  43. for folder_scene in _selected_zones:
  44. scene_path = os.path.join(_dataset_folder, folder_scene)
  45. train_zones = _selected_zones[folder_scene]
  46. for id_zone, index_folder in enumerate(zones):
  47. index_str = str(index_folder)
  48. if len(index_str) < 2:
  49. index_str = "0" + index_str
  50. current_zone_folder = "zone" + index_str
  51. zone_path = os.path.join(scene_path, current_zone_folder)
  52. # custom path for interval of reconstruction and metric
  53. features_path = []
  54. for transformation in _transformations:
  55. # check if it's a static content and create augmented images if necessary
  56. if transformation.getName() == 'static':
  57. # {sceneName}/zoneXX/static
  58. static_metric_path = os.path.join(zone_path, transformation.getName())
  59. # img.png
  60. image_name = transformation.getParam().split('/')[-1]
  61. # {sceneName}/zoneXX/static/img
  62. image_prefix_name = image_name.replace('.png', '')
  63. image_folder_path = os.path.join(static_metric_path, image_prefix_name)
  64. if not os.path.exists(image_folder_path):
  65. os.makedirs(image_folder_path)
  66. features_path.append(image_folder_path)
  67. # get image path to manage
  68. # {sceneName}/static/img.png
  69. transform_image_path = os.path.join(scene_path, transformation.getName(), image_name)
  70. static_transform_image = Image.open(transform_image_path)
  71. static_transform_image_block = divide_in_blocks(static_transform_image, cfg.sub_image_size)[id_zone]
  72. dt.augmented_data_image(static_transform_image_block, image_folder_path, image_prefix_name)
  73. else:
  74. metric_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  75. features_path.append(metric_interval_path)
  76. # as labels are same for each metric
  77. for label in os.listdir(features_path[0]):
  78. label_features_path = []
  79. for path in features_path:
  80. label_path = os.path.join(path, label)
  81. label_features_path.append(label_path)
  82. # getting images list for each metric
  83. features_images_list = []
  84. for index_metric, label_path in enumerate(label_features_path):
  85. if _transformations[index_metric].getName() == 'static':
  86. # by default append nothing..
  87. features_images_list.append([])
  88. else:
  89. images = sorted(os.listdir(label_path))
  90. features_images_list.append(images)
  91. # construct each line using all images path of each
  92. for index_image in range(0, len(features_images_list[0])):
  93. images_path = []
  94. # get information about rotation and flip from first transformation (need to be a not static transformation)
  95. current_post_fix = features_images_list[0][index_image].split(cfg.post_image_name_separator)[-1]
  96. # getting images with same index and hence name for each metric (transformation)
  97. for index_metric in range(0, len(features_path)):
  98. # custom behavior for static transformation (need to check specific image)
  99. if _transformations[index_metric].getName() == 'static':
  100. # add static path with selecting correct data augmented image
  101. image_name = _transformations[index_metric].getParam().split('/')[-1].replace('.png', '')
  102. img_path = os.path.join(features_path[index_metric], image_name + cfg.post_image_name_separator + current_post_fix)
  103. images_path.append(img_path)
  104. else:
  105. img_path = features_images_list[index_metric][index_image]
  106. images_path.append(os.path.join(label_features_path[index_metric], img_path))
  107. if label == cfg.noisy_folder:
  108. line = '1;'
  109. else:
  110. line = '0;'
  111. # compute line information with all images paths
  112. for id_path, img_path in enumerate(images_path):
  113. if id_path < len(images_path) - 1:
  114. line = line + img_path + '::'
  115. else:
  116. line = line + img_path
  117. line = line + '\n'
  118. if id_zone in train_zones:
  119. train_file_data.append(line)
  120. else:
  121. test_file_data.append(line)
  122. train_file = open(output_train_filename, 'w')
  123. test_file = open(output_test_filename, 'w')
  124. random.shuffle(train_file_data)
  125. random.shuffle(test_file_data)
  126. for line in train_file_data:
  127. train_file.write(line)
  128. for line in test_file_data:
  129. test_file.write(line)
  130. train_file.close()
  131. test_file.close()
  132. def main():
  133. parser = argparse.ArgumentParser(description="Compute specific dataset for model using of metric")
  134. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  135. parser.add_argument('--features', type=str,
  136. help="list of features choice in order to compute data",
  137. default='svd_reconstruction, ipca_reconstruction',
  138. required=True)
  139. parser.add_argument('--folder', type=str,
  140. help='folder where generated data are available',
  141. required=True)
  142. parser.add_argument('--params', type=str,
  143. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  144. default='100, 200 :: 50, 25',
  145. required=True)
  146. parser.add_argument('--size', type=str,
  147. help="Size of input images",
  148. default="100, 100")
  149. parser.add_argument('--selected_zones', type=str, help='file which contains all selected zones of scene', required=True)
  150. args = parser.parse_args()
  151. p_filename = args.output
  152. p_folder = args.folder
  153. p_features = list(map(str.strip, args.features.split(',')))
  154. p_params = list(map(str.strip, args.params.split('::')))
  155. p_size = args.size # not necessary to split here
  156. p_selected_zones = args.selected_zones
  157. selected_zones = {}
  158. with(open(p_selected_zones, 'r')) as f:
  159. for line in f.readlines():
  160. data = line.split(';')
  161. del data[-1]
  162. scene_name = data[0]
  163. thresholds = data[1:]
  164. selected_zones[scene_name] = [ int(t) for t in thresholds ]
  165. # create list of Transformation
  166. transformations = []
  167. for id, feature in enumerate(p_features):
  168. if feature not in features_choices:
  169. raise ValueError("Unknown metric, please select a correct metric : ", features_choices)
  170. transformations.append(Transformation(feature, p_params[id], p_size))
  171. if transformations[0].getName() == 'static':
  172. raise ValueError("The first transformation in list cannot be static")
  173. # create database using img folder (generate first time only)
  174. generate_data_model(p_filename, transformations, p_folder, selected_zones)
  175. if __name__== "__main__":
  176. main()