raster.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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.transforms.functions import to_uint8 as 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.ext_type = path.split(".")[-1]
  39. if self.ext_type.lower() in ["npy", "npz"]:
  40. self._src_data = None
  41. else:
  42. try:
  43. # raster format support in GDAL:
  44. # https://www.osgeo.cn/gdal/drivers/raster/index.html
  45. self._src_data = gdal.Open(path)
  46. except:
  47. raise TypeError("Unsupported data format: `{}`".format(self.ext_type))
  48. self._getInfo()
  49. self.to_uint8 = to_uint8
  50. self.setBands(band_list)
  51. else:
  52. raise ValueError("The path {0} not exists.".format(path))
  53. def setBands(self,
  54. band_list: Union[List[int], Tuple[int], None]) -> None:
  55. """ Set band of data.
  56. Args:
  57. band_list (Union[List[int], Tuple[int], None]):
  58. band list (start with 1) or None (all of bands).
  59. """
  60. if band_list is not None:
  61. if len(band_list) > self.bands:
  62. raise ValueError("The lenght of band_list must be less than {0}.".format(str(self.bands)))
  63. if max(band_list) > self.bands or min(band_list) < 1:
  64. raise ValueError("The range of band_list must within [1, {0}].".format(str(self.bands)))
  65. self.band_list = band_list
  66. def getArray(self,
  67. start_loc: Union[List[int], Tuple[int], None]=None,
  68. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  69. """ Get ndarray data
  70. Args:
  71. start_loc (Union[List[int], Tuple[int], None], optional):
  72. Coordinates of the upper left corner of the block, if None means return full image.
  73. block_size (Union[List[int], Tuple[int]], optional):
  74. Block size. Defaults to [512, 512].
  75. Returns:
  76. np.ndarray: data's ndarray.
  77. """
  78. if self._src_data is not None:
  79. if start_loc is None:
  80. return self._getAarray()
  81. else:
  82. return self._getBlock(start_loc, block_size)
  83. else:
  84. print("Numpy doesn't support blocking temporarily.")
  85. return self._getNumpy()
  86. def _getInfo(self) -> None:
  87. if self._src_data is not None:
  88. self.bands = self._src_data.RasterCount
  89. self.width = self._src_data.RasterXSize
  90. self.height = self._src_data.RasterYSize
  91. self.geot = self._src_data.GetGeoTransform()
  92. self.proj = self._src_data.GetProjection()
  93. else:
  94. d_shape = self._getNumpy().shape
  95. if len(d_shape) == 3:
  96. self.height, self.width, self.bands = d_shape
  97. else:
  98. self.height, self.width = d_shape
  99. self.bands = 1
  100. self.geot = None
  101. self.proj = None
  102. def _getNumpy(self):
  103. ima = np.load(self.path)
  104. if self.band_list is not None:
  105. band_array = []
  106. for b in self.band_list:
  107. band_i = ima[:, :, b - 1]
  108. band_array.append(band_i)
  109. ima = np.stack(band_array, axis=0)
  110. return ima
  111. def _getAarray(self, window: Union[None, List[int], Tuple[int]]=None) -> np.ndarray:
  112. if window is not None:
  113. xoff, yoff, xsize, ysize = window
  114. if self.band_list is None:
  115. if window is None:
  116. ima = self._src_data.ReadAsArray()
  117. else:
  118. ima = self._src_data.ReadAsArray(xoff, yoff, xsize, ysize)
  119. else:
  120. band_array = []
  121. for b in self.band_list:
  122. if window is None:
  123. band_i = self._src_data.GetRasterBand(b).ReadAsArray()
  124. else:
  125. band_i = self._src_data.GetRasterBand(b).ReadAsArray(xoff, yoff, xsize, ysize)
  126. band_array.append(band_i)
  127. ima = np.stack(band_array, axis=0)
  128. if self.bands == 1:
  129. # the type is complex means this is a SAR data
  130. if isinstance(type(ima[0, 0]), complex):
  131. ima = abs(ima)
  132. else:
  133. ima = ima.transpose((1, 2, 0))
  134. if self.to_uint8 is True:
  135. ima = raster2uint8(ima)
  136. return ima
  137. def _getBlock(self,
  138. start_loc: Union[List[int], Tuple[int]],
  139. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  140. if len(start_loc) != 2 or len(block_size) != 2:
  141. raise ValueError("The length start_loc/block_size must be 2.")
  142. xoff, yoff = start_loc
  143. xsize, ysize = block_size
  144. if (xoff < 0 or xoff > self.width) or (yoff < 0 or yoff > self.height):
  145. raise ValueError(
  146. "start_loc must be within [0-{0}, 0-{1}].".format(str(self.width), str(self.height)))
  147. if xoff + xsize > self.width:
  148. xsize = self.width - xoff
  149. if yoff + ysize > self.height:
  150. ysize = self.height - yoff
  151. ima = self._getAarray([int(xoff), int(yoff), int(xsize), int(ysize)])
  152. h, w = ima.shape[:2] if len(ima.shape) == 3 else ima.shape
  153. if self.bands != 1:
  154. tmp = np.zeros((block_size[0], block_size[1], self.bands), dtype=ima.dtype)
  155. tmp[:h, :w, :] = ima
  156. else:
  157. tmp = np.zeros((block_size[0], block_size[1]), dtype=ima.dtype)
  158. tmp[:h, :w] = ima
  159. return tmp