generate_data_model.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. scenes_list = cfg.scenes_names
  19. scenes_indexes = cfg.scenes_indices
  20. path = cfg.dataset_path
  21. zones = cfg.zones_indices
  22. seuil_expe_filename = cfg.seuil_expe_filename
  23. renderer_choices = cfg.renderer_choices
  24. normalization_choices = cfg.normalization_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. zones_indices = cfg.zones_indices
  30. generic_output_file_svd = '_random.csv'
  31. min_value_interval = sys.maxsize
  32. max_value_interval = 0
  33. def construct_new_line(path_seuil, 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. features = [float(m) for id, m in enumerate(features) if id % each == 0 ]
  39. if norm:
  40. if choice == 'svdne':
  41. features = utils.normalize_arr_with_range(features, min_value_interval, max_value_interval)
  42. if choice == 'svdn':
  43. features = utils.normalize_arr(features)
  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 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. data_filename = _feature + "_svd" + generic_output_file_svd
  74. data_file_path = os.path.join(zone_path, data_filename)
  75. # getting number of line and read randomly lines
  76. f = open(data_file_path)
  77. lines = f.readlines()
  78. # check if user select current scene and zone to be part of training data set
  79. for line in lines:
  80. begin, end = _interval
  81. line_data = line.split(';')
  82. features = line_data[begin+1:end+1]
  83. features = [float(m) for m in features]
  84. min_value = min(features)
  85. max_value = max(features)
  86. if min_value < min_value_interval:
  87. min_value_interval = min_value
  88. if max_value > max_value_interval:
  89. max_value_interval = max_value
  90. def generate_data_model(_filename, _interval, _choice, _feature, _scenes = scenes_list, _zones = zones_indices, _percent = 1, _step=1, _each=1, _norm=False, _custom=False):
  91. output_train_filename = _filename + ".train"
  92. output_test_filename = _filename + ".test"
  93. if not '/' in output_train_filename:
  94. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  95. # create path if not exists
  96. if not os.path.exists(output_data_folder):
  97. os.makedirs(output_data_folder)
  98. train_file = open(output_train_filename, 'w')
  99. test_file = open(output_test_filename, 'w')
  100. for folder_scene in scenes_list:
  101. # only take care of maxwell scenes
  102. scene_path = os.path.join(path, folder_scene)
  103. zones_indices = zones
  104. # write into file
  105. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  106. if not os.path.exists(folder_learned_path):
  107. os.makedirs(folder_learned_path)
  108. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  109. with open(file_learned_path, 'w') as f:
  110. for i in _zones:
  111. f.write(str(i) + ';')
  112. for id_zone, index_folder in enumerate(zones_indices):
  113. index_str = str(index_folder)
  114. if len(index_str) < 2:
  115. index_str = "0" + index_str
  116. current_zone_folder = "zone" + index_str
  117. zone_path = os.path.join(scene_path, current_zone_folder)
  118. # if custom normalization choices then we use svd values not already normalized
  119. if _custom:
  120. data_filename = _feature + "_svd" + generic_output_file_svd
  121. else:
  122. data_filename = _feature + "_" + _choice + generic_output_file_svd
  123. data_file_path = os.path.join(zone_path, data_filename)
  124. # getting number of line and read randomly lines
  125. f = open(data_file_path)
  126. lines = f.readlines()
  127. num_lines = len(lines)
  128. lines_indexes = np.arange(num_lines)
  129. random.shuffle(lines_indexes)
  130. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  131. counter = 0
  132. # check if user select current scene and zone to be part of training data set
  133. for index in lines_indexes:
  134. image_index = int(lines[index].split(';')[0])
  135. percent = counter / num_lines
  136. if image_index % _step == 0:
  137. line = construct_new_line(path_seuil, _interval, lines[index], _choice, _each, _norm)
  138. if id_zone in _zones and folder_scene in _scenes and percent <= _percent:
  139. train_file.write(line)
  140. else:
  141. test_file.write(line)
  142. counter += 1
  143. f.close()
  144. train_file.close()
  145. test_file.close()
  146. def main():
  147. # getting all params
  148. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  149. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  150. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  151. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  152. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)
  153. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  154. parser.add_argument('--zones', type=str, help='Zones indices to use for training data set')
  155. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)', default=1.0)
  156. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  157. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  158. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  159. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  160. args = parser.parse_args()
  161. p_filename = args.output
  162. p_interval = list(map(int, args.interval.split(',')))
  163. p_kind = args.kind
  164. p_feature = args.feature
  165. p_scenes = args.scenes.split(',')
  166. p_zones = list(map(int, args.zones.split(',')))
  167. p_percent = args.percent
  168. p_step = args.step
  169. p_each = args.each
  170. p_renderer = args.renderer
  171. p_custom = args.custom
  172. # list all possibles choices of renderer
  173. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  174. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  175. # getting scenes from indexes user selection
  176. scenes_selected = []
  177. for scene_id in p_scenes:
  178. index = scenes_indices.index(scene_id.strip())
  179. scenes_selected.append(scenes_list[index])
  180. # find min max value if necessary to renormalize data
  181. if p_custom:
  182. get_min_max_value_interval(scenes_list, p_interval, p_feature)
  183. # write new file to save
  184. if not os.path.exists(custom_min_max_folder):
  185. os.makedirs(custom_min_max_folder)
  186. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  187. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  188. with open(min_max_filename_path, 'w') as f:
  189. f.write(str(min_value_interval) + '\n')
  190. f.write(str(max_value_interval) + '\n')
  191. # create database using img folder (generate first time only)
  192. generate_data_model(p_filename, p_interval, p_kind, p_feature, scenes_selected, p_zones, p_percent, p_step, p_each, p_custom)
  193. if __name__== "__main__":
  194. main()