predict_seuil_expe_curve.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # main imports
  2. import sys, os, argparse
  3. import subprocess
  4. import numpy as np
  5. # image processing imports
  6. from ipfml.processing.segmentation import divide_in_blocks
  7. from PIL import Image
  8. # model imports
  9. from sklearn.externals import joblib
  10. # modules imports
  11. sys.path.insert(0, '') # trick to enable import of main folder module
  12. import custom_config as cfg
  13. from modules.utils import data as dt
  14. # parameters from config and others
  15. scenes_path = cfg.dataset_path
  16. min_max_filename = cfg.min_max_filename_extension
  17. threshold_expe_filename = cfg.seuil_expe_filename
  18. threshold_map_folder = cfg.threshold_map_folder
  19. threshold_map_file_prefix = cfg.threshold_map_folder + "_"
  20. zones = cfg.zones_indices
  21. maxwell_scenes = cfg.maxwell_scenes_names
  22. features_choices = cfg.features_choices_labels
  23. simulation_curves_zones = "simulation_curves_zones_"
  24. tmp_filename = '/tmp/__model__img_to_predict.png'
  25. current_dirpath = os.getcwd()
  26. def main():
  27. parser = argparse.ArgumentParser(description="Script which predicts threshold using specific keras model")
  28. parser.add_argument('--features', type=str,
  29. help="list of features choice in order to compute data",
  30. default='svd_reconstruction, ipca_reconstruction',
  31. required=True)
  32. parser.add_argument('--params', type=str,
  33. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  34. default='100, 200 :: 50, 25',
  35. required=True)
  36. parser.add_argument('--model', type=str, help='.json file of keras model', required=True)
  37. parser.add_argument('--size', type=str, help="Expected output size before processing transformation", default="100,100")
  38. parser.add_argument('--renderer', type=str,
  39. help='Renderer choice in order to limit scenes used',
  40. choices=cfg.renderer_choices,
  41. default='all',
  42. required=True)
  43. args = parser.parse_args()
  44. p_features = list(map(str.strip, args.features.split(',')))
  45. p_params = list(map(str.strip, args.params.split('::')))
  46. p_model_file = args.model
  47. p_size = args.size
  48. p_renderer = args.renderer
  49. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  50. scenes = os.listdir(scenes_path)
  51. print(scenes)
  52. # go ahead each scenes
  53. for id_scene, folder_scene in enumerate(scenes):
  54. # only take in consideration renderer scenes
  55. if folder_scene in scenes_list:
  56. print(folder_scene)
  57. scene_path = os.path.join(scenes_path, folder_scene)
  58. # get all images of folder
  59. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  60. number_scene_image = len(scene_images)
  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. threshold_expes = []
  66. threshold_expes_found = []
  67. block_predictions_str = []
  68. # get zones list info
  69. for index in zones:
  70. index_str = str(index)
  71. if len(index_str) < 2:
  72. index_str = "0" + index_str
  73. zone_folder = "zone"+index_str
  74. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  75. with open(threshold_path_file) as f:
  76. threshold = int(f.readline())
  77. threshold_expes.append(threshold)
  78. # Initialize default data to get detected model threshold found
  79. threshold_expes_found.append(int(end_quality_image)) # by default use max
  80. block_predictions_str.append(index_str + ";" + p_model_file + ";" + str(threshold) + ";" + str(start_quality_image) + ";" + str(quality_step_image))
  81. # for each images
  82. for img_path in scene_images:
  83. current_img = Image.open(img_path)
  84. img_blocks = divide_in_blocks(current_img, cfg.sub_image_size)
  85. current_quality_image = dt.get_scene_image_quality(img_path)
  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('.json', '_'))
  90. block.save(tmp_file_path)
  91. python_cmd = "python predict_noisy_image.py --image " + tmp_file_path + \
  92. " --features " + p_features + \
  93. " --params " + p_params + \
  94. " --model " + p_model_file + \
  95. " --size " + p_size
  96. ## call command ##
  97. p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
  98. (output, err) = p.communicate()
  99. ## Wait for result ##
  100. p_status = p.wait()
  101. prediction = int(output)
  102. # save here in specific file of block all the predictions done
  103. block_predictions_str[id_block] = block_predictions_str[id_block] + ";" + str(prediction)
  104. print(str(id_block) + " : " + str(current_quality_image) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  105. print("------------------------")
  106. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  107. print("------------------------")
  108. # end of scene => display of results
  109. # construct path using model name for saving threshold map folder
  110. model_threshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  111. # create threshold model path if necessary
  112. if not os.path.exists(model_threshold_path):
  113. os.makedirs(model_threshold_path)
  114. map_filename = os.path.join(model_threshold_path, simulation_curves_zones + folder_scene)
  115. f_map = open(map_filename, 'w')
  116. for line in block_predictions_str:
  117. f_map.write(line + '\n')
  118. f_map.close()
  119. print("Scene " + str(id_scene + 1) + "/" + str(len(maxwell_scenes)) + " Done..")
  120. print("------------------------")
  121. print("Model predictions are saved into %s" % map_filename)
  122. if __name__== "__main__":
  123. main()