raster.py 8.5 KB

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