generate_data_model_random.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Sep 14 21:02:42 2018
  5. @author: jbuisine
  6. """
  7. from __future__ import print_function
  8. import sys, os, getopt
  9. import numpy as np
  10. import random
  11. import time
  12. import json
  13. from PIL import Image
  14. from ipfml import processing, metrics, utils
  15. from modules.utils import config as cfg
  16. from modules.utils import data as dt
  17. # getting configuration information
  18. zone_folder = cfg.zone_folder
  19. min_max_filename = cfg.min_max_filename_extension
  20. # define all scenes values
  21. all_scenes_list = cfg.scenes_names
  22. all_scenes_indices = cfg.scenes_indices
  23. choices = cfg.normalization_choices
  24. path = cfg.dataset_path
  25. zones = cfg.zones_indices
  26. seuil_expe_filename = cfg.seuil_expe_filename
  27. metric_choices = cfg.metric_choices_labels
  28. output_data_folder = cfg.output_data_folder
  29. custom_min_max_folder = cfg.min_max_custom_folder
  30. min_max_ext = cfg.min_max_filename_extension
  31. calibration_folder = 'calibration'
  32. generic_output_file_svd = '_random.csv'
  33. min_value_interval = sys.maxsize
  34. max_value_interval = 0
  35. def construct_new_line(path_seuil, interval, line, norm):
  36. begin, end = interval
  37. line_data = line.split(';')
  38. seuil = line_data[0]
  39. metrics = line_data[begin+1:end+1]
  40. metrics = [float(m) for m in metrics]
  41. # TODO : check if it's always necessary to do that (loss of information for svd)
  42. if norm:
  43. metrics = utils.normalize_arr_with_range(metrics, min_value_interval, max_value_interval)
  44. with open(path_seuil, "r") as seuil_file:
  45. seuil_learned = int(seuil_file.readline().strip())
  46. if seuil_learned > int(seuil):
  47. line = '1'
  48. else:
  49. line = '0'
  50. for idx, val in enumerate(metrics):
  51. line += ';'
  52. line += str(val)
  53. line += '\n'
  54. return line
  55. def get_min_max_value_interval(_scenes_list, _filename, _interval, _choice, _color, _metric):
  56. global min_value_interval, max_value_interval
  57. scenes = os.listdir(path)
  58. # remove min max file from scenes folder
  59. scenes = [s for s in scenes if min_max_filename not in s]
  60. # remove calibration mire from images
  61. scenes = [s for s in scenes if calibration_folder not in s]
  62. for id_scene, folder_scene in enumerate(scenes):
  63. # only take care of synthesis scenes
  64. if folder_scene in _scenes_list:
  65. scene_path = os.path.join(path, folder_scene)
  66. zones_folder = []
  67. # create zones list
  68. for index in zones:
  69. index_str = str(index)
  70. if len(index_str) < 2:
  71. index_str = "0" + index_str
  72. zones_folder.append("zone"+index_str)
  73. # shuffle list of zones (=> randomly choose zones)
  74. random.shuffle(zones_folder)
  75. for id_zone, zone_folder in enumerate(zones_folder):
  76. zone_path = os.path.join(scene_path, zone_folder)
  77. if _color:
  78. data_filename = _metric + "_color_" + _choice + generic_output_file_svd
  79. else:
  80. data_filename = _metric + "_" + _choice + generic_output_file_svd
  81. data_file_path = os.path.join(zone_path, data_filename)
  82. # getting number of line and read randomly lines
  83. f = open(data_file_path)
  84. lines = f.readlines()
  85. counter = 0
  86. # check if user select current scene and zone to be part of training data set
  87. for line in lines:
  88. begin, end = _interval
  89. line_data = line.split(';')
  90. metrics = line_data[begin+1:end+1]
  91. metrics = [float(m) for m in metrics]
  92. min_value = min(metrics)
  93. max_value = max(metrics)
  94. if min_value < min_value_interval:
  95. min_value_interval = min_value
  96. if max_value > max_value_interval:
  97. max_value_interval = max_value
  98. counter += 1
  99. def generate_data_model(_scenes_list, _filename, _interval, _choice, _metric, _scenes = scenes_list, _nb_zones = 4, _percent = 1, _random=0, _step=40, _color=False, _norm = False):
  100. output_train_filename = _filename + ".train"
  101. output_test_filename = _filename + ".test"
  102. if not '/' in output_train_filename:
  103. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  104. # create path if not exists
  105. if not os.path.exists(output_data_folder):
  106. os.makedirs(output_data_folder)
  107. scenes = os.listdir(path)
  108. # remove min max file from scenes folder
  109. scenes = [s for s in scenes if min_max_filename not in s]
  110. train_file_data = []
  111. test_file_data = []
  112. for id_scene, folder_scene in enumerate(scenes):
  113. # only take care of maxwell scenes
  114. if folder_scene in _scenes_list:
  115. scene_path = os.path.join(path, folder_scene)
  116. zones_folder = []
  117. # create zones list
  118. for index in zones:
  119. index_str = str(index)
  120. if len(index_str) < 2:
  121. index_str = "0" + index_str
  122. zones_folder.append("zone"+index_str)
  123. # shuffle list of zones (=> randomly choose zones)
  124. if _random:
  125. random.shuffle(zones_folder)
  126. path_seuil = os.path.join(scene_path, seuil_expe_filename)
  127. for id_zone, zone_folder in enumerate(zones_folder):
  128. zone_path = os.path.join(scene_path, zone_folder)
  129. if _color:
  130. data_filename = _metric + "_color_" + _choice + generic_output_file_svd
  131. else:
  132. data_filename = _metric + "_" + _choice + generic_output_file_svd
  133. data_file_path = os.path.join(zone_path, data_filename)
  134. # getting number of line and read randomly lines
  135. f = open(data_file_path)
  136. lines = f.readlines()
  137. num_lines = len(lines)
  138. if _random:
  139. random.shuffle(lines_indexes)
  140. counter = 0
  141. # check if user select current scene and zone to be part of training data set
  142. for data in lines:
  143. percent = counter / num_lines
  144. image_index = int(data.split(';')[0])
  145. if image_index % _step == 0:
  146. line = construct_new_line(path_seuil, _interval, data, _choice, _norm, _sep, _index)
  147. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  148. train_file_data.append(line)
  149. else:
  150. test_file_data.append(line)
  151. counter += 1
  152. f.close()
  153. train_file = open(output_train_filename, 'w')
  154. test_file = open(output_test_filename, 'w')
  155. for line in train_file_data:
  156. train_file.write(line)
  157. for line in test_file_data:
  158. test_file_data.write(line)
  159. train_file.close()
  160. test_file.close()
  161. def main():
  162. p_custom = False
  163. if len(sys.argv) <= 1:
  164. print('Run with default parameters...')
  165. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --random 0 --step 40 --color 0 --custom min_max_filename')
  166. sys.exit(2)
  167. try:
  168. opts, args = getopt.getopt(sys.argv[1:], "ho:i:k:s:n:p:r:s:c:c", ["help=", "output=", "interval=", "kind=", "metric=","scenes=", "nb_zones=", "percent=", "random=", "step=", "color=", "custom="])
  169. except getopt.GetoptError:
  170. # print help information and exit:
  171. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --random 0 --step 40 --color 0 --custom min_max_filename')
  172. sys.exit(2)
  173. for o, a in opts:
  174. if o == "-h":
  175. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --random 0 --step 40 --color 0 --custom min_max_filename')
  176. sys.exit()
  177. elif o in ("-o", "--output"):
  178. p_filename = a
  179. elif o in ("-i", "--interval"):
  180. p_interval = list(map(int, a.split(',')))
  181. elif o in ("-k", "--kind"):
  182. p_kind = a
  183. elif o in ("-m", "--metric"):
  184. p_metric = a
  185. elif o in ("-s", "--scenes"):
  186. p_scenes = a.split(',')
  187. elif o in ("-n", "--nb_zones"):
  188. p_nb_zones = int(a)
  189. elif o in ("-p", "--percent"):
  190. p_percent = float(a)
  191. elif o in ("-r", "--random"):
  192. p_random = int(a)
  193. elif o in ("-p", "--percent"):
  194. p_step = int(a)
  195. elif o in ("-c", "--color"):
  196. p_color = int(a)
  197. elif o in ("-c", "--custom"):
  198. p_custom = a
  199. else:
  200. assert False, "unhandled option"
  201. # list all possibles choices of renderer
  202. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  203. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  204. # getting scenes from indexes user selection
  205. scenes_selected = []
  206. for scene_id in p_scenes:
  207. index = scenes_indices.index(scene_id.strip())
  208. scenes_selected.append(scenes_list[index])
  209. # find min max value if necessary to renormalize data
  210. if p_custom:
  211. get_min_max_value_interval(scenes_list, p_filename, p_interval, p_kind, p_color, p_metric)
  212. # write new file to save
  213. if not os.path.exists(custom_min_max_folder):
  214. os.makedirs(custom_min_max_folder)
  215. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  216. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  217. with open(min_max_filename_path, 'w') as f:
  218. f.write(str(min_value_interval) + '\n')
  219. f.write(str(max_value_interval) + '\n')
  220. # create database using img folder (generate first time only)
  221. generate_data_model(scenes_list, p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_random, p_step, p_color, p_custom)
  222. if __name__== "__main__":
  223. main()