generate_dataset_sequence_file.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 config as cfg
  17. from transformations import Transformation
  18. def generate_data_model(_filename, _transformations, _dataset_folder, _selected_zones, _sequence):
  19. output_train_filename = os.path.join(cfg.output_datasets, _filename, _filename + ".train")
  20. output_test_filename = os.path.join(cfg.output_datasets, _filename, _filename + ".test")
  21. # create path if not exists
  22. if not os.path.exists(os.path.join(cfg.output_datasets, _filename)):
  23. os.makedirs(os.path.join(cfg.output_datasets, _filename))
  24. train_file = open(output_train_filename, 'w')
  25. test_file = open(output_test_filename, 'w')
  26. # train_file_data = []
  27. # test_file_data = []
  28. # specific number of zones (zones indices)
  29. zones = np.arange(16)
  30. # go ahead each scenes
  31. for folder_scene in _selected_zones:
  32. scene_path = os.path.join(_dataset_folder, folder_scene)
  33. train_zones = _selected_zones[folder_scene]
  34. for id_zone, index_folder in enumerate(zones):
  35. index_str = str(index_folder)
  36. if len(index_str) < 2:
  37. index_str = "0" + index_str
  38. current_zone_folder = "zone" + index_str
  39. zone_path = os.path.join(scene_path, current_zone_folder)
  40. # custom path for interval of reconstruction and metric
  41. features_path = []
  42. for transformation in _transformations:
  43. # check if it's a static content and create augmented images if necessary
  44. if transformation.getName() == 'static':
  45. # {sceneName}/zoneXX/static
  46. static_metric_path = os.path.join(zone_path, transformation.getName())
  47. # img.png
  48. image_name = transformation.getParam().split('/')[-1]
  49. # {sceneName}/zoneXX/static/img
  50. image_prefix_name = image_name.replace('.png', '')
  51. image_folder_path = os.path.join(static_metric_path, image_prefix_name)
  52. if not os.path.exists(image_folder_path):
  53. os.makedirs(image_folder_path)
  54. features_path.append(image_folder_path)
  55. # get image path to manage
  56. # {sceneName}/static/img.png
  57. # TODO : check this part
  58. #transform_image_path = os.path.join(scene_path, transformation.getName(), image_name)
  59. #static_transform_image = Image.open(transform_image_path)
  60. #static_transform_image_block = divide_in_blocks(static_transform_image, cfg.sub_image_size)[id_zone]
  61. #transformation.augmented_data_image(static_transform_image_block, image_folder_path, image_prefix_name)
  62. else:
  63. metric_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  64. features_path.append(metric_interval_path)
  65. # as labels are same for each metric
  66. for label in os.listdir(features_path[0]):
  67. label_features_path = []
  68. for path in features_path:
  69. label_path = os.path.join(path, label)
  70. label_features_path.append(label_path)
  71. # getting images list for each metric
  72. features_images_list = []
  73. for index_metric, label_path in enumerate(label_features_path):
  74. if _transformations[index_metric].getName() == 'static':
  75. # by default append nothing..
  76. features_images_list.append([])
  77. else:
  78. images = sorted(os.listdir(label_path))
  79. features_images_list.append(images)
  80. sequence_data = []
  81. # construct each line using all images path of each
  82. for index_image in range(0, len(features_images_list[0])):
  83. images_path = []
  84. # get information about rotation and flip from first transformation (need to be a not static transformation)
  85. current_post_fix = features_images_list[0][index_image].split(cfg.post_image_name_separator)[-1]
  86. # getting images with same index and hence name for each metric (transformation)
  87. for index_metric in range(0, len(features_path)):
  88. # custom behavior for static transformation (need to check specific image)
  89. if _transformations[index_metric].getName() == 'static':
  90. # add static path with selecting correct data augmented image
  91. image_name = _transformations[index_metric].getParam().split('/')[-1].replace('.png', '')
  92. img_path = os.path.join(features_path[index_metric], image_name + cfg.post_image_name_separator + current_post_fix)
  93. images_path.append(img_path)
  94. else:
  95. img_path = features_images_list[index_metric][index_image]
  96. images_path.append(os.path.join(label_features_path[index_metric], img_path))
  97. if label == cfg.noisy_folder:
  98. line = '1;'
  99. else:
  100. line = '0;'
  101. # add new data information into sequence
  102. sequence_data.append(images_path)
  103. if len(sequence_data) >= _sequence:
  104. # prepare whole line for LSTM model kind
  105. # keeping last noisy label
  106. for id_seq, seq_images_path in enumerate(sequence_data):
  107. # compute line information with all images paths
  108. for id_path, img_path in enumerate(seq_images_path):
  109. if id_path < len(seq_images_path) - 1:
  110. line = line + img_path + '::'
  111. else:
  112. line = line + img_path
  113. if id_seq < len(sequence_data) - 1:
  114. line += ';'
  115. line = line + '\n'
  116. if id_zone in train_zones:
  117. # train_file_data.append(line)
  118. train_file.write(line)
  119. else:
  120. # test_file_data.append(line)
  121. test_file.write(line)
  122. # remove first element (sliding window)
  123. del sequence_data[0]
  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('--folder', type=str,
  136. help='folder where generated data are available',
  137. required=True)
  138. parser.add_argument('--features', type=str,
  139. help="list of features choice in order to compute data",
  140. default='svd_reconstruction, ipca_reconstruction',
  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('--sequence', type=int, help='sequence length expected', required=True)
  147. parser.add_argument('--size', type=str,
  148. help="Size of input images",
  149. default="100, 100")
  150. parser.add_argument('--selected_zones', type=str, help='file which contains all selected zones of scene', required=True)
  151. args = parser.parse_args()
  152. p_filename = args.output
  153. p_folder = args.folder
  154. p_features = list(map(str.strip, args.features.split(',')))
  155. p_params = list(map(str.strip, args.params.split('::')))
  156. p_sequence = args.sequence
  157. p_size = args.size # not necessary to split here
  158. p_selected_zones = args.selected_zones
  159. selected_zones = {}
  160. with(open(p_selected_zones, 'r')) as f:
  161. for line in f.readlines():
  162. data = line.split(';')
  163. del data[-1]
  164. scene_name = data[0]
  165. thresholds = data[1:]
  166. selected_zones[scene_name] = [ int(t) for t in thresholds ]
  167. # create list of Transformation
  168. transformations = []
  169. for id, feature in enumerate(p_features):
  170. if feature not in cfg.features_choices_labels:
  171. raise ValueError("Unknown metric, please select a correct metric : ", cfg.features_choices_labels)
  172. transformations.append(Transformation(feature, p_params[id], p_size))
  173. if transformations[0].getName() == 'static':
  174. raise ValueError("The first transformation in list cannot be static")
  175. # create database using img folder (generate first time only)
  176. generate_data_model(p_filename, transformations, p_folder, selected_zones, p_sequence)
  177. if __name__== "__main__":
  178. main()