generate_data_model_random_maxwell.py 8.6 KB

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