predict_seuil_expe_maxwell_curve.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from sklearn.externals import joblib
  2. import numpy as np
  3. from ipfml import processing
  4. from PIL import Image
  5. import sys, os, getopt
  6. import subprocess
  7. import time
  8. from modules.utils import config as cfg
  9. config_filename = cfg.config_filename
  10. scenes_path = cfg.dataset_path
  11. min_max_filename = cfg.min_max_filename_extension
  12. threshold_expe_filename = cfg.seuil_expe_filename
  13. threshold_map_folder = cfg.threshold_map_folder
  14. threshold_map_file_prefix = cfg.threshold_map_folder + "_"
  15. zones = cfg.zones_indices
  16. maxwell_scenes = cfg.maxwell_scenes_names
  17. simulation_curves_zones = "simulation_curves_zones_"
  18. tmp_filename = '/tmp/__model__img_to_predict.png'
  19. current_dirpath = os.getcwd()
  20. def main():
  21. p_custom = False
  22. if len(sys.argv) <= 1:
  23. print('Run with default parameters...')
  24. print('python predict_seuil_expe_maxwell_curve.py --interval "0,20" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  25. sys.exit(2)
  26. try:
  27. opts, args = getopt.getopt(sys.argv[1:], "ht:m:o:l:c", ["help=", "interval=", "model=", "mode=", "metric=", "limit_detection=", "custom="])
  28. except getopt.GetoptError:
  29. # print help information and exit:
  30. print('python predict_seuil_expe_maxwell_curve.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  31. sys.exit(2)
  32. for o, a in opts:
  33. if o == "-h":
  34. print('python predict_seuil_expe_maxwell_curve.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  35. sys.exit()
  36. elif o in ("-t", "--interval"):
  37. p_interval = a
  38. elif o in ("-m", "--model"):
  39. p_model_file = a
  40. elif o in ("-o", "--mode"):
  41. p_mode = a
  42. if p_mode != 'svdn' and p_mode != 'svdne' and p_mode != 'svd':
  43. assert False, "Mode not recognized"
  44. elif o in ("-m", "--metric"):
  45. p_metric = a
  46. elif o in ("-l", "--limit_detection"):
  47. p_limit = int(a)
  48. elif o in ("-c", "--custom"):
  49. p_custom = a
  50. else:
  51. assert False, "unhandled option"
  52. scenes = os.listdir(scenes_path)
  53. scenes = [s for s in scenes if s in maxwell_scenes]
  54. print(scenes)
  55. # go ahead each scenes
  56. for id_scene, folder_scene in enumerate(scenes):
  57. # only take in consideration maxwell scenes
  58. if folder_scene in maxwell_scenes:
  59. print(folder_scene)
  60. scene_path = os.path.join(scenes_path, folder_scene)
  61. config_path = os.path.join(scene_path, config_filename)
  62. with open(config_path, "r") as config_file:
  63. last_image_name = config_file.readline().strip()
  64. prefix_image_name = config_file.readline().strip()
  65. start_index_image = config_file.readline().strip()
  66. end_index_image = config_file.readline().strip()
  67. step_counter = int(config_file.readline().strip())
  68. threshold_expes = []
  69. threshold_expes_found = []
  70. block_predictions_str = []
  71. # get zones list info
  72. for index in zones:
  73. index_str = str(index)
  74. if len(index_str) < 2:
  75. index_str = "0" + index_str
  76. zone_folder = "zone"+index_str
  77. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  78. with open(threshold_path_file) as f:
  79. threshold = int(f.readline())
  80. threshold_expes.append(threshold)
  81. # Initialize default data to get detected model threshold found
  82. threshold_expes_found.append(int(end_index_image)) # by default use max
  83. block_predictions_str.append(index_str + ";" + p_model_file + ";" + str(threshold) + ";" + str(start_index_image) + ";" + str(step_counter))
  84. current_counter_index = int(start_index_image)
  85. end_counter_index = int(end_index_image)
  86. print(current_counter_index)
  87. while(current_counter_index <= end_counter_index):
  88. current_counter_index_str = str(current_counter_index)
  89. while len(start_index_image) > len(current_counter_index_str):
  90. current_counter_index_str = "0" + current_counter_index_str
  91. img_path = os.path.join(scene_path, prefix_image_name + current_counter_index_str + ".png")
  92. current_img = Image.open(img_path)
  93. img_blocks = processing.divide_in_blocks(current_img, (200, 200))
  94. for id_block, block in enumerate(img_blocks):
  95. # check only if necessary for this scene (not already detected)
  96. #if not threshold_expes_detected[id_block]:
  97. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.joblib', '_'))
  98. block.save(tmp_file_path)
  99. python_cmd = "python predict_noisy_image_svd.py --image " + tmp_file_path + \
  100. " --interval '" + p_interval + \
  101. "' --model " + p_model_file + \
  102. " --mode " + p_mode + \
  103. " --metric " + p_metric
  104. # specify use of custom file for min max normalization
  105. if p_custom:
  106. python_cmd = python_cmd + ' --custom ' + p_custom
  107. ## call command ##
  108. p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
  109. (output, err) = p.communicate()
  110. ## Wait for result ##
  111. p_status = p.wait()
  112. prediction = int(output)
  113. # save here in specific file of block all the predictions done
  114. block_predictions_str[id_block] = block_predictions_str[id_block] + ";" + str(prediction)
  115. print(str(id_block) + " : " + str(current_counter_index) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  116. current_counter_index += step_counter
  117. print("------------------------")
  118. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  119. print("------------------------")
  120. # end of scene => display of results
  121. # construct path using model name for saving threshold map folder
  122. model_threshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  123. # create threshold model path if necessary
  124. if not os.path.exists(model_threshold_path):
  125. os.makedirs(model_threshold_path)
  126. map_filename = os.path.join(model_threshold_path, simulation_curves_zones + folder_scene)
  127. f_map = open(map_filename, 'w')
  128. for line in block_predictions_str:
  129. f_map.write(line + '\n')
  130. f_map.close()
  131. print("Scene " + str(id_scene + 1) + "/" + str(len(maxwell_scenes)) + " Done..")
  132. print("------------------------")
  133. print("Model predictions are saved into %s" % map_filename)
  134. time.sleep(10)
  135. if __name__== "__main__":
  136. main()