generate_data_model_file.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. zones = cfg.zones_indices
  19. seuil_expe_filename = cfg.seuil_expe_filename
  20. normalization_choices = cfg.normalization_choices
  21. features_choices = cfg.features_choices_labels
  22. output_data_folder = cfg.output_datasets
  23. custom_min_max_folder = cfg.min_max_custom_folder
  24. min_max_ext = cfg.min_max_filename_extension
  25. zones_indices = cfg.zones_indices
  26. generic_output_file_svd = '_random.csv'
  27. min_value_interval = sys.maxsize
  28. max_value_interval = 0
  29. def construct_new_line(threshold, interval, line, choice, each, norm):
  30. begin, end = interval
  31. line_data = line.split(';')
  32. seuil = line_data[0]
  33. features = line_data[begin+1:end+1]
  34. features = [float(m) for id, m in enumerate(features) if id % each == 0 ]
  35. if norm:
  36. if choice == 'svdne':
  37. features = utils.normalize_arr_with_range(features, min_value_interval, max_value_interval)
  38. if choice == 'svdn':
  39. features = utils.normalize_arr(features)
  40. if threshold > int(seuil):
  41. line = '1'
  42. else:
  43. line = '0'
  44. for val in features:
  45. line += ';'
  46. line += str(val)
  47. line += '\n'
  48. return line
  49. def get_min_max_value_interval(path, _scenes_list, _interval, _feature):
  50. global min_value_interval, max_value_interval
  51. scenes = os.listdir(path)
  52. # remove min max file from scenes folder
  53. scenes = [s for s in scenes if min_max_filename not in s]
  54. for folder_scene in scenes:
  55. # only take care of maxwell scenes
  56. if folder_scene in _scenes_list:
  57. scene_path = os.path.join(path, folder_scene)
  58. zones_folder = []
  59. # create zones list
  60. for index in zones:
  61. index_str = str(index)
  62. if len(index_str) < 2:
  63. index_str = "0" + index_str
  64. zones_folder.append("zone"+index_str)
  65. for zone_folder in zones_folder:
  66. zone_path = os.path.join(scene_path, zone_folder)
  67. data_filename = _feature + "_svd" + generic_output_file_svd
  68. data_file_path = os.path.join(zone_path, data_filename)
  69. # getting number of line and read randomly lines
  70. f = open(data_file_path)
  71. lines = f.readlines()
  72. # check if user select current scene and zone to be part of training data set
  73. for line in lines:
  74. begin, end = _interval
  75. line_data = line.split(';')
  76. features = line_data[begin+1:end+1]
  77. features = [float(m) for m in features]
  78. min_value = min(features)
  79. max_value = max(features)
  80. if min_value < min_value_interval:
  81. min_value_interval = min_value
  82. if max_value > max_value_interval:
  83. max_value_interval = max_value
  84. def generate_data_model(_filename, _data_path, _interval, _choice, _feature, _thresholds, _learned_zones, _step=1, _each=1, _norm=False, _custom=False):
  85. output_train_filename = os.path.join(output_data_folder, _filename + ".train")
  86. output_test_filename = os.path.join(output_data_folder,_filename + ".test")
  87. # create path if not exists
  88. if not os.path.exists(output_data_folder):
  89. os.makedirs(output_data_folder)
  90. train_file = open(output_train_filename, 'w')
  91. test_file = open(output_test_filename, 'w')
  92. # get zone indices
  93. zones_indices = np.arange(16)
  94. for folder_scene in _learned_zones:
  95. # get train zones
  96. train_zones = _learned_zones[folder_scene]
  97. scene_thresholds = _thresholds[folder_scene]
  98. scene_path = os.path.join(_data_path, folder_scene)
  99. for id_zone, index_folder in enumerate(zones_indices):
  100. index_str = str(index_folder)
  101. if len(index_str) < 2:
  102. index_str = "0" + index_str
  103. current_zone_folder = "zone" + index_str
  104. zone_path = os.path.join(scene_path, current_zone_folder)
  105. # if custom normalization choices then we use svd values not already normalized
  106. if _custom:
  107. data_filename = _feature + "_svd" + generic_output_file_svd
  108. else:
  109. data_filename = _feature + "_" + _choice + generic_output_file_svd
  110. data_file_path = os.path.join(zone_path, data_filename)
  111. # getting number of line and read randomly lines
  112. f = open(data_file_path)
  113. lines = f.readlines()
  114. num_lines = len(lines)
  115. lines_indexes = np.arange(num_lines)
  116. random.shuffle(lines_indexes)
  117. counter = 0
  118. # check if user select current scene and zone to be part of training data set
  119. for index in lines_indexes:
  120. image_index = int(lines[index].split(';')[0])
  121. if image_index % _step == 0:
  122. line = construct_new_line(scene_thresholds[id_zone], _interval, lines[index], _choice, _each, _norm)
  123. if id_zone in train_zones:
  124. train_file.write(line)
  125. else:
  126. test_file.write(line)
  127. counter += 1
  128. f.close()
  129. train_file.close()
  130. test_file.close()
  131. def main():
  132. # getting all params
  133. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  134. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)', required=True)
  135. parser.add_argument('--data', type=str, help='folder which contains data of dataset', required=True)
  136. parser.add_argument('--thresholds', type=str, help='file with scene list information and thresholds', required=True)
  137. parser.add_argument('--selected_zones', type=str, help='file which contains all selected zones of scene', required=True)
  138. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"', required=True)
  139. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  140. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices, required=True)
  141. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  142. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  143. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  144. args = parser.parse_args()
  145. p_filename = args.output
  146. p_data = args.data
  147. p_thresholds = args.thresholds
  148. p_selected_zones = args.selected_zones
  149. p_interval = list(map(int, args.interval.split(',')))
  150. p_kind = args.kind
  151. p_feature = args.feature
  152. p_step = args.step
  153. p_each = args.each
  154. p_custom = args.custom
  155. # 1. retrieve human_thresholds
  156. human_thresholds = {}
  157. # extract thresholds
  158. with open(p_thresholds) as f:
  159. thresholds_line = f.readlines()
  160. for line in thresholds_line:
  161. data = line.split(';')
  162. del data[-1] # remove unused last element `\n`
  163. current_scene = data[0]
  164. thresholds_scene = data[1:]
  165. # TODO : check if really necessary
  166. if current_scene != '50_shades_of_grey':
  167. human_thresholds[current_scene] = [ int(threshold) for threshold in thresholds_scene ]
  168. # 2. get selected zones
  169. selected_zones = {}
  170. with(open(p_selected_zones, 'r')) as f:
  171. for line in f.readlines():
  172. data = line.split(';')
  173. del data[-1]
  174. scene_name = data[0]
  175. thresholds = data[1:]
  176. selected_zones[scene_name] = [ int(t) for t in thresholds ]
  177. # find min max value if necessary to renormalize data
  178. if p_custom:
  179. get_min_max_value_interval(p_data, selected_zones, p_interval, p_feature)
  180. # write new file to save
  181. if not os.path.exists(custom_min_max_folder):
  182. os.makedirs(custom_min_max_folder)
  183. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  184. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  185. with open(min_max_filename_path, 'w') as f:
  186. f.write(str(min_value_interval) + '\n')
  187. f.write(str(max_value_interval) + '\n')
  188. # create database using img folder (generate first time only)
  189. generate_data_model(p_filename, p_data, p_interval, p_kind, p_feature, human_thresholds, selected_zones, p_step, p_each, p_custom)
  190. if __name__== "__main__":
  191. main()