reconstruct.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import numpy as np
  2. import pandas as pd
  3. import os, sys, argparse
  4. from sklearn import linear_model
  5. from sklearn import svm
  6. from sklearn.utils import shuffle
  7. import modules.config as cfg
  8. import modules.metrics as metrics
  9. from joblib import dump, load
  10. from PIL import Image
  11. def reconstruct(_scene_name, _model_path, _n):
  12. # construct the empty output image
  13. output_image = np.empty([cfg.number_of_rows, cfg.number_of_columns])
  14. # load the trained model
  15. clf = load(_model_path)
  16. # load scene and its `n` first pixel value data
  17. scene_path = os.path.join(cfg.folder_scenes_path, _scene_name)
  18. columns_folder = os.listdir(scene_path)
  19. for id_column, column in enumerate(columns_folder):
  20. folder_path = os.path.join(scene_path, column)
  21. pixel_files_list = os.listdir(folder_path)
  22. pixels = []
  23. for id_row, pixel_file in enumerate(pixel_files_list):
  24. pixel_file_path = os.path.join(folder_path, pixel_file)
  25. with open(pixel_file_path, 'r') as f:
  26. # predict the expected pixel value
  27. lines = [float(l)/255. for l in f.readlines()]
  28. pixel_values = lines[0:int(_n)]
  29. pixels.append(pixel_values)
  30. # predict column pixels and fill image column by column
  31. pixels_predicted = clf.predict(pixels)
  32. output_image[id_column] = pixels_predicted*255.
  33. print("{0:.2f}%".format(id_column / cfg.number_of_columns * 100))
  34. sys.stdout.write("\033[F")
  35. return output_image
  36. def main():
  37. parser = argparse.ArgumentParser(description="Train model and saved it")
  38. parser.add_argument('--scene', type=str, help='Scene name to reconstruct', choices=cfg.scenes_list)
  39. parser.add_argument('--model_path', type=str, help='Model file path')
  40. parser.add_argument('--n', type=str, help='Number of pixel values approximated to keep')
  41. parser.add_argument('--image_name', type=str, help="The ouput image name")
  42. args = parser.parse_args()
  43. param_scene_name = args.scene
  44. param_n = args.n
  45. param_model_path = args.model_path
  46. param_image_name = args.image_name
  47. # get default value of `n` param
  48. if not param_n:
  49. param_n = param_model_path.split('_')[0]
  50. output_image = reconstruct(param_scene_name, param_model_path, param_n)
  51. if not os.path.exists(cfg.reconstructed_folder):
  52. os.makedirs(cfg.reconstructed_folder)
  53. image_path = os.path.join(cfg.reconstructed_folder, param_image_name)
  54. img = Image.fromarray(np.uint8(output_image))
  55. img.save(image_path)
  56. if __name__== "__main__":
  57. main()