generate_data_model_random_center.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # main imports
  2. import sys, os, argparse
  3. import numpy as np
  4. import pandas as pd
  5. import random
  6. # image processing imports
  7. from PIL import Image
  8. from ipfml import utils
  9. # modules imports
  10. sys.path.insert(0, '') # trick to enable import of main folder module
  11. import custom_config as cfg
  12. from modules.utils import data as dt
  13. from data_attributes import get_svd_data
  14. # getting configuration information
  15. learned_folder = cfg.learned_zones_folder
  16. min_max_filename = cfg.min_max_filename_extension
  17. # define all scenes variables
  18. all_scenes_list = cfg.scenes_names
  19. all_scenes_indices = cfg.scenes_indices
  20. normalization_choices = cfg.normalization_choices
  21. path = cfg.dataset_path
  22. zones = cfg.zones_indices
  23. seuil_expe_filename = cfg.seuil_expe_filename
  24. renderer_choices = cfg.renderer_choices
  25. features_choices = cfg.features_choices_labels
  26. output_data_folder = cfg.output_data_folder
  27. custom_min_max_folder = cfg.min_max_custom_folder
  28. min_max_ext = cfg.min_max_filename_extension
  29. generic_output_file_svd = '_random.csv'
  30. min_value_interval = sys.maxsize
  31. max_value_interval = 0
  32. abs_gap_data = 150
  33. def construct_new_line(seuil_learned, interval, line, choice, each, norm):
  34. begin, end = interval
  35. line_data = line.split(';')
  36. seuil = line_data[0]
  37. features = line_data[begin+1:end+1]
  38. # keep only if modulo result is 0 (keep only each wanted values)
  39. features = [float(m) for id, m in enumerate(features) if id % each == 0]
  40. # TODO : check if it's always necessary to do that (loss of information for svd)
  41. if norm:
  42. if choice == 'svdne':
  43. features = utils.normalize_arr_with_range(features, min_value_interval, max_value_interval)
  44. if choice == 'svdn':
  45. features = utils.normalize_arr(features)
  46. if seuil_learned > int(seuil):
  47. line = '1'
  48. else:
  49. line = '0'
  50. for val in features:
  51. line += ';'
  52. line += str(val)
  53. line += '\n'
  54. return line
  55. def get_min_max_value_interval(_scenes_list, _interval, _feature):
  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. for folder_scene in scenes:
  61. # only take care of maxwell scenes
  62. if folder_scene in _scenes_list:
  63. scene_path = os.path.join(path, folder_scene)
  64. zones_folder = []
  65. # create zones list
  66. for index in zones:
  67. index_str = str(index)
  68. if len(index_str) < 2:
  69. index_str = "0" + index_str
  70. zones_folder.append("zone"+index_str)
  71. for zone_folder in zones_folder:
  72. zone_path = os.path.join(scene_path, zone_folder)
  73. # if custom normalization choices then we use svd values not already normalized
  74. data_filename = _feature + "_svd"+ generic_output_file_svd
  75. data_file_path = os.path.join(zone_path, data_filename)
  76. # getting number of line and read randomly lines
  77. f = open(data_file_path)
  78. lines = f.readlines()
  79. # check if user select current scene and zone to be part of training data set
  80. for line in lines:
  81. begin, end = _interval
  82. line_data = line.split(';')
  83. features = line_data[begin+1:end+1]
  84. features = [float(m) for m in features]
  85. min_value = min(features)
  86. max_value = max(features)
  87. if min_value < min_value_interval:
  88. min_value_interval = min_value
  89. if max_value > max_value_interval:
  90. max_value_interval = max_value
  91. def generate_data_model(_scenes_list, _filename, _interval, _choice, _feature, _scenes, _nb_zones = 4, _percent = 1, _random=0, _step=1, _each=1, _custom = False):
  92. output_train_filename = _filename + ".train"
  93. output_test_filename = _filename + ".test"
  94. if not '/' in output_train_filename:
  95. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  96. # create path if not exists
  97. if not os.path.exists(output_data_folder):
  98. os.makedirs(output_data_folder)
  99. train_file_data = []
  100. test_file_data = []
  101. for folder_scene in _scenes_list:
  102. scene_path = os.path.join(path, folder_scene)
  103. zones_indices = zones
  104. # shuffle list of zones (=> randomly choose zones)
  105. # only in random mode
  106. if _random:
  107. random.shuffle(zones_indices)
  108. # store zones learned
  109. learned_zones_indices = zones_indices[:_nb_zones]
  110. # write into file
  111. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  112. if not os.path.exists(folder_learned_path):
  113. os.makedirs(folder_learned_path)
  114. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  115. with open(file_learned_path, 'w') as f:
  116. for i in learned_zones_indices:
  117. f.write(str(i) + ';')
  118. for id_zone, index_folder in enumerate(zones_indices):
  119. index_str = str(index_folder)
  120. if len(index_str) < 2:
  121. index_str = "0" + index_str
  122. current_zone_folder = "zone" + index_str
  123. zone_path = os.path.join(scene_path, current_zone_folder)
  124. # if custom normalization choices then we use svd values not already normalized
  125. if _custom:
  126. data_filename = _feature + "_svd"+ generic_output_file_svd
  127. else:
  128. data_filename = _feature + "_" + _choice + generic_output_file_svd
  129. data_file_path = os.path.join(zone_path, data_filename)
  130. # getting number of line and read randomly lines
  131. f = open(data_file_path)
  132. lines = f.readlines()
  133. num_lines = len(lines)
  134. # randomly shuffle image
  135. if _random:
  136. random.shuffle(lines)
  137. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  138. with open(path_seuil, "r") as seuil_file:
  139. seuil_learned = int(seuil_file.readline().strip())
  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. with open(path_seuil, "r") as seuil_file:
  147. seuil_learned = int(seuil_file.readline().strip())
  148. gap_threshold = abs(seuil_learned - image_index)
  149. # only keep data near to threshold of zone image
  150. if gap_threshold <= abs_gap_data:
  151. line = construct_new_line(seuil_learned, _interval, data, _choice, _each, _custom)
  152. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  153. train_file_data.append(line)
  154. else:
  155. test_file_data.append(line)
  156. counter += 1
  157. f.close()
  158. train_file = open(output_train_filename, 'w')
  159. test_file = open(output_test_filename, 'w')
  160. for line in train_file_data:
  161. train_file.write(line)
  162. for line in test_file_data:
  163. test_file.write(line)
  164. train_file.close()
  165. test_file.close()
  166. def main():
  167. # getting all params
  168. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  169. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  170. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  171. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  172. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)
  173. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  174. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set')
  175. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  176. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)')
  177. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  178. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  179. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  180. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  181. args = parser.parse_args()
  182. p_filename = args.output
  183. p_interval = list(map(int, args.interval.split(',')))
  184. p_kind = args.kind
  185. p_feature = args.feature
  186. p_scenes = args.scenes.split(',')
  187. p_nb_zones = args.nb_zones
  188. p_random = args.random
  189. p_percent = args.percent
  190. p_step = args.step
  191. p_each = args.each
  192. p_renderer = args.renderer
  193. p_custom = args.custom
  194. # list all possibles choices of renderer
  195. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  196. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  197. # getting scenes from indexes user selection
  198. scenes_selected = []
  199. for scene_id in p_scenes:
  200. index = scenes_indices.index(scene_id.strip())
  201. scenes_selected.append(scenes_list[index])
  202. # find min max value if necessary to renormalize data
  203. if p_custom:
  204. get_min_max_value_interval(scenes_list, p_interval, p_feature)
  205. # write new file to save
  206. if not os.path.exists(custom_min_max_folder):
  207. os.makedirs(custom_min_max_folder)
  208. min_max_filename_path = os.path.join(custom_min_max_folder, p_custom)
  209. with open(min_max_filename_path, 'w') as f:
  210. f.write(str(min_value_interval) + '\n')
  211. f.write(str(max_value_interval) + '\n')
  212. # create database using img folder (generate first time only)
  213. generate_data_model(scenes_list, p_filename, p_interval, p_kind, p_feature, scenes_selected, p_nb_zones, p_percent, p_random, p_step, p_each, p_custom)
  214. if __name__== "__main__":
  215. main()