raster.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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(
  48. self.ext_type))
  49. self.to_uint8 = to_uint8
  50. self.setBands(band_list)
  51. self._getInfo()
  52. else:
  53. raise ValueError("The path {0} not exists.".format(path))
  54. def setBands(self, 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(
  63. "The lenght of band_list must be less than {0}.".format(
  64. str(self.bands)))
  65. if max(band_list) > self.bands or min(band_list) < 1:
  66. raise ValueError("The range of band_list must within [1, {0}].".
  67. format(str(self.bands)))
  68. self.band_list = band_list
  69. def getArray(
  70. self,
  71. start_loc: Union[List[int], Tuple[int], None]=None,
  72. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  73. """ Get ndarray data
  74. Args:
  75. start_loc (Union[List[int], Tuple[int], None], optional):
  76. Coordinates of the upper left corner of the block, if None means return full image.
  77. block_size (Union[List[int], Tuple[int]], optional):
  78. Block size. Defaults to [512, 512].
  79. Returns:
  80. np.ndarray: data's ndarray.
  81. """
  82. if self._src_data is not None:
  83. if start_loc is None:
  84. return self._getAarray()
  85. else:
  86. return self._getBlock(start_loc, block_size)
  87. else:
  88. print("Numpy doesn't support blocking temporarily.")
  89. return self._getNumpy()
  90. def _getInfo(self) -> None:
  91. if self._src_data is not None:
  92. self.bands = self._src_data.RasterCount
  93. self.width = self._src_data.RasterXSize
  94. self.height = self._src_data.RasterYSize
  95. self.geot = self._src_data.GetGeoTransform()
  96. self.proj = self._src_data.GetProjection()
  97. d_name = self._getBlock([0, 0], [1, 1]).dtype.name
  98. else:
  99. d_img = self._getNumpy()
  100. d_shape = d_img.shape
  101. d_name = d_img.dtype.name
  102. if len(d_shape) == 3:
  103. self.height, self.width, self.bands = d_shape
  104. else:
  105. self.height, self.width = d_shape
  106. self.bands = 1
  107. self.geot = None
  108. self.proj = None
  109. if "int8" in d_name:
  110. self.datatype = gdal.GDT_Byte
  111. elif "int16" in d_name:
  112. self.datatype = gdal.GDT_UInt16
  113. else:
  114. self.datatype = gdal.GDT_Float32
  115. def _getNumpy(self):
  116. ima = np.load(self.path)
  117. if self.band_list is not None:
  118. band_array = []
  119. for b in self.band_list:
  120. band_i = ima[:, :, b - 1]
  121. band_array.append(band_i)
  122. ima = np.stack(band_array, axis=0)
  123. return ima
  124. def _getAarray(
  125. self,
  126. window: Union[None, List[int], Tuple[int]]=None) -> np.ndarray:
  127. if window is not None:
  128. xoff, yoff, xsize, ysize = window
  129. if self.band_list is None:
  130. if window is None:
  131. ima = self._src_data.ReadAsArray()
  132. else:
  133. ima = self._src_data.ReadAsArray(xoff, yoff, xsize, ysize)
  134. else:
  135. band_array = []
  136. for b in self.band_list:
  137. if window is None:
  138. band_i = self._src_data.GetRasterBand(b).ReadAsArray()
  139. else:
  140. band_i = self._src_data.GetRasterBand(b).ReadAsArray(
  141. xoff, yoff, xsize, ysize)
  142. band_array.append(band_i)
  143. ima = np.stack(band_array, axis=0)
  144. if self.bands == 1:
  145. # the type is complex means this is a SAR data
  146. if isinstance(type(ima[0, 0]), complex):
  147. ima = abs(ima)
  148. else:
  149. ima = ima.transpose((1, 2, 0))
  150. if self.to_uint8 is True:
  151. ima = raster2uint8(ima)
  152. return ima
  153. def _getBlock(
  154. self,
  155. start_loc: Union[List[int], Tuple[int]],
  156. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  157. if len(start_loc) != 2 or len(block_size) != 2:
  158. raise ValueError("The length start_loc/block_size must be 2.")
  159. xoff, yoff = start_loc
  160. xsize, ysize = block_size
  161. if (xoff < 0 or xoff > self.width) or (yoff < 0 or yoff > self.height):
  162. raise ValueError("start_loc must be within [0-{0}, 0-{1}].".format(
  163. str(self.width), str(self.height)))
  164. if xoff + xsize > self.width:
  165. xsize = self.width - xoff
  166. if yoff + ysize > self.height:
  167. ysize = self.height - yoff
  168. ima = self._getAarray([int(xoff), int(yoff), int(xsize), int(ysize)])
  169. h, w = ima.shape[:2] if len(ima.shape) == 3 else ima.shape
  170. if self.bands != 1:
  171. tmp = np.zeros(
  172. (block_size[0], block_size[1], self.bands), dtype=ima.dtype)
  173. tmp[:h, :w, :] = ima
  174. else:
  175. tmp = np.zeros((block_size[0], block_size[1]), dtype=ima.dtype)
  176. tmp[:h, :w] = ima
  177. return tmp