pca.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. import paddlers
  19. from sklearn.decomposition import PCA
  20. from joblib import dump
  21. from utils import Raster, save_geotiff, time_it
  22. @time_it
  23. def pca_train(img_path, save_dir="output", dim=3):
  24. raster = Raster(img_path)
  25. im = raster.getArray()
  26. n_im = np.reshape(im, (-1, raster.bands))
  27. pca = PCA(n_components=dim, whiten=True)
  28. pca_model = pca.fit(n_im)
  29. if not osp.exists(save_dir):
  30. os.makedirs(save_dir)
  31. name = osp.splitext(osp.normpath(img_path).split(os.sep)[-1])[0]
  32. model_save_path = osp.join(save_dir, (name + "_pca.joblib"))
  33. image_save_path = osp.join(save_dir, (name + "_pca.tif"))
  34. dump(pca_model, model_save_path) # Save model
  35. output = pca_model.transform(n_im).reshape(
  36. (raster.height, raster.width, -1))
  37. save_geotiff(output, image_save_path, raster.proj, raster.geot) # Save tiff
  38. print("The output image and the PCA model are saved in {}.".format(
  39. save_dir))
  40. if __name__ == "__main__":
  41. parser = argparse.ArgumentParser()
  42. parser.add_argument("--im_path", type=str, required=True, \
  43. help="Path of HSIs image.")
  44. parser.add_argument("--save_dir", type=str, default="output", \
  45. help="Directory to save PCA params(*.joblib). Default: output.")
  46. parser.add_argument("--dim", type=int, default=3, \
  47. help="Dimension to reduce to. Default: 3.")
  48. args = parser.parse_args()
  49. pca_train(args.im_path, args.save_dir, args.dim)