predict_seuil_expe.py 7.6 KB

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