generate_data_model_random_maxwell.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 image_processing, metrics
  15. from modules.utils import config as cfg
  16. # getting configuration information
  17. config_filename = cfg.config_filename
  18. zone_folder = cfg.zone_folder
  19. min_max_filename = cfg.min_max_filename_extension
  20. # define all scenes values
  21. scenes_list = cfg.maxwell_scenes_names
  22. scenes_indexes = cfg.maxwell_scenes_indices
  23. choices = cfg.normalization_choices
  24. path = cfg.dataset_path
  25. zones = cfg.zones_indices
  26. seuil_expe_filename = cfg.seuil_expe_filename
  27. metric_choices = cfg.metric_choices_labels
  28. output_data_folder = cfg.output_data_folder
  29. min_value_interval = sys.maxsize
  30. max_value_interval = 0
  31. def construct_new_line(path_seuil, interval, line, norm, sep, index):
  32. begin, end = interval
  33. line_data = line.split(';')
  34. seuil = line_data[0]
  35. metrics = line_data[begin+1:end+1]
  36. metrics = [float(m) for m in metrics]
  37. if norm:
  38. metrics = image_processing.normalize_arr_with_range(metrics, min_value_interval, max_value_interval)
  39. with open(path_seuil, "r") as seuil_file:
  40. seuil_learned = int(seuil_file.readline().strip())
  41. if seuil_learned > int(seuil):
  42. line = '1'
  43. else:
  44. line = '0'
  45. for idx, val in enumerate(metrics):
  46. if index:
  47. line += " " + str(idx + 1)
  48. line += sep
  49. line += str(val)
  50. line += '\n'
  51. return line
  52. def get_min_max_value_interval(_filename, _interval, _choice, _metric, _scenes = scenes_list, _nb_zones = 4, _percent = 1):
  53. global min_value_interval, max_value_interval
  54. scenes = os.listdir(path)
  55. # remove min max file from scenes folder
  56. scenes = [s for s in scenes if min_max_filename not in s]
  57. for id_scene, folder_scene in enumerate(scenes):
  58. # only take care of maxwell scenes
  59. if folder_scene in scenes_list:
  60. scene_path = os.path.join(path, folder_scene)
  61. zones_folder = []
  62. # create zones list
  63. for index in zones:
  64. index_str = str(index)
  65. if len(index_str) < 2:
  66. index_str = "0" + index_str
  67. zones_folder.append("zone"+index_str)
  68. # shuffle list of zones (=> randomly choose zones)
  69. random.shuffle(zones_folder)
  70. for id_zone, zone_folder in enumerate(zones_folder):
  71. zone_path = os.path.join(scene_path, zone_folder)
  72. data_filename = _metric + "_" + _choice + generic_output_file_svd
  73. data_file_path = os.path.join(zone_path, data_filename)
  74. # getting number of line and read randomly lines
  75. f = open(data_file_path)
  76. lines = f.readlines()
  77. counter = 0
  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. metrics = line_data[begin+1:end+1]
  83. metrics = [float(m) for m in metrics]
  84. min_value = min(metrics)
  85. max_value = max(metrics)
  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. counter += 1
  91. def generate_data_model(_filename, _interval, _choice, _metric, _scenes = scenes_list, _nb_zones = 4, _percent = 1, _norm = False, _sep=':', _index=True):
  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 = open(output_train_filename, 'w')
  100. test_file = open(output_test_filename, 'w')
  101. scenes = os.listdir(path)
  102. # remove min max file from scenes folder
  103. scenes = [s for s in scenes if min_max_filename not in s]
  104. for id_scene, folder_scene in enumerate(scenes):
  105. # only take care of maxwell scenes
  106. if folder_scene in scenes_list:
  107. scene_path = os.path.join(path, folder_scene)
  108. zones_folder = []
  109. # create zones list
  110. for index in zones:
  111. index_str = str(index)
  112. if len(index_str) < 2:
  113. index_str = "0" + index_str
  114. zones_folder.append("zone"+index_str)
  115. # shuffle list of zones (=> randomly choose zones)
  116. random.shuffle(zones_folder)
  117. for id_zone, zone_folder in enumerate(zones_folder):
  118. zone_path = os.path.join(scene_path, zone_folder)
  119. data_filename = _metric + "_" + _choice + generic_output_file_svd
  120. data_file_path = os.path.join(zone_path, data_filename)
  121. # getting number of line and read randomly lines
  122. f = open(data_file_path)
  123. lines = f.readlines()
  124. num_lines = len(lines)
  125. lines_indexes = np.arange(num_lines)
  126. random.shuffle(lines_indexes)
  127. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  128. counter = 0
  129. # check if user select current scene and zone to be part of training data set
  130. for index in lines_indexes:
  131. line = construct_new_line(path_seuil, _interval, lines[index], _norm, _sep, _index)
  132. percent = counter / num_lines
  133. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  134. train_file.write(line)
  135. else:
  136. test_file.write(line)
  137. counter += 1
  138. f.close()
  139. train_file.close()
  140. test_file.close()
  141. def main():
  142. if len(sys.argv) <= 1:
  143. print('Run with default parameters...')
  144. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --norm 1 --sep : --rowindex 1')
  145. sys.exit(2)
  146. try:
  147. opts, args = getopt.getopt(sys.argv[1:], "ho:i:k:s:n:p:r", ["help=", "output=", "interval=", "kind=", "metric=","scenes=", "nb_zones=", "percent=", "norm=", "sep=", "rowindex="])
  148. except getopt.GetoptError:
  149. # print help information and exit:
  150. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --norm 1 --sep : --rowindex 1')
  151. sys.exit(2)
  152. for o, a in opts:
  153. if o == "-h":
  154. print('python generate_data_model_random.py --output xxxx --interval 0,20 --kind svdne --metric lab --scenes "A, B, D" --nb_zones 5 --percent 0.7 --norm 1 --sep : --rowindex 1')
  155. sys.exit()
  156. elif o in ("-o", "--output"):
  157. p_filename = a
  158. elif o in ("-i", "--interval"):
  159. p_interval = list(map(int, a.split(',')))
  160. elif o in ("-k", "--kind"):
  161. p_kind = a
  162. elif o in ("-m", "--metric"):
  163. p_metric = a
  164. elif o in ("-s", "--scenes"):
  165. p_scenes = a.split(',')
  166. elif o in ("-n", "--nb_zones"):
  167. p_nb_zones = int(a)
  168. elif o in ("-n", "--norm"):
  169. if int(a) == 1:
  170. p_norm = True
  171. else:
  172. p_norm = False
  173. elif o in ("-p", "--percent"):
  174. p_percent = float(a)
  175. elif o in ("-s", "--sep"):
  176. p_sep = a
  177. elif o in ("-r", "--rowindex"):
  178. if int(a) == 1:
  179. p_rowindex = True
  180. else:
  181. p_rowindex = False
  182. else:
  183. assert False, "unhandled option"
  184. # getting scenes from indexes user selection
  185. scenes_selected = []
  186. for scene_id in p_scenes:
  187. index = scenes_indexes.index(scene_id.strip())
  188. scenes_selected.append(scenes_list[index])
  189. # find min max value if necessary to renormalize data
  190. if p_norm:
  191. get_min_max_value_interval(p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent)
  192. # create database using img folder (generate first time only)
  193. generate_data_model(p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_norm, p_sep, p_rowindex)
  194. if __name__== "__main__":
  195. main()