predict_seuil_expe_curve.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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('--renderer', type=str,
  38. help='Renderer choice in order to limit scenes used',
  39. choices=cfg.renderer_choices,
  40. default='all',
  41. required=True)
  42. args = parser.parse_args()
  43. p_features = list(map(str.strip, args.features.split(',')))
  44. p_params = list(map(str.strip, args.params.split('::')))
  45. p_model_file = args.model
  46. p_renderer = args.renderer
  47. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  48. scenes = os.listdir(scenes_path)
  49. print(scenes)
  50. # go ahead each scenes
  51. for id_scene, folder_scene in enumerate(scenes):
  52. # only take in consideration renderer scenes
  53. if folder_scene in scenes_list:
  54. print(folder_scene)
  55. scene_path = os.path.join(scenes_path, folder_scene)
  56. # get all images of folder
  57. scene_images = sorted([os.path.join(scene_path, img) for img in os.listdir(scene_path) if cfg.scene_image_extension in img])
  58. number_scene_image = len(scene_images)
  59. start_quality_image = dt.get_scene_image_quality(scene_images[0])
  60. end_quality_image = dt.get_scene_image_quality(scene_images[-1])
  61. # using first two images find the step of quality used
  62. quality_step_image = dt.get_scene_image_quality(scene_images[1]) - start_quality_image
  63. threshold_expes = []
  64. threshold_expes_found = []
  65. block_predictions_str = []
  66. # get zones list info
  67. for index in zones:
  68. index_str = str(index)
  69. if len(index_str) < 2:
  70. index_str = "0" + index_str
  71. zone_folder = "zone"+index_str
  72. threshold_path_file = os.path.join(os.path.join(scene_path, zone_folder), threshold_expe_filename)
  73. with open(threshold_path_file) as f:
  74. threshold = int(f.readline())
  75. threshold_expes.append(threshold)
  76. # Initialize default data to get detected model threshold found
  77. threshold_expes_found.append(int(end_quality_image)) # by default use max
  78. block_predictions_str.append(index_str + ";" + p_model_file + ";" + str(threshold) + ";" + str(start_quality_image) + ";" + str(quality_step_image))
  79. # for each images
  80. for img_path in scene_images:
  81. current_img = Image.open(img_path)
  82. img_blocks = divide_in_blocks(current_img, cfg.keras_img_size)
  83. current_quality_image = dt.get_scene_image_quality(img_path)
  84. for id_block, block in enumerate(img_blocks):
  85. # check only if necessary for this scene (not already detected)
  86. #if not threshold_expes_detected[id_block]:
  87. tmp_file_path = tmp_filename.replace('__model__', p_model_file.split('/')[-1].replace('.json', '_'))
  88. block.save(tmp_file_path)
  89. python_cmd = "python predict_noisy_image.py --image " + tmp_file_path + \
  90. " --features " + p_features + \
  91. " --params " + p_params + \
  92. " --model " + p_model_file
  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. print("------------------------")
  103. print("Scene " + str(id_scene + 1) + "/" + str(len(scenes)))
  104. print("------------------------")
  105. # end of scene => display of results
  106. # construct path using model name for saving threshold map folder
  107. model_threshold_path = os.path.join(threshold_map_folder, p_model_file.split('/')[-1].replace('.joblib', ''))
  108. # create threshold model path if necessary
  109. if not os.path.exists(model_threshold_path):
  110. os.makedirs(model_threshold_path)
  111. map_filename = os.path.join(model_threshold_path, simulation_curves_zones + folder_scene)
  112. f_map = open(map_filename, 'w')
  113. for line in block_predictions_str:
  114. f_map.write(line + '\n')
  115. f_map.close()
  116. print("Scene " + str(id_scene + 1) + "/" + str(len(maxwell_scenes)) + " Done..")
  117. print("------------------------")
  118. print("Model predictions are saved into %s" % map_filename)
  119. if __name__== "__main__":
  120. main()