predict_seuil_expe_maxwell_curve.py 6.9 KB

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