generate_data_model_random.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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_image_features
  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. def construct_new_line(path_seuil, interval, line, choice, each, norm):
  33. begin, end = interval
  34. line_data = line.split(';')
  35. seuil = line_data[0]
  36. features = line_data[begin+1:end+1]
  37. # keep only if modulo result is 0 (keep only each wanted values)
  38. features = [float(m) for id, m in enumerate(features) if id % each == 0]
  39. # TODO : check if it's always necessary to do that (loss of information for svd)
  40. if norm:
  41. if choice == 'svdne':
  42. features = utils.normalize_arr_with_range(features, min_value_interval, max_value_interval)
  43. if choice == 'svdn':
  44. features = utils.normalize_arr(features)
  45. with open(path_seuil, "r") as seuil_file:
  46. seuil_learned = int(seuil_file.readline().strip())
  47. if seuil_learned > int(seuil):
  48. line = '1'
  49. else:
  50. line = '0'
  51. for val in features:
  52. line += ';'
  53. line += str(val)
  54. line += '\n'
  55. return line
  56. def get_min_max_value_interval(_scenes_list, _interval, _feature):
  57. global min_value_interval, max_value_interval
  58. scenes = os.listdir(path)
  59. # remove min max file from scenes folder
  60. scenes = [s for s in scenes if min_max_filename not in s]
  61. for folder_scene in scenes:
  62. # only take care of maxwell scenes
  63. if folder_scene in _scenes_list:
  64. scene_path = os.path.join(path, folder_scene)
  65. zones_folder = []
  66. # create zones list
  67. for index in zones:
  68. index_str = str(index)
  69. if len(index_str) < 2:
  70. index_str = "0" + index_str
  71. zones_folder.append("zone"+index_str)
  72. for zone_folder in zones_folder:
  73. zone_path = os.path.join(scene_path, zone_folder)
  74. # if custom normalization choices then we use svd values not already normalized
  75. data_filename = _feature + "_svd"+ generic_output_file_svd
  76. data_file_path = os.path.join(zone_path, data_filename)
  77. # getting number of line and read randomly lines
  78. f = open(data_file_path)
  79. lines = f.readlines()
  80. # check if user select current scene and zone to be part of training data set
  81. for line in lines:
  82. begin, end = _interval
  83. line_data = line.split(';')
  84. features = line_data[begin+1:end+1]
  85. features = [float(m) for m in features]
  86. min_value = min(features)
  87. max_value = max(features)
  88. if min_value < min_value_interval:
  89. min_value_interval = min_value
  90. if max_value > max_value_interval:
  91. max_value_interval = max_value
  92. def generate_data_model(_scenes_list, _filename, _interval, _choice, _feature, _scenes, _nb_zones = 4, _percent = 1, _random=0, _step=1, _each=1, _custom = False):
  93. output_train_filename = _filename + ".train"
  94. output_test_filename = _filename + ".test"
  95. if not '/' in output_train_filename:
  96. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  97. # create path if not exists
  98. if not os.path.exists(output_data_folder):
  99. os.makedirs(output_data_folder)
  100. train_file_data = []
  101. test_file_data = []
  102. for folder_scene in _scenes_list:
  103. scene_path = os.path.join(path, folder_scene)
  104. zones_indices = zones
  105. # shuffle list of zones (=> randomly choose zones)
  106. # only in random mode
  107. if _random:
  108. random.shuffle(zones_indices)
  109. # store zones learned
  110. learned_zones_indices = zones_indices[:_nb_zones]
  111. # write into file
  112. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  113. if not os.path.exists(folder_learned_path):
  114. os.makedirs(folder_learned_path)
  115. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  116. with open(file_learned_path, 'w') as f:
  117. for i in learned_zones_indices:
  118. f.write(str(i) + ';')
  119. for id_zone, index_folder in enumerate(zones_indices):
  120. index_str = str(index_folder)
  121. if len(index_str) < 2:
  122. index_str = "0" + index_str
  123. current_zone_folder = "zone" + index_str
  124. zone_path = os.path.join(scene_path, current_zone_folder)
  125. # if custom normalization choices then we use svd values not already normalized
  126. if _custom:
  127. data_filename = _feature + "_svd"+ generic_output_file_svd
  128. else:
  129. data_filename = _feature + "_" + _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. # getting all params
  162. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  163. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  164. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  165. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  166. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)
  167. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  168. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set')
  169. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  170. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)')
  171. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  172. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  173. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  174. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  175. args = parser.parse_args()
  176. p_filename = args.output
  177. p_interval = list(map(int, args.interval.split(',')))
  178. p_kind = args.kind
  179. p_feature = args.feature
  180. p_scenes = args.scenes.split(',')
  181. p_nb_zones = args.nb_zones
  182. p_random = args.random
  183. p_percent = args.percent
  184. p_step = args.step
  185. p_each = args.each
  186. p_renderer = args.renderer
  187. p_custom = args.custom
  188. # list all possibles choices of renderer
  189. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  190. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  191. # getting scenes from indexes user selection
  192. scenes_selected = []
  193. for scene_id in p_scenes:
  194. index = scenes_indices.index(scene_id.strip())
  195. scenes_selected.append(scenes_list[index])
  196. # find min max value if necessary to renormalize data
  197. if p_custom:
  198. get_min_max_value_interval(scenes_list, p_interval, p_feature)
  199. # write new file to save
  200. if not os.path.exists(custom_min_max_folder):
  201. os.makedirs(custom_min_max_folder)
  202. min_max_filename_path = os.path.join(custom_min_max_folder, p_custom)
  203. with open(min_max_filename_path, 'w') as f:
  204. f.write(str(min_value_interval) + '\n')
  205. f.write(str(max_value_interval) + '\n')
  206. # create database using img folder (generate first time only)
  207. 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)
  208. if __name__== "__main__":
  209. main()