predict_seuil_expe.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # main imports
  2. import sys, os, argparse
  3. import subprocess
  4. import time
  5. import numpy as np
  6. # image processing imports
  7. from ipfml.processing import segmentation
  8. from PIL import Image
  9. # models imports
  10. from sklearn.externals import joblib
  11. # modules imports
  12. sys.path.insert(0, '') # trick to enable import of main folder module
  13. import custom_config as cfg
  14. from modules.utils import data as dt
  15. # variables and parameters
  16. scenes_path = cfg.dataset_path
  17. min_max_filename = cfg.min_max_filename_extension
  18. threshold_expe_filename = cfg.seuil_expe_filename
  19. threshold_map_folder = cfg.threshold_map_folder
  20. threshold_map_file_prefix = cfg.threshold_map_folder + "_"
  21. zones = cfg.zones_indices
  22. normalization_choices = cfg.normalization_choices
  23. features_choices = cfg.features_choices_labels
  24. tmp_filename = '/tmp/__model__img_to_predict.png'
  25. current_dirpath = os.getcwd()
  26. def main():
  27. p_custom = False
  28. parser = argparse.ArgumentParser(description="Script which predicts threshold using specific model")
  29. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  30. parser.add_argument('--model', type=str, help='.joblib or .json file (sklearn or keras model)')
  31. parser.add_argument('--mode', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  32. parser.add_argument('--feature', type=str, help='Feature data choice', choices=features_choices)
  33. parser.add_argument('--limit_detection', type=int, help='Specify number of same prediction to stop threshold prediction', default=2)
  34. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  35. args = parser.parse_args()
  36. p_interval = list(map(int, args.interval.split(',')))
  37. p_model_file = args.model
  38. p_mode = args.mode
  39. p_feature = args.feature
  40. p_limit = args.limit
  41. p_custom = args.custom
  42. scenes = os.listdir(scenes_path)
  43. scenes = [s for s in scenes if not min_max_filename in s]
  44. # go ahead each scenes
  45. for id_scene, folder_scene in enumerate(scenes):
  46. print(folder_scene)
  47. scene_path = os.path.join(scenes_path, folder_scene)
  48. threshold_expes = []
  49. threshold_expes_detected = []
  50. threshold_expes_counter = []
  51. threshold_expes_found = []
  52. # get all images of folder
  53. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  54. start_quality_image = dt.get_scene_image_quality(scene_images[0])
  55. end_quality_image = dt.get_scene_image_quality(scene_images[-1])
  56. # get zones list info
  57. for index in zones:
  58. index_str = str(index)
  59. if len(index_str) < 2:
  60. index_str = "0" + index_str
  61. zone_folder = "zone"+index_str
  62. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  63. with open(threshold_path_file) as f:
  64. threshold = int(f.readline())
  65. threshold_expes.append(threshold)
  66. # Initialize default data to get detected model threshold found
  67. threshold_expes_detected.append(False)
  68. threshold_expes_counter.append(0)
  69. threshold_expes_found.append(end_quality_image) # by default use max
  70. check_all_done = False
  71. # for each images
  72. for img_path in scene_images:
  73. current_img = Image.open(img_path)
  74. current_quality_image = dt.get_scene_image_quality(img_path)
  75. current_image_potfix = dt.get_scene_image_postfix(img_path)
  76. img_blocks = segmentation.divide_in_blocks(current_img, (200, 200))
  77. current_img = Image.open(img_path)
  78. img_blocks = segmentation.divide_in_blocks(current_img, (200, 200))
  79. check_all_done = all(d == True for d in threshold_expes_detected)
  80. if check_all_done:
  81. break
  82. for id_block, block in enumerate(img_blocks):
  83. # check only if necessary for this scene (not already detected)
  84. if not threshold_expes_detected[id_block]:
  85. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.joblib', '_'))
  86. block.save(tmp_file_path)
  87. python_cmd = "python prediction/predict_noisy_image_svd.py --image " + tmp_file_path + \
  88. " --interval '" + p_interval + \
  89. "' --model " + p_model_file + \
  90. " --mode " + p_mode + \
  91. " --feature " + p_feature
  92. # specify use of custom file for min max normalization
  93. if p_custom:
  94. python_cmd = python_cmd + ' --custom ' + p_custom
  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_quality_image
  108. print(str(id_block) + " : " + current_image_potfix + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  109. print("------------------------")
  110. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  111. print("------------------------")
  112. # end of scene => display of results
  113. # construct path using model name for saving threshold map folder
  114. model_treshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  115. # create threshold model path if necessary
  116. if not os.path.exists(model_treshold_path):
  117. os.makedirs(model_treshold_path)
  118. abs_dist = []
  119. map_filename = os.path.join(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_quality_image))
  137. f_map.write('\n- END : ' + str(end_quality_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. if __name__== "__main__":
  149. main()