generate_dataset_sequence_file.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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(output_data_folder, _filename, _filename + ".train")
  20. output_test_filename = os.path.join(output_data_folder, _filename, _filename + ".test")
  21. # create path if not exists
  22. if not os.path.exists(os.path.join(output_data_folder, _filename)):
  23. os.makedirs(os.path.join(output_data_folder, _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. transform_image_path = os.path.join(scene_path, transformation.getName(), image_name)
  58. static_transform_image = Image.open(transform_image_path)
  59. static_transform_image_block = divide_in_blocks(static_transform_image, cfg.sub_image_size)[id_zone]
  60. dt.augmented_data_image(static_transform_image_block, image_folder_path, image_prefix_name)
  61. else:
  62. metric_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  63. features_path.append(metric_interval_path)
  64. # as labels are same for each metric
  65. for label in os.listdir(features_path[0]):
  66. label_features_path = []
  67. for path in features_path:
  68. label_path = os.path.join(path, label)
  69. label_features_path.append(label_path)
  70. # getting images list for each metric
  71. features_images_list = []
  72. for index_metric, label_path in enumerate(label_features_path):
  73. if _transformations[index_metric].getName() == 'static':
  74. # by default append nothing..
  75. features_images_list.append([])
  76. else:
  77. images = sorted(os.listdir(label_path))
  78. features_images_list.append(images)
  79. sequence_data = []
  80. # construct each line using all images path of each
  81. for index_image in range(0, len(features_images_list[0])):
  82. images_path = []
  83. # get information about rotation and flip from first transformation (need to be a not static transformation)
  84. current_post_fix = features_images_list[0][index_image].split(cfg.post_image_name_separator)[-1]
  85. # getting images with same index and hence name for each metric (transformation)
  86. for index_metric in range(0, len(features_path)):
  87. # custom behavior for static transformation (need to check specific image)
  88. if _transformations[index_metric].getName() == 'static':
  89. # add static path with selecting correct data augmented image
  90. image_name = _transformations[index_metric].getParam().split('/')[-1].replace('.png', '')
  91. img_path = os.path.join(features_path[index_metric], image_name + cfg.post_image_name_separator + current_post_fix)
  92. images_path.append(img_path)
  93. else:
  94. img_path = features_images_list[index_metric][index_image]
  95. images_path.append(os.path.join(label_features_path[index_metric], img_path))
  96. if label == cfg.noisy_folder:
  97. line = '1;'
  98. else:
  99. line = '0;'
  100. # add new data information into sequence
  101. sequence_data.append(images_path)
  102. if len(sequence_data) >= _sequence:
  103. # prepare whole line for LSTM model kind
  104. # keeping last noisy label
  105. for id_seq, seq_images_path in enumerate(sequence_data):
  106. # compute line information with all images paths
  107. for id_path, img_path in enumerate(seq_images_path):
  108. if id_path < len(seq_images_path) - 1:
  109. line = line + img_path + '::'
  110. else:
  111. line = line + img_path
  112. if id_seq < len(sequence_data) - 1:
  113. line += ';'
  114. line = line + '\n'
  115. if id_zone in train_zones:
  116. # train_file_data.append(line)
  117. train_file.write(line)
  118. else:
  119. # test_file_data.append(line)
  120. test_file.write(line)
  121. # remove first element (sliding window)
  122. del sequence_data[0]
  123. # random.shuffle(train_file_data)
  124. # random.shuffle(test_file_data)
  125. # for line in train_file_data:
  126. # train_file.write(line)
  127. # for line in test_file_data:
  128. # test_file.write(line)
  129. train_file.close()
  130. test_file.close()
  131. def main():
  132. parser = argparse.ArgumentParser(description="Compute specific dataset for model using of metric")
  133. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  134. parser.add_argument('--folder', type=str,
  135. help='folder where generated data are available',
  136. required=True)
  137. parser.add_argument('--features', type=str,
  138. help="list of features choice in order to compute data",
  139. default='svd_reconstruction, ipca_reconstruction',
  140. required=True)
  141. parser.add_argument('--params', type=str,
  142. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  143. default='100, 200 :: 50, 25',
  144. required=True)
  145. parser.add_argument('--sequence', type=int, help='sequence length expected', 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_sequence = args.sequence
  156. p_size = args.size # not necessary to split here
  157. p_selected_zones = args.selected_zones
  158. selected_zones = {}
  159. with(open(p_selected_zones, 'r')) as f:
  160. for line in f.readlines():
  161. data = line.split(';')
  162. del data[-1]
  163. scene_name = data[0]
  164. thresholds = data[1:]
  165. selected_zones[scene_name] = [ int(t) for t in thresholds ]
  166. # create list of Transformation
  167. transformations = []
  168. for id, feature in enumerate(p_features):
  169. if feature not in features_choices:
  170. raise ValueError("Unknown metric, please select a correct metric : ", features_choices)
  171. transformations.append(Transformation(feature, p_params[id], p_size))
  172. if transformations[0].getName() == 'static':
  173. raise ValueError("The first transformation in list cannot be static")
  174. # create database using img folder (generate first time only)
  175. generate_data_model(p_filename, transformations, p_folder, selected_zones, p_sequence)
  176. if __name__== "__main__":
  177. main()