reconstruct.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. for id_column in range(cfg.number_of_columns):
  19. folder_path = os.path.join(scene_path, str(id_column))
  20. pixels = []
  21. for id_row in range(cfg.number_of_rows):
  22. pixel_filename = _scene_name + '_' + str(id_column) + '_' + str(id_row) + ".dat"
  23. pixel_file_path = os.path.join(folder_path, pixel_filename)
  24. with open(pixel_file_path, 'r') as f:
  25. # predict the expected pixel value
  26. lines = [float(l)/255. for l in f.readlines()]
  27. pixel_values = lines[0:int(_n)]
  28. pixels.append(pixel_values)
  29. # predict column pixels and fill image column by column
  30. pixels_predicted = clf.predict(pixels)
  31. # change normalized predicted value to pixel value
  32. pixels_predicted = pixels_predicted*255.
  33. for id_pixel, pixel in enumerate(pixels_predicted):
  34. output_image[id_pixel, id_column] = pixel
  35. print("{0:.2f}%".format(id_column / cfg.number_of_columns * 100))
  36. sys.stdout.write("\033[F")
  37. return output_image
  38. def main():
  39. parser = argparse.ArgumentParser(description="Train model and saved it")
  40. parser.add_argument('--scene', type=str, help='Scene name to reconstruct', choices=cfg.scenes_list)
  41. parser.add_argument('--model_path', type=str, help='Model file path')
  42. parser.add_argument('--n', type=str, help='Number of pixel values approximated to keep')
  43. parser.add_argument('--image_name', type=str, help="The ouput image name")
  44. args = parser.parse_args()
  45. param_scene_name = args.scene
  46. param_n = args.n
  47. param_model_path = args.model_path
  48. param_image_name = args.image_name
  49. # get default value of `n` param
  50. if not param_n:
  51. param_n = param_model_path.split('_')[0]
  52. output_image = reconstruct(param_scene_name, param_model_path, param_n)
  53. if not os.path.exists(cfg.reconstructed_folder):
  54. os.makedirs(cfg.reconstructed_folder)
  55. image_path = os.path.join(cfg.reconstructed_folder, param_image_name)
  56. img = Image.fromarray(np.uint8(output_image))
  57. img.save(image_path)
  58. if __name__== "__main__":
  59. main()