Coverage for src/rok4/utils.py: 97%

103 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-01 12:58 +0000

1"""Provide functions to manipulate OGR / OSR entities""" 

2 

3# -- IMPORTS -- 

4 

5# standard library 

6import os 

7import re 

8from typing import Tuple 

9 

10# 3rd party 

11from osgeo import gdal, ogr, osr 

12 

13# package 

14from rok4.enums import ColorFormat 

15 

16# -- GLOBALS -- 

17ogr.UseExceptions() 

18osr.UseExceptions() 

19gdal.UseExceptions() 

20 

21__SR_BOOK = {} 

22 

23 

24def srs_to_spatialreference(srs: str) -> "osgeo.osr.SpatialReference": 

25 """Convert coordinates system as string to OSR spatial reference 

26 

27 Using a cache, to instanciate a Spatial Reference from a string only once. 

28 

29 Args: 

30 srs (str): coordinates system PROJ4 compliant, with authority and code, like EPSG:3857 or IGNF:LAMB93 

31 

32 Raises: 

33 RuntimeError: Provided SRS is invalid for OSR 

34 

35 Returns: 

36 osgeo.osr.SpatialReference: Corresponding OSR spatial reference 

37 """ 

38 

39 global __SR_BOOK 

40 

41 if srs.upper() not in __SR_BOOK: 

42 authority, code = srs.split(":", 1) 

43 

44 sr = osr.SpatialReference() 

45 if authority.upper() == "EPSG": 

46 sr.ImportFromEPSG(int(code)) 

47 else: 

48 sr.ImportFromProj4(f"+init={srs.upper()} +wktext") 

49 

50 __SR_BOOK[srs.upper()] = sr 

51 

52 return __SR_BOOK[srs.upper()] 

53 

54 

55def bbox_to_geometry( 

56 bbox: Tuple[float, float, float, float], densification: int = 0 

57) -> "osgeo.ogr.Geometry": 

58 """Convert bbox coordinates to OGR geometry 

59 

60 Args: 

61 bbox (Tuple[float, float, float, float]): bounding box (xmin, ymin, xmax, ymax) 

62 densification (int, optional): Number of point to add for each side of bounding box. Defaults to 0. 

63 

64 Raises: 

65 RuntimeError: Provided SRS is invalid for OSR 

66 

67 Returns: 

68 osgeo.ogr.Geometry: Corresponding OGR geometry, with spatial reference if provided 

69 """ 

70 

71 ring = ogr.Geometry(ogr.wkbLinearRing) 

72 

73 if densification > 0: 

74 step_x = (bbox[2] - bbox[0]) / (densification + 1) 

75 step_y = (bbox[3] - bbox[1]) / (densification + 1) 

76 

77 for i in range(densification + 1): 

78 ring.AddPoint(bbox[0] + step_x * i, bbox[1]) 

79 for i in range(densification + 1): 

80 ring.AddPoint(bbox[2], bbox[1] + step_y * i) 

81 for i in range(densification + 1): 

82 ring.AddPoint(bbox[2] - step_x * i, bbox[3]) 

83 for i in range(densification + 1): 

84 ring.AddPoint(bbox[0], bbox[3] - step_y * i) 

85 ring.AddPoint(bbox[0], bbox[1]) 

86 

87 else: 

88 ring.AddPoint(bbox[0], bbox[1]) 

89 ring.AddPoint(bbox[2], bbox[1]) 

90 ring.AddPoint(bbox[2], bbox[3]) 

91 ring.AddPoint(bbox[0], bbox[3]) 

92 ring.AddPoint(bbox[0], bbox[1]) 

93 

94 geom = ogr.Geometry(ogr.wkbPolygon) 

95 geom.AddGeometry(ring) 

96 geom.SetCoordinateDimension(2) 

97 

98 return geom 

99 

100 

101def reproject_bbox( 

102 bbox: Tuple[float, float, float, float], srs_src: str, srs_dst: str, densification: int = 5 

103) -> Tuple[float, float, float, float]: 

104 """Return bounding box in other coordinates system 

105 

106 Points are added to be sure output bounding box contains input bounding box 

107 

108 Args: 

109 bbox (Tuple[float, float, float, float]): bounding box (xmin, ymin, xmax, ymax) with source coordinates system 

110 srs_src (str): source coordinates system 

111 srs_dst (str): destination coordinates system 

112 densification (int, optional): Number of point to add for each side of bounding box. Defaults to 5. 

113 

114 Returns: 

115 Tuple[float, float, float, float]: bounding box (xmin, ymin, xmax, ymax) with destination coordinates system 

116 """ 

117 

118 sr_src = srs_to_spatialreference(srs_src) 

119 sr_src_inv = sr_src.EPSGTreatsAsLatLong() or sr_src.EPSGTreatsAsNorthingEasting() 

120 

121 sr_dst = srs_to_spatialreference(srs_dst) 

122 sr_dst_inv = sr_dst.EPSGTreatsAsLatLong() or sr_dst.EPSGTreatsAsNorthingEasting() 

123 

124 if sr_src.IsSame(sr_dst) and sr_src_inv == sr_dst_inv: 

125 # Les système sont vraiment les même, avec le même ordre des axes 

126 return bbox 

127 elif sr_src.IsSame(sr_dst) and sr_src_inv != sr_dst_inv: 

128 # Les système sont les même pour OSR, mais l'ordre des axes est différent 

129 return (bbox[1], bbox[0], bbox[3], bbox[2]) 

130 

131 # Systèmes différents 

132 

133 bbox_src = bbox_to_geometry(bbox, densification) 

134 bbox_src.AssignSpatialReference(sr_src) 

135 

136 bbox_dst = bbox_src.Clone() 

