raster.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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, Optional
  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. def _get_type(type_name: str) -> int:
  23. if type_name in ["bool", "uint8"]:
  24. gdal_type = gdal.GDT_Byte
  25. elif type_name in ["int8", "int16"]:
  26. gdal_type = gdal.GDT_Int16
  27. elif type_name == "uint16":
  28. gdal_type = gdal.GDT_UInt16
  29. elif type_name == "int32":
  30. gdal_type = gdal.GDT_Int32
  31. elif type_name == "uint32":
  32. gdal_type = gdal.GDT_UInt32
  33. elif type_name in ["int64", "uint64", "float16", "float32"]:
  34. gdal_type = gdal.GDT_Float32
  35. elif type_name == "float64":
  36. gdal_type = gdal.GDT_Float64
  37. elif type_name == "complex64":
  38. gdal_type = gdal.GDT_CFloat64
  39. else:
  40. raise TypeError("Non-suported data type `{}`.".format(type_name))
  41. return gdal_type
  42. class Raster:
  43. def __init__(self,
  44. path: Optional[str],
  45. gdal_obj: Optional[gdal.Dataset]=None,
  46. band_list: Union[List[int], Tuple[int], None]=None,
  47. to_uint8: bool=False) -> None:
  48. """ Class of read raster.
  49. Args:
  50. path (Optional[str]): The path of raster.
  51. gdal_obj (Optional[Any], optional): The object of GDAL. Defaults to None.
  52. band_list (Union[List[int], Tuple[int], None], optional):
  53. band list (start with 1) or None (all of bands). Defaults to None.
  54. to_uint8 (bool, optional):
  55. Convert uint8 or return raw data. Defaults to False.
  56. """
  57. super(Raster, self).__init__()
  58. if path is not None:
  59. if osp.exists(path):
  60. self.path = path
  61. self.ext_type = path.split(".")[-1]
  62. if self.ext_type.lower() in ["npy", "npz"]:
  63. self._src_data = None
  64. else:
  65. try:
  66. # raster format support in GDAL:
  67. # https://www.osgeo.cn/gdal/drivers/raster/index.html
  68. self._src_data = gdal.Open(path)
  69. except:
  70. raise TypeError(
  71. "Unsupported data format: `{}`".format(self.ext_type))
  72. else:
  73. raise ValueError("The path {0} not exists.".format(path))
  74. else:
  75. if gdal_obj is not None:
  76. self._src_data = gdal_obj
  77. else:
  78. raise ValueError("At least one of `path` and `gdal_obj` is not None.")
  79. self.to_uint8 = to_uint8
  80. self._getInfo()
  81. self.setBands(band_list)
  82. self._getType()
  83. def setBands(self, band_list: Union[List[int], Tuple[int], None]) -> None:
  84. """ Set band of data.
  85. Args:
  86. band_list (Union[List[int], Tuple[int], None]):
  87. band list (start with 1) or None (all of bands).
  88. """
  89. if band_list is not None:
  90. if len(band_list) > self.bands:
  91. raise ValueError(
  92. "The lenght of band_list must be less than {0}.".format(
  93. str(self.bands)))
  94. if max(band_list) > self.bands or min(band_list) < 1:
  95. raise ValueError("The range of band_list must within [1, {0}].".
  96. format(str(self.bands)))
  97. self.band_list = band_list
  98. def getArray(
  99. self,
  100. start_loc: Union[List[int], Tuple[int, int], None]=None,
  101. block_size: Union[List[int], Tuple[int, int]]=[512, 512]) -> np.ndarray:
  102. """ Get ndarray data
  103. Args:
  104. start_loc (Union[List[int], Tuple[int], None], optional):
  105. Coordinates of the upper left corner of the block, if None means return full image.
  106. block_size (Union[List[int], Tuple[int]], optional):
  107. Block size. Defaults to [512, 512].
  108. Returns:
  109. np.ndarray: data's ndarray.
  110. """
  111. if self._src_data is not None:
  112. if start_loc is None:
  113. return self._getArray()
  114. else:
  115. return self._getBlock(start_loc, block_size)
  116. else:
  117. print("Numpy doesn't support blocking temporarily.")
  118. return self._getNumpy()
  119. def _getInfo(self) -> None:
  120. if self._src_data is not None:
  121. self.width = self._src_data.RasterXSize
  122. self.height = self._src_data.RasterYSize
  123. self.bands = self._src_data.RasterCount
  124. self.geot = self._src_data.GetGeoTransform()
  125. self.proj = self._src_data.GetProjection()
  126. else:
  127. d_img = self._getNumpy()
  128. d_shape = d_img.shape
  129. if len(d_shape) == 3:
  130. self.height, self.width, self.bands = d_shape
  131. else:
  132. self.height, self.width = d_shape
  133. self.bands = 1
  134. self.geot = None
  135. self.proj = None
  136. def _getType(self) -> None:
  137. d_name = self.getArray([0, 0], [1, 1]).dtype.name
  138. self.datatype = _get_type(d_name)
  139. def _getNumpy(self):
  140. ima = np.load(self.path)
  141. if self.band_list is not None:
  142. band_array = []
  143. for b in self.band_list:
  144. band_i = ima[:, :, b - 1]
  145. band_array.append(band_i)
  146. ima = np.stack(band_array, axis=0)
  147. return ima
  148. def _getArray(
  149. self,
  150. window: Union[None, List[int], Tuple[int, int, int, int]]=None) -> np.ndarray:
  151. if self._src_data is None:
  152. raise ValueError("The raster is None.")
  153. if window is not None:
  154. xoff, yoff, xsize, ysize = window
  155. if self.band_list is None:
  156. if window is None:
  157. ima = self._src_data.ReadAsArray()
  158. else:
  159. ima = self._src_data.ReadAsArray(xoff, yoff, xsize, ysize)
  160. else:
  161. band_array = []
  162. for b in self.band_list:
  163. if window is None:
  164. band_i = self._src_data.GetRasterBand(b).ReadAsArray()
  165. else:
  166. band_i = self._src_data.GetRasterBand(b).ReadAsArray(
  167. xoff, yoff, xsize, ysize)
  168. band_array.append(band_i)
  169. ima = np.stack(band_array, axis=0)
  170. if self.bands == 1:
  171. if len(ima.shape) == 3:
  172. ima = ima.squeeze(0)
  173. # the type is complex means this is a SAR data
  174. if isinstance(type(ima[0, 0]), complex):
  175. ima = abs(ima)
  176. else:
  177. ima = ima.transpose((1, 2, 0))
  178. if self.to_uint8 is True:
  179. ima = raster2uint8(ima)
  180. return ima
  181. def _getBlock(
  182. self,
  183. start_loc: Union[List[int], Tuple[int, int]],
  184. block_size: Union[List[int], Tuple[int, int]]=[512, 512]) -> np.ndarray:
  185. if len(start_loc) != 2 or len(block_size) != 2:
  186. raise ValueError("The length start_loc/block_size must be 2.")
  187. xoff, yoff = start_loc
  188. xsize, ysize = block_size
  189. if (xoff < 0 or xoff > self.width) or (yoff < 0 or yoff > self.height):
  190. raise ValueError("start_loc must be within [0-{0}, 0-{1}].".format(
  191. str(self.width), str(self.height)))
  192. if xoff + xsize > self.width:
  193. xsize = self.width - xoff
  194. if yoff + ysize > self.height:
  195. ysize = self.height - yoff
  196. ima = self._getArray([int(xoff), int(yoff), int(xsize), int(ysize)])
  197. h, w = ima.shape[:2] if len(ima.shape) == 3 else ima.shape
  198. if self.bands != 1:
  199. tmp = np.zeros(
  200. (block_size[0], block_size[1], self.bands), dtype=ima.dtype)
  201. tmp[:h, :w, :] = ima
  202. else:
  203. tmp = np.zeros((block_size[0], block_size[1]), dtype=ima.dtype)
  204. tmp[:h, :w] = ima
  205. return tmp
  206. def save_geotiff(image: np.ndarray,
  207. save_path: str,
  208. proj: str,
  209. geotf: Tuple,
  210. use_type: Optional[int]=None,
  211. clear_ds: bool=True) -> None:
  212. if len(image.shape) == 2:
  213. height, width = image.shape
  214. channel = 1
  215. else:
  216. height, width, channel = image.shape
  217. if use_type is not None:
  218. data_type = use_type
  219. else:
  220. data_type = _get_type(image.dtype.name)
  221. driver = gdal.GetDriverByName("GTiff")
  222. dst_ds = driver.Create(save_path, width, height, channel, data_type)
  223. dst_ds.SetGeoTransform(geotf)
  224. dst_ds.SetProjection(proj)
  225. if channel > 1:
  226. for i in range(channel):
  227. band = dst_ds.GetRasterBand(i + 1)
  228. band.WriteArray(image[:, :, i])
  229. dst_ds.FlushCache()
  230. else:
  231. band = dst_ds.GetRasterBand(1)
  232. band.WriteArray(image)
  233. dst_ds.FlushCache()
  234. if clear_ds:
  235. dst_ds = None
  236. return dst_ds