raster.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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.path as osp
  15. import numpy as np
  16. from typing import List, Tuple, Union
  17. from paddlers.utils import raster2uint8
  18. try:
  19. from osgeo import gdal
  20. except:
  21. import gdal
  22. class Raster:
  23. def __init__(self,
  24. path: str,
  25. band_list: Union[List[int], Tuple[int], None]=None,
  26. to_uint8: bool=False) -> None:
  27. """ Class of read raster.
  28. Args:
  29. path (str): The path of raster.
  30. band_list (Union[List[int], Tuple[int], None], optional):
  31. band list (start with 1) or None (all of bands). Defaults to None.
  32. to_uint8 (bool, optional):
  33. Convert uint8 or return raw data. Defaults to False.
  34. """
  35. super(Raster, self).__init__()
  36. if osp.exists(path):
  37. self.path = path
  38. self.__src_data = np.load(path) if path.split(".")[-1] == "npy" \
  39. else gdal.Open(path)
  40. self._getInfo()
  41. self.to_uint8 = to_uint8
  42. self.setBands(band_list)
  43. else:
  44. raise ValueError("The path {0} not exists.".format(path))
  45. def setBands(self,
  46. band_list: Union[List[int], Tuple[int], None]) -> None:
  47. """ Set band of data.
  48. Args:
  49. band_list (Union[List[int], Tuple[int], None]):
  50. band list (start with 1) or None (all of bands).
  51. """
  52. if band_list is not None:
  53. if len(band_list) > self.bands:
  54. raise ValueError("The lenght of band_list must be less than {0}.".format(str(self.bands)))
  55. if max(band_list) > self.bands or min(band_list) < 1:
  56. raise ValueError("The range of band_list must within [1, {0}].".format(str(self.bands)))
  57. self.band_list = band_list
  58. def getArray(self,
  59. start_loc: Union[List[int], Tuple[int], None]=None,
  60. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  61. """ Get ndarray data
  62. Args:
  63. start_loc (Union[List[int], Tuple[int], None], optional):
  64. Coordinates of the upper left corner of the block, if None means return full image.
  65. block_size (Union[List[int], Tuple[int]], optional):
  66. Block size. Defaults to [512, 512].
  67. Returns:
  68. np.ndarray: data's ndarray.
  69. """
  70. if start_loc is None:
  71. return self._getAarray()
  72. else:
  73. return self._getBlock(start_loc, block_size)
  74. def _getInfo(self) -> None:
  75. self.bands = self.__src_data.RasterCount
  76. self.width = self.__src_data.RasterXSize
  77. self.height = self.__src_data.RasterYSize
  78. def _getAarray(self, window: Union[None, List[int], Tuple[int]]=None) -> np.ndarray:
  79. if window is not None:
  80. xoff, yoff, xsize, ysize = window
  81. if self.band_list is None:
  82. if window is None:
  83. ima = self.__src_data.ReadAsArray()
  84. else:
  85. ima = self.__src_data.ReadAsArray(xoff, yoff, xsize, ysize)
  86. else:
  87. band_array = []
  88. for b in self.band_list:
  89. if window is None:
  90. band_i = self.__src_data.GetRasterBand(b).ReadAsArray()
  91. else:
  92. band_i = self.__src_data.GetRasterBand(b).ReadAsArray(xoff, yoff, xsize, ysize)
  93. band_array.append(band_i)
  94. ima = np.stack(band_array, axis=0)
  95. if self.bands == 1:
  96. # the type is complex means this is a SAR data
  97. if isinstance(type(ima[0, 0]), complex):
  98. ima = abs(ima)
  99. else:
  100. ima = ima.transpose((1, 2, 0))
  101. if self.to_uint8 is True:
  102. ima = raster2uint8(ima)
  103. return ima
  104. def _getBlock(self,
  105. start_loc: Union[List[int], Tuple[int]],
  106. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  107. if len(start_loc) != 2 or len(block_size) != 2:
  108. raise ValueError("The length start_loc/block_size must be 2.")
  109. xoff, yoff = start_loc
  110. xsize, ysize = block_size
  111. if (xoff < 0 or xoff > self.width) or (yoff < 0 or yoff > self.height):
  112. raise ValueError(
  113. "start_loc must be within [0-{0}, 0-{1}].".format(str(self.width), str(self.height)))
  114. if xoff + xsize > self.width:
  115. xsize = self.width - xoff
  116. if yoff + ysize > self.height:
  117. ysize = self.height - yoff
  118. ima = self._getAarray([int(xoff), int(yoff), int(xsize), int(ysize)])
  119. h, w = ima.shape[:2] if len(ima.shape) == 3 else ima.shape
  120. if self.bands != 1:
  121. tmp = np.zeros((block_size[0], block_size[1], self.bands), dtype=ima.dtype)
  122. tmp[:h, :w, :] = ima
  123. else:
  124. tmp = np.zeros((block_size[0], block_size[1]), dtype=ima.dtype)
  125. tmp[:h, :w] = ima
  126. return tmp