predict_seuil_expe_curve_opti_scene.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. simulation_curves_zones = "simulation_curves_zones_"
  25. tmp_filename = '/tmp/__model__img_to_predict.png'
  26. current_dirpath = os.getcwd()
  27. def main():
  28. p_custom = False
  29. parser = argparse.ArgumentParser(description="Script which predicts threshold using specific model")
  30. parser.add_argument('--solution', type=str, help='Data of solution to specify filters to use')
  31. parser.add_argument('--model', type=str, help='.joblib or .json file (sklearn or keras model)')
  32. parser.add_argument('--mode', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  33. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)
  34. parser.add_argument('--scene', type=str, help='scene to use for simulation', choices=cfg.scenes_indices)
  35. #parser.add_argument('--limit_detection', type=int, help='Specify number of same prediction to stop threshold prediction', default=2)
  36. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  37. parser.add_argument('--filter', type=str, help='filter reduction solution used', choices=cfg.filter_reduction_choices)
  38. args = parser.parse_args()
  39. # keep p_interval as it is
  40. p_solution = args.solution
  41. p_model_file = args.model
  42. p_mode = args.mode
  43. p_feature = args.feature
  44. p_scene = args.scene
  45. #p_limit = args.limit
  46. p_custom = args.custom
  47. p_filter = args.filter
  48. # get scene name using index
  49. # list all possibles choices of renderer
  50. scenes_list = cfg.scenes_names
  51. scenes_indices = cfg.scenes_indices
  52. scene_index = scenes_indices.index(p_scene.strip())
  53. scene_name = scenes_list[scene_index]
  54. print(scene_name)
  55. scene_path = os.path.join(scenes_path, scene_name)
  56. threshold_expes = []
  57. threshold_expes_found = []
  58. block_predictions_str = []
  59. # get all images of folder
  60. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  61. start_quality_image = dt.get_scene_image_quality(scene_images[0])
  62. end_quality_image = dt.get_scene_image_quality(scene_images[-1])
  63. # using first two images find the step of quality used
  64. quality_step_image = dt.get_scene_image_quality(scene_images[1]) - start_quality_image
  65. # get zones list info
  66. for index in zones:
  67. index_str = str(index)
  68. if len(index_str) < 2:
  69. index_str = "0" + index_str
  70. zone_folder = "zone"+index_str
  71. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  72. with open(threshold_path_file) as f:
  73. threshold = int(f.readline())
  74. threshold_expes.append(threshold)
  75. # Initialize default data to get detected model threshold found
  76. threshold_expes_found.append(end_quality_image) # by default use max
  77. block_predictions_str.append(index_str + ";" + p_model_file + ";" + str(threshold) + ";" + str(start_quality_image) + ";" + str(quality_step_image))
  78. # for each images
  79. for img_path in scene_images:
  80. current_img = Image.open(img_path)
  81. current_quality_image = dt.get_scene_image_quality(img_path)
  82. img_blocks = segmentation.divide_in_blocks(current_img, (200, 200))
  83. for id_block, block in enumerate(img_blocks):
  84. # check only if necessary for this scene (not already detected)
  85. #if not threshold_expes_detected[id_block]:
  86. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.joblib', '_'))
  87. block.save(tmp_file_path)
  88. python_cmd_line = "python prediction/predict_noisy_image_svd_" + p_filter + ".py --image {0} --solution '{1}' --model {2} --mode {3} --feature {4}"
  89. python_cmd = python_cmd_line.format(tmp_file_path, p_solution, p_model_file, p_mode, p_feature)
  90. # specify use of custom file for min max normalization
  91. if p_custom:
  92. python_cmd = python_cmd + ' --custom ' + p_custom
  93. ## call command ##
  94. p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
  95. (output, err) = p.communicate()
  96. ## Wait for result ##
  97. p_status = p.wait()
  98. prediction = int(output)
  99. # save here in specific file of block all the predictions done
  100. block_predictions_str[id_block] = block_predictions_str[id_block] + ";" + str(prediction)
  101. print(str(id_block) + " : " + str(current_quality_image) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  102. # end of scene => display of results
  103. # construct path using model name for saving threshold map folder
  104. model_threshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  105. # create threshold model path if necessary
  106. if not os.path.exists(model_threshold_path):
  107. os.makedirs(model_threshold_path)
  108. map_filename = os.path.join(model_threshold_path, simulation_curves_zones + scene_name)
  109. f_map = open(map_filename, 'w')
  110. for line in block_predictions_str:
  111. f_map.write(line + '\n')
  112. f_map.close()
  113. print("------------------------")
  114. print("Model predictions are saved into %s" % map_filename)
  115. if __name__== "__main__":
  116. main()