reconstruct_keras.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # main imports
  2. import numpy as np
  3. import pandas as pd
  4. import json
  5. import os, sys, argparse
  6. # models imports
  7. from keras.models import model_from_json
  8. from joblib import dump, load
  9. # image processing imports
  10. from PIL import Image
  11. # modules and config imports
  12. sys.path.insert(0, '') # trick to enable import of main folder module
  13. import custom_config as cfg
  14. from features import compute_feature
  15. def reconstruct(_scene_name, _model_path, _n, _feature_choice):
  16. # construct the empty output image
  17. output_image = np.empty([cfg.number_of_rows, cfg.number_of_columns])
  18. # load the trained model
  19. with open(_model_path, 'r') as f:
  20. json_model = json.load(f)
  21. model = model_from_json(json_model)
  22. model.load_weights(_model_path.replace('.json', '.h5'))
  23. model.compile(loss='binary_crossentropy',
  24. optimizer='adam',
  25. metrics=['accuracy'])
  26. # load scene and its `n` first pixel value data
  27. scene_path = os.path.join(cfg.dataset_path, _scene_name)
  28. for id_column in range(cfg.number_of_columns):
  29. folder_path = os.path.join(scene_path, str(id_column))
  30. pixels_predicted = []
  31. for id_row in range(cfg.number_of_rows):
  32. pixel_filename = _scene_name + '_' + str(id_column) + '_' + str(id_row) + ".dat"
  33. pixel_file_path = os.path.join(folder_path, pixel_filename)
  34. with open(pixel_file_path, 'r') as f:
  35. # predict the expected pixel value
  36. lines = [float(l)/255. for l in f.readlines()]
  37. pixel_values = lines[0:int(_n)]
  38. data = compute_feature(_feature_choice, pixel_values)
  39. pixel_values = np.array(data).reshape(1, (int(_n)))
  40. # predict pixel per pixel
  41. pixels_predicted.append(model.predict(pixel_values))
  42. # change normalized predicted value to pixel value
  43. pixels_predicted = [ val * 255. for val in pixels_predicted]
  44. for id_pixel, pixel in enumerate(pixels_predicted):
  45. output_image[id_pixel, id_column] = pixel
  46. print("{0:.2f}%".format(id_column / cfg.number_of_columns * 100))
  47. sys.stdout.write("\033[F")
  48. return output_image
  49. def main():
  50. parser = argparse.ArgumentParser(description="Train model and saved it")
  51. parser.add_argument('--scene', type=str, help='Scene name to reconstruct', choices=cfg.scenes_list)
  52. parser.add_argument('--model_path', type=str, help='Json model file path')
  53. parser.add_argument('--n', type=str, help='Number of pixel values approximated to keep')
  54. parser.add_argument('--feature', type=str, help='Feature choice to compute from samples', choices=cfg.features_list)
  55. parser.add_argument('--image_name', type=str, help="The ouput image name")
  56. args = parser.parse_args()
  57. param_scene_name = args.scene
  58. param_n = args.n
  59. param_feature = args.feature
  60. param_model_path = args.model_path
  61. param_image_name = args.image_name
  62. # get default value of `n` param
  63. if not param_n:
  64. param_n = param_model_path.split('_')[0]
  65. output_image = reconstruct(param_scene_name, param_model_path, param_n, param_feature)
  66. if not os.path.exists(cfg.reconstructed_folder):
  67. os.makedirs(cfg.reconstructed_folder)
  68. image_path = os.path.join(cfg.reconstructed_folder, param_image_name)
  69. img = Image.fromarray(np.uint8(output_image))
  70. img.save(image_path)
  71. if __name__== "__main__":
  72. main()