pca.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import os.path as osp
  16. import numpy as np
  17. import argparse
  18. from sklearn.decomposition import PCA
  19. from joblib import dump
  20. from utils import Raster, save_geotiff, timer
  21. @timer
  22. def pca_train(img_path, save_dir="output", dim=3):
  23. raster = Raster(img_path)
  24. im = raster.getArray()
  25. n_im = np.reshape(im, (-1, raster.bands))
  26. pca = PCA(n_components=dim, whiten=True)
  27. pca_model = pca.fit(n_im)
  28. if not osp.exists(save_dir):
  29. os.makedirs(save_dir)
  30. name = osp.splitext(osp.normpath(img_path).split(os.sep)[-1])[0]
  31. model_save_path = osp.join(save_dir, (name + "_pca.joblib"))
  32. image_save_path = osp.join(save_dir, (name + "_pca.tif"))
  33. dump(pca_model, model_save_path) # save model
  34. output = pca_model.transform(n_im).reshape((raster.height, raster.width, -1))
  35. save_geotiff(output, image_save_path, raster.proj, raster.geot) # save tiff
  36. print("The Image and model of PCA saved in {}.".format(save_dir))
  37. parser = argparse.ArgumentParser(description="input parameters")
  38. parser.add_argument("--im_path", type=str, required=True, \
  39. help="The path of HSIs image.")
  40. parser.add_argument("--save_dir", type=str, default="output", \
  41. help="The params(*.joblib) saved folder, `output` is the default.")
  42. parser.add_argument("--dim", type=int, default=3, \
  43. help="The dimension after reduced, `3` is the default.")
  44. if __name__ == "__main__":
  45. args = parser.parse_args()
  46. pca_train(args.im_path, args.save_dir, args.dim)