oif.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 itertools
  15. import argparse
  16. import paddlers
  17. import numpy as np
  18. import pandas as pd
  19. from easydict import EasyDict as edict
  20. from utils import Raster, time_it
  21. def _calcOIF(rgb, stds, rho):
  22. r, g, b = rgb
  23. s1 = stds[int(r)]
  24. s2 = stds[int(g)]
  25. s3 = stds[int(b)]
  26. r12 = rho[int(r), int(g)]
  27. r23 = rho[int(g), int(b)]
  28. r31 = rho[int(b), int(r)]
  29. return (s1 + s2 + s3) / (abs(r12) + abs(r23) + abs(r31))
  30. @time_it
  31. def oif(img_path, topk=5):
  32. raster = Raster(img_path)
  33. img = raster.getArray()
  34. img_flatten = img.reshape([-1, raster.bands])
  35. stds = np.std(img_flatten, axis=0)
  36. datas = edict()
  37. for c in range(raster.bands):
  38. datas[str(c + 1)] = img_flatten[:, c]
  39. datas = pd.DataFrame(datas)
  40. rho = datas.corr().values
  41. band_combs = edict()
  42. for rgb in itertools.combinations(list(range(raster.bands)), 3):
  43. band_combs[str(rgb)] = _calcOIF(rgb, stds, rho)
  44. band_combs = sorted(
  45. band_combs.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
  46. print("== Optimal band combination ==")
  47. for i in range(topk):
  48. k, v = band_combs[i]
  49. print("Bands: {0}, OIF value: {1}.".format(k, v))
  50. if __name__ == "__main__":
  51. parser = argparse.ArgumentParser()
  52. parser.add_argument("--im_path", type=str, required=True, \
  53. help="Path of HSIs image.")
  54. parser.add_argument("--topk", type=int, default=5, \
  55. help="Number of top results. The default value is 5.")
  56. args = parser.parse_args()
  57. oif(args.im_path, args.topk)