raster.py 9.5 KB

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