generate_dataset.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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):
  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. zones_indices = zones
  51. # shuffle list of zones (=> randomly choose zones)
  52. # only in random mode
  53. if _random:
  54. random.shuffle(zones_indices)
  55. # store zones learned
  56. learned_zones_indices = zones_indices[:_nb_zones]
  57. # write into file
  58. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  59. if not os.path.exists(folder_learned_path):
  60. os.makedirs(folder_learned_path)
  61. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  62. with open(file_learned_path, 'w') as f:
  63. for i in learned_zones_indices:
  64. f.write(str(i) + ';')
  65. for id_zone, index_folder in enumerate(zones_indices):
  66. index_str = str(index_folder)
  67. if len(index_str) < 2:
  68. index_str = "0" + index_str
  69. current_zone_folder = "zone" + index_str
  70. zone_path = os.path.join(scene_path, current_zone_folder)
  71. # custom path for interval of reconstruction and metric
  72. metrics_path = []
  73. for transformation in _transformations:
  74. metric_interval_path = os.path.join(zone_path, transformation.getTransformationPath())
  75. metrics_path.append(metric_interval_path)
  76. # as labels are same for each metric
  77. for label in os.listdir(metrics_path[0]):
  78. label_metrics_path = []
  79. for path in metrics_path:
  80. label_path = os.path.join(path, label)
  81. label_metrics_path.append(label_path)
  82. # getting images list for each metric
  83. metrics_images_list = []
  84. for label_path in label_metrics_path:
  85. images = sorted(os.listdir(label_path))
  86. metrics_images_list.append(images)
  87. # construct each line using all images path of each
  88. for index_image in range(0, len(metrics_images_list[0])):
  89. images_path = []
  90. # getting images with same index and hence name for each metric (transformation)
  91. for index_metric in range(0, len(metrics_path)):
  92. img_path = metrics_images_list[index_metric][index_image]
  93. images_path.append(os.path.join(label_metrics_path[index_metric], img_path))
  94. if label == cfg.noisy_folder:
  95. line = '1;'
  96. else:
  97. line = '0;'
  98. # compute line information with all images paths
  99. for id_path, img_path in enumerate(images_path):
  100. if id_path < len(images_path) - 1:
  101. line = line + img_path + '::'
  102. else:
  103. line = line + img_path
  104. line = line + '\n'
  105. if id_zone < _nb_zones and folder_scene in _scenes:
  106. train_file_data.append(line)
  107. else:
  108. test_file_data.append(line)
  109. train_file = open(output_train_filename, 'w')
  110. test_file = open(output_test_filename, 'w')
  111. random.shuffle(train_file_data)
  112. random.shuffle(test_file_data)
  113. for line in train_file_data:
  114. train_file.write(line)
  115. for line in test_file_data:
  116. test_file.write(line)
  117. train_file.close()
  118. test_file.close()
  119. def main():
  120. parser = argparse.ArgumentParser(description="Compute specific dataset for model using of metric")
  121. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  122. parser.add_argument('--metrics', type=str,
  123. help="list of metrics choice in order to compute data",
  124. default='svd_reconstruction, ipca_reconstruction',
  125. required=True)
  126. parser.add_argument('--params', type=str,
  127. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  128. default='100, 200 :: 50, 25',
  129. required=True)
  130. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  131. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set', choices=list(range(1, 17)))
  132. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=cfg.renderer_choices, default='all')
  133. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  134. args = parser.parse_args()
  135. p_filename = args.output
  136. p_metrics = list(map(str.strip, args.metrics.split(',')))
  137. p_params = list(map(str.strip, args.params.split('::')))
  138. p_scenes = args.scenes.split(',')
  139. p_nb_zones = args.nb_zones
  140. p_renderer = args.renderer
  141. p_random = args.random
  142. # create list of Transformation
  143. transformations = []
  144. for id, metric in enumerate(p_metrics):
  145. if metric not in metric_choices:
  146. raise ValueError("Unknown metric, please select a correct metric : ", metric_choices)
  147. transformations.append(Transformation(metric, p_params[id]))
  148. # list all possibles choices of renderer
  149. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  150. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  151. # getting scenes from indexes user selection
  152. scenes_selected = []
  153. for scene_id in p_scenes:
  154. index = scenes_indices.index(scene_id.strip())
  155. scenes_selected.append(scenes_list[index])
  156. # create database using img folder (generate first time only)
  157. generate_data_model(scenes_list, p_filename, transformations, scenes_selected, p_nb_zones, p_random)
  158. if __name__== "__main__":
  159. main()