raster.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. from typing import List, Tuple, Union
  16. import numpy as np
  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. self.bands = self._src_data.RasterCount
  61. if band_list is not None:
  62. if len(band_list) > self.bands:
  63. raise ValueError(
  64. "The lenght of band_list must be less than {0}.".format(
  65. str(self.bands)))
  66. if max(band_list) > self.bands or min(band_list) < 1:
  67. raise ValueError("The range of band_list must within [1, {0}].".
  68. format(str(self.bands)))
  69. self.band_list = band_list
  70. def getArray(
  71. self,
  72. start_loc: Union[List[int], Tuple[int], None]=None,
  73. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  74. """ Get ndarray data
  75. Args:
  76. start_loc (Union[List[int], Tuple[int], None], optional):
  77. Coordinates of the upper left corner of the block, if None means return full image.
  78. block_size (Union[List[int], Tuple[int]], optional):
  79. Block size. Defaults to [512, 512].
  80. Returns:
  81. np.ndarray: data's ndarray.
  82. """
  83. if self._src_data is not None:
  84. if start_loc is None:
  85. return self._getArray()
  86. else:
  87. return self._getBlock(start_loc, block_size)
  88. else:
  89. print("Numpy doesn't support blocking temporarily.")
  90. return self._getNumpy()
  91. def _getInfo(self) -> None:
  92. if self._src_data is not None:
  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 _getArray(
  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. if len(ima.shape) == 3:
  146. ima = ima.squeeze(0)
  147. # the type is complex means this is a SAR data
  148. if isinstance(type(ima[0, 0]), complex):
  149. ima = abs(ima)
  150. else:
  151. ima = ima.transpose((1, 2, 0))
  152. if self.to_uint8 is True:
  153. ima = raster2uint8(ima)
  154. return ima
  155. def _getBlock(
  156. self,
  157. start_loc: Union[List[int], Tuple[int]],
  158. block_size: Union[List[int], Tuple[int]]=[512, 512]) -> np.ndarray:
  159. if len(start_loc) != 2 or len(block_size) != 2:
  160. raise ValueError("The length start_loc/block_size must be 2.")
  161. xoff, yoff = start_loc
  162. xsize, ysize = block_size
  163. if (xoff < 0 or xoff > self.width) or (yoff < 0 or yoff > self.height):
  164. raise ValueError("start_loc must be within [0-{0}, 0-{1}].".format(
  165. str(self.width), str(self.height)))
  166. if xoff + xsize > self.width:
  167. xsize = self.width - xoff
  168. if yoff + ysize > self.height:
  169. ysize = self.height - yoff
  170. ima = self._getArray([int(xoff), int(yoff), int(xsize), int(ysize)])
  171. h, w = ima.shape[:2] if len(ima.shape) == 3 else ima.shape
  172. if self.bands != 1:
  173. tmp = np.zeros(
  174. (block_size[0], block_size[1], self.bands), dtype=ima.dtype)
  175. tmp[:h, :w, :] = ima
  176. else:
  177. tmp = np.zeros((block_size[0], block_size[1]), dtype=ima.dtype)
  178. tmp[:h, :w] = ima
  179. return tmp
  180. def save_mask_geotiff(mask: np.ndarray, save_path: str, proj: str, geotf: Tuple) -> None:
  181. height, width = mask.shape
  182. driver = gdal.GetDriverByName("GTiff")
  183. dst_ds = driver.Create(save_path, width, height, 1, gdal.GDT_UInt16)
  184. dst_ds.SetGeoTransform(geotf)
  185. dst_ds.SetProjection(proj)
  186. band = dst_ds.GetRasterBand(1)
  187. band.WriteArray(mask)
  188. dst_ds.FlushCache()
  189. dst_ds = None