predict_seuil_expe_curve.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. config_filename = cfg.config_filename
  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. maxwell_scenes = cfg.maxwell_scenes_names
  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. parser = argparse.ArgumentParser(description="Script which predicts threshold using specific keras model")
  29. parser.add_argument('--features', type=str,
  30. help="list of features choice in order to compute data",
  31. default='svd_reconstruction, ipca_reconstruction',
  32. required=True)
  33. parser.add_argument('--params', type=str,
  34. help="list of specific param for each metric choice (See README.md for further information in 3D mode)",
  35. default='100, 200 :: 50, 25',
  36. required=True)
  37. parser.add_argument('--model', type=str, help='.json file of keras model', required=True)
  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_renderer = args.renderer
  48. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  49. scenes = os.listdir(scenes_path)
  50. print(scenes)
  51. # go ahead each scenes
  52. for id_scene, folder_scene in enumerate(scenes):
  53. # only take in consideration renderer scenes
  54. if folder_scene in scenes_list:
  55. print(folder_scene)
  56. scene_path = os.path.join(scenes_path, folder_scene)
  57. # get all images of folder
  58. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  59. number_scene_image = len(scene_images)
  60. start_quality_image = dt.get_scene_image_quality(scene_images[0])
  61. end_quality_image = dt.get_scene_image_quality(scene_images[-1])
  62. # using first two images find the step of quality used
  63. quality_step_image = dt.get_scene_image_quality(scene_images[1]) - start_quality_image
  64. threshold_expes = []
  65. threshold_expes_found = []
  66. block_predictions_str = []
  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_found.append(int(end_quality_image)) # by default use max
  79. block_predictions_str.append(index_str + ";" + p_model_file + ";" + str(threshold) + ";" + str(start_quality_image) + ";" + str(quality_step_image))
  80. # for each images
  81. for img_path in scene_images:
  82. current_img = Image.open(img_path)
  83. img_blocks = divide_in_blocks(current_img, cfg.keras_img_size)
  84. current_quality_image = dt.get_scene_image_quality(img_path)
  85. for id_block, block in enumerate(img_blocks):
  86. # check only if necessary for this scene (not already detected)
  87. #if not threshold_expes_detected[id_block]:
  88. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.json', '_'))
  89. block.save(tmp_file_path)
  90. python_cmd = "python predict_noisy_image.py --image " + tmp_file_path + \
  91. " --features " + p_features + \
  92. " --params " + p_params + \
  93. " --model " + p_model_file
  94. ## call command ##
  95. p = subprocess.Popen(python_cmd, stdout=subprocess.PIPE, shell=True)
  96. (output, err) = p.communicate()
  97. ## Wait for result ##
  98. p_status = p.wait()
  99. prediction = int(output)
  100. # save here in specific file of block all the predictions done
  101. block_predictions_str[id_block] = block_predictions_str[id_block] + ";" + str(prediction)
  102. print(str(id_block) + " : " + str(current_quality_image) + "/" + str(threshold_expes[id_block]) + " => " + str(prediction))
  103. print("------------------------")
  104. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  105. print("------------------------")
  106. # end of scene => display of results
  107. # construct path using model name for saving threshold map folder
  108. model_threshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  109. # create threshold model path if necessary
  110. if not os.path.exists(model_threshold_path):
  111. os.makedirs(model_threshold_path)
  112. map_filename = os.path.join(model_threshold_path, simulation_curves_zones + folder_scene)
  113. f_map = open(map_filename, 'w')
  114. for line in block_predictions_str:
  115. f_map.write(line + '\n')
  116. f_map.close()
  117. print("Scene " + str(id_scene + 1) + "/" + str(len(maxwell_scenes)) + " Done..")
  118. print("------------------------")
  119. print("Model predictions are saved into %s" % map_filename)
  120. if __name__== "__main__":
  121. main()