predict_seuil_expe.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. from sklearn.externals import joblib
  2. import numpy as np
  3. from ipfml import processing, utils
  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. tmp_filename = '/tmp/__model__img_to_predict.png'
  17. current_dirpath = os.getcwd()
  18. def main():
  19. p_custom = False
  20. if len(sys.argv) <= 1:
  21. print('Run with default parameters...')
  22. print('python predict_seuil_expe.py --interval "0,20" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  23. sys.exit(2)
  24. try:
  25. opts, args = getopt.getopt(sys.argv[1:], "ht:m:o:l:c", ["help=", "interval=", "model=", "mode=", "metric=" "limit_detection=", "custom="])
  26. except getopt.GetoptError:
  27. # print help information and exit:
  28. print('python predict_seuil_expe.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  29. sys.exit(2)
  30. for o, a in opts:
  31. if o == "-h":
  32. print('python predict_seuil_expe.py --interval "xx,xx" --model path/to/xxxx.joblib --mode svdn --metric lab --limit_detection xx --custom min_max_filename')
  33. sys.exit()
  34. elif o in ("-t", "--interval"):
  35. p_interval = a
  36. elif o in ("-mo", "--model"):
  37. p_model_file = a
  38. elif o in ("-o", "--mode"):
  39. p_mode = a
  40. if p_mode != 'svdn' and p_mode != 'svdne' and p_mode != 'svd':
  41. assert False, "Mode not recognized"
  42. elif o in ("-me", "--metric"):
  43. p_metric = a
  44. elif o in ("-l", "--limit_detection"):
  45. p_limit = int(a)
  46. elif o in ("-c", "--custom"):
  47. p_custom = a
  48. else:
  49. assert False, "unhandled option"
  50. scenes = os.listdir(scenes_path)
  51. scenes = [s for s in scenes if not min_max_filename in s]
  52. # go ahead each scenes
  53. for id_scene, folder_scene in enumerate(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_detected = []
  65. threshold_expes_counter = []
  66. threshold_expes_found = []
  67. # get zones list info
  68. for index in zones:
  69. index_str = str(index)
  70. if len(index_str) < 2:
  71. index_str = "0" + index_str
  72. zone_folder = "zone"+index_str
  73. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  74. with open(threshold_path_file) as f:
  75. threshold = int(f.readline())
  76. threshold_expes.append(threshold)
  77. # Initialize default data to get detected model threshold found
  78. threshold_expes_detected.append(False)
  79. threshold_expes_counter.append(0)
  80. threshold_expes_found.append(int(end_index_image)) # by default use max
  81. current_counter_index = int(start_index_image)
  82. end_counter_index = int(end_index_image)
  83. print(current_counter_index)
  84. check_all_done = False
  85. while(current_counter_index <= end_counter_index and not check_all_done):
  86. current_counter_index_str = str(current_counter_index)
  87. while len(start_index_image) > len(current_counter_index_str):
  88. current_counter_index_str = "0" + current_counter_index_str
  89. img_path = os.path.join(scene_path, prefix_image_name + current_counter_index_str + ".png")
  90. current_img = Image.open(img_path)
  91. img_blocks = processing.divide_in_blocks(current_img, (200, 200))
  92. check_all_done = all(d == True for d in threshold_expes_detected)
  93. for id_block, block in enumerate(img_blocks):
  94. # check only if necessary for this scene (not already detected)
  95. if not threshold_expes_detected[id_block]:
  96. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.joblib', '_'))
  97. block.save(tmp_file_path)
  98. python_cmd = "python predict_noisy_image_svd.py --image " + tmp_file_path + \
  99. " --interval '" + p_interval + \
  100. "' --model " + p_model_file + \
  101. " --mode " + p_mode + \
  102. " --metric " + p_metric
  103. # specify use of custom file for min max normalization
  104. if p_custom:
  105. python_cmd = python_cmd + ' --custom ' + p_custom
  106. ## call command ##
  107. p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
  108. (output, err) = p.communicate()
  109. ## Wait for result ##
  110. p_status = p.wait()
  111. prediction = int(output)
  112. if prediction == 0:
  113. threshold_expes_counter[id_block] = threshold_expes_counter[id_block] + 1
  114. else:
  115. threshold_expes_counter[id_block] = 0
  116. if threshold_expes_counter[id_block] == p_limit:
  117. threshold_expes_detected[id_block] = True
  118. threshold_expes_found[id_block] = current_counter_index
  119. print(str(id_block) + " : " + str(current_counter_index) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  120. current_counter_index += step_counter
  121. print("------------------------")
  122. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  123. print("------------------------")
  124. # end of scene => display of results
  125. # construct path using model name for saving threshold map folder
  126. model_treshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  127. # create threshold model path if necessary
  128. if not os.path.exists(model_treshold_path):
  129. os.makedirs(model_treshold_path)
  130. abs_dist = []
  131. map_filename = os.path.join(model_treshold_path, threshold_map_file_prefix + folder_scene)
  132. f_map = open(map_filename, 'w')
  133. line_information = ""
  134. # default header
  135. f_map.write('| | | | |\n')
  136. f_map.write('---|----|----|---\n')
  137. for id, threshold in enumerate(threshold_expes_found):
  138. line_information += str(threshold) + " / " + str(threshold_expes[id]) + " | "
  139. abs_dist.append(abs(threshold - threshold_expes[id]))
  140. if (id + 1) % 4 == 0:
  141. f_map.write(line_information + '\n')
  142. line_information = ""
  143. f_map.write(line_information + '\n')
  144. min_abs_dist = min(abs_dist)
  145. max_abs_dist = max(abs_dist)
  146. avg_abs_dist = sum(abs_dist) / len(abs_dist)
  147. f_map.write('\nScene information : ')
  148. f_map.write('\n- BEGIN : ' + str(start_index_image))
  149. f_map.write('\n- END : ' + str(end_index_image))
  150. f_map.write('\n\nDistances information : ')
  151. f_map.write('\n- MIN : ' + str(min_abs_dist))
  152. f_map.write('\n- MAX : ' + str(max_abs_dist))
  153. f_map.write('\n- AVG : ' + str(avg_abs_dist))
  154. f_map.write('\n\nOther information : ')
  155. f_map.write('\n- Detection limit : ' + str(p_limit))
  156. # by default print last line
  157. f_map.close()
  158. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)) + " Done..")
  159. print("------------------------")
  160. time.sleep(10)
  161. if __name__== "__main__":
  162. main()