137 os.environ["OGR_ENABLE_PARTIAL_REPROJECTION"] = "YES" 

138 bbox_dst.TransformTo(sr_dst) 

139 

140 env = bbox_dst.GetEnvelope() 

141 return (env[0], env[2], env[1], env[3]) 

142 

143 

144def reproject_point( 

145 point: Tuple[float, float], 

146 sr_src: "osgeo.osr.SpatialReference", 

147 sr_dst: "osgeo.osr.SpatialReference", 

148) -> Tuple[float, float]: 

149 """Reproject a point 

150 

151 Args: 

152 point (Tuple[float, float]): source spatial reference point 

153 sr_src (osgeo.osr.SpatialReference): source spatial reference 

154 sr_dst (osgeo.osr.SpatialReference): destination spatial reference 

155 

156 Returns: 

157 Tuple[float, float]: X/Y in destination spatial reference 

158 """ 

159 

160 sr_src_inv = sr_src.EPSGTreatsAsLatLong() or sr_src.EPSGTreatsAsNorthingEasting() 

161 sr_dst_inv = sr_dst.EPSGTreatsAsLatLong() or sr_dst.EPSGTreatsAsNorthingEasting() 

162 

163 if sr_src.IsSame(sr_dst) and sr_src_inv == sr_dst_inv: 

164 # Les système sont vraiment les mêmes, avec le même ordre des axes 

165 return (point[0], point[1]) 

166 elif sr_src.IsSame(sr_dst) and sr_src_inv != sr_dst_inv: 

167 # Les système sont les même pour OSR, mais l'ordre des axes est différent 

168 return (point[1], point[0]) 

169 

170 # Systèmes différents 

171 ct = osr.CreateCoordinateTransformation(sr_src, sr_dst) 

172 x_dst, y_dst, z_dst = ct.TransformPoint(point[0], point[1]) 

173 

174 return (x_dst, y_dst) 

175 

176 

177def compute_bbox(source_dataset: gdal.Dataset) -> Tuple: 

178 """Image boundingbox computing method 

179 

180 Args: 

181 source_dataset (gdal.Dataset): Dataset instanciated 

182 from the raster image 

183 

184 Limitations: 

185 Image's axis must be parallel to SRS' axis 

186 

187 Raises: 

188 AttributeError: source_dataset is not a gdal.Dataset instance. 

189 Exception: The dataset does not contain transform data. 

190 """ 

191 bbox = None 

192 transform_vector = source_dataset.GetGeoTransform() 

193 if transform_vector is None: 

194 raise Exception( 

195 "No transform vector found in the dataset created from " 

196 + f"the following file : {source_dataset.GetFileList()[0]}" 

197 ) 

198 width = source_dataset.RasterXSize 

199 height = source_dataset.RasterYSize 

200 x_range = ( 

201 transform_vector[0], 

202 transform_vector[0] + width * transform_vector[1] + height * transform_vector[2], 

203 ) 

204 y_range = ( 

205 transform_vector[3], 

206 transform_vector[3] + width * transform_vector[4] + height * transform_vector[5], 

207 ) 

208 spatial_ref = source_dataset.GetSpatialRef() 

209 if spatial_ref is not None and spatial_ref.GetDataAxisToSRSAxisMapping() == [2, 1]: 

210 # Coordonnées terrain de type (latitude, longitude) 

211 # => on permute les coordonnées terrain par rapport à l'image 

212 bbox = (min(y_range), min(x_range), max(y_range), max(x_range)) 

213 else: 

214 # Coordonnées terrain de type (longitude, latitude) ou pas de SRS 

215 # => les coordonnées terrain sont dans le même ordre que celle de l'image 

216 bbox = (min(x_range), min(y_range), max(x_range), max(y_range)) 

217 return bbox 

218 

219 

220def compute_format(dataset: gdal.Dataset, path: str = None) -> ColorFormat: 

221 """Image color format computing method 

222 

223 Args: 

224 dataset (gdal.Dataset): Dataset instanciated from the image 

225 path (str, optionnal): path to the original file/object 

226 

227 Raises: 

228 AttributeError: source_dataset is not a gdal.Dataset instance. 

229 Exception: No color band found or unsupported color format. 

230 """ 

231 color_format = None 

232 if path is None: 

233 path = dataset.GetFileList()[0] 

234 if dataset.RasterCount < 1: 

235 raise Exception(f"Image {path} contains no color band.") 

236 

237 band_1_datatype = dataset.GetRasterBand(1).DataType 

238 data_type_name = gdal.GetDataTypeName(band_1_datatype) 

239 data_type_size = gdal.GetDataTypeSize(band_1_datatype) 

240 color_interpretation = dataset.GetRasterBand(1).GetRasterColorInterpretation() 

241 color_name = None 

242 if color_interpretation is not None: 

243 color_name = gdal.GetColorInterpretationName(color_interpretation) 

244 compression_regex_match = re.search(r"COMPRESSION\s*=\s*PACKBITS", gdal.Info(dataset)) 

245 

246 if ( 

247 data_type_name == "Byte" 

248 and data_type_size == 8 

249 and color_name == "Palette" 

250 and compression_regex_match 

251 ): 

252 # Compris par libTIFF comme du noir et blanc sur 1 bit 

253 color_format = ColorFormat.BIT 

254 elif data_type_name == "Byte" and data_type_size == 8: 

255 color_format = ColorFormat.UINT8 

256 elif data_type_name == "Float32" and data_type_size == 32: 

257 color_format = ColorFormat.FLOAT32 

258 else: 

259 raise Exception( 

260 f"Unsupported color format for image {path} : " 

261 + f"'{data_type_name}' ({data_type_size} bits)" 

262 ) 

263 return color_format