generate_data_model_random.py 11 KB

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