generate_dataset.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. import sys, os, argparse
  8. import numpy as np
  9. import random
  10. import time
  11. import json
  12. from PIL import Image
  13. from ipfml import processing, metrics, utils
  14. from skimage import color
  15. from modules.utils import config as cfg
  16. from modules.utils import data as dt
  17. from transformation_functions import svd_reconstruction
  18. from modules.classes.Transformation import Transformation
  19. # getting configuration information
  20. config_filename = cfg.config_filename
  21. zone_folder = cfg.zone_folder
  22. learned_folder = cfg.learned_zones_folder
  23. min_max_filename = cfg.min_max_filename_extension
  24. # define all scenes values
  25. scenes_list = cfg.scenes_names
  26. scenes_indexes = cfg.scenes_indices
  27. choices = cfg.normalization_choices
  28. dataset_path = cfg.dataset_path
  29. zones = cfg.zones_indices
  30. seuil_expe_filename = cfg.seuil_expe_filename
  31. metric_choices = cfg.metric_choices_labels
  32. output_data_folder = cfg.output_data_folder
  33. generic_output_file_svd = '_random.csv'
  34. def generate_data_model(_scenes_list, _filename, _transformations, _scenes, _nb_zones = 4, _random=0, _only_noisy=0):
  35. output_train_filename = _filename + ".train"
  36. output_test_filename = _filename + ".test"
  37. if not '/' in output_train_filename:
  38. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  39. # create path if not exists
  40. if not os.path.exists(output_data_folder):
  41. os.makedirs(output_data_folder)
  42. train_file_data = []
  43. test_file_data = []
  44. scenes = os.listdir(dataset_path)
  45. # remove min max file from scenes folder
  46. scenes = [s for s in scenes if min_max_filename not in s]
  47. # go ahead each scenes
  48. for id_scene, folder_scene in enumerate(_scenes_list):
  49. scene_path = os.path.join(dataset_path, folder_scene)
  50. config_file_path = os.path.join(scene_path, config_filename)
  51. # only get last image path
  52. with open(config_file_path, "r") as config_file:
  53. last_image_name = config_file.readline().strip()
  54. ref_image_path = os.path.join(scene_path, last_image_name)
  55. zones_indices = zones
  56. # shuffle list of zones (=> randomly choose zones)
  57. # only in random mode
  58. if _random:
  59. random.shuffle(zones_indices)
  60. # store zones learned
  61. learned_zones_indices = zones_indices[:_nb_zones]
  62. # write into file
  63. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  64. if not os.path.exists(folder_learned_path):
  65. os.makedirs(folder_learned_path)
  66. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  67. with open(file_learned_path, 'w') as f:
  68. for i in learned_zones_indices:
  69. f.write(str(i) + ';')
  70. ref_image_blocks = processing.divide_in_blocks(Image.open(ref_image_path), cfg.keras_img_size)
  71. for id_zone, index_folder in enumerate(zones_indices):
  72. index_str = str(index_folder)
  73. if len(index_str) < 2:
  74. index_str = "0" + index_str
  75. current_zone_folder = "zone" + index_str
  76. zone_path = os.path.join(scene_path, current_zone_folder)
  77. # path of zone of reference image
  78. ref_image_block_path = os.path.join(zone_path, last_image_name)
  79. if not os.path.exists(ref_image_block_path):
  80. ref_image_blocks[id_zone].save(ref_image_block_path)
  81. # custom path for interval of reconstruction and metric
  82. metrics_path = []
  83. for transformation in _transformations:
  84. metric_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  85. metrics_path.append(metric_interval_path)
  86. # as labels are same for each metric
  87. for label in os.listdir(metrics_path[0]):
  88. if (label == cfg.not_noisy_folder and _only_noisy == 0) or label == cfg.noisy_folder:
  89. label_metrics_path = []
  90. for path in metrics_path:
  91. label_path = os.path.join(path, label)
  92. label_metrics_path.append(label_path)
  93. # getting images list for each metric
  94. metrics_images_list = []
  95. for label_path in label_metrics_path:
  96. images = sorted(os.listdir(label_path))
  97. metrics_images_list.append(images)
  98. # construct each line using all images path of each
  99. for index_image in range(0, len(metrics_images_list[0])):
  100. images_path = []
  101. # getting images with same index and hence name for each metric (transformation)
  102. for index_metric in range(0, len(metrics_path)):
  103. img_path = metrics_images_list[index_metric][index_image]
  104. images_path.append(os.path.join(label_metrics_path[index_metric], img_path))
  105. line = ref_image_block_path + ';'
  106. # compute line information with all images paths
  107. for id_path, img_path in enumerate(images_path):
  108. if id_path < len(images_path) - 1:
  109. line = line + img_path + '::'
  110. else:
  111. line = line + img_path
  112. line = line + '\n'
  113. if id_zone < _nb_zones and folder_scene in _scenes:
  114. train_file_data.append(line)
  115. else:
  116. test_file_data.append(line)
  117. train_file = open(output_train_filename, 'w')
  118. test_file = open(output_test_filename, 'w')
  119. random.shuffle(train_file_data)
  120. random.shuffle(test_file_data)
  121. for line in train_file_data:
  122. train_file.write(line)
  123. for line in test_file_data:
  124. test_file.write(line)
  125. train_file.close()
  126. test_file.close()
  127. def main():
  128. parser = argparse.ArgumentParser(description="Compute specific dataset for model using of metric")
  129. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  130. parser.add_argument('--metrics', type=str,
  131. help="list of metrics choice in order to compute data",
  132. default='svd_reconstruction, ipca_reconstruction',
  133. required=True)
  134. parser.add_argument('--params', type=str,
  135. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  136. default='100, 200 :: 50, 25',
  137. required=True)
  138. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  139. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set', choices=list(range(1, 17)))
  140. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=cfg.renderer_choices, default='all')
  141. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  142. parser.add_argument('--only_noisy', type=int, help='Only noisy will be used', choices=[0, 1])
  143. args = parser.parse_args()
  144. p_filename = args.output
  145. p_metrics = list(map(str.strip, args.metrics.split(',')))
  146. p_params = list(map(str.strip, args.params.split('::')))
  147. p_scenes = args.scenes.split(',')
  148. p_nb_zones = args.nb_zones
  149. p_renderer = args.renderer
  150. p_random = args.random
  151. p_only_noisy = args.only_noisy
  152. # create list of Transformation
  153. transformations = []
  154. for id, metric in enumerate(p_metrics):
  155. if metric not in metric_choices:
  156. raise ValueError("Unknown metric, please select a correct metric : ", metric_choices)
  157. transformations.append(Transformation(metric, p_params[id]))
  158. # list all possibles choices of renderer
  159. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  160. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  161. # getting scenes from indexes user selection
  162. scenes_selected = []
  163. for scene_id in p_scenes:
  164. index = scenes_indices.index(scene_id.strip())
  165. scenes_selected.append(scenes_list[index])
  166. # create database using img folder (generate first time only)
  167. generate_data_model(scenes_list, p_filename, transformations, scenes_selected, p_nb_zones, p_random, p_only_noisy)
  168. if __name__== "__main__":
  169. main()