Debian Codegraph @

django/contrib/gis/gdal/raster/band.py

raw
1 from ctypes import byref, c_double, c_int, c_void_p
2
3 from django.contrib.gis.gdal.error import GDALException
4 from django.contrib.gis.gdal.prototypes import raster as capi
5 from django.contrib.gis.gdal.raster.base import GDALRasterBase
6 from django.contrib.gis.shortcuts import numpy
7 from django.utils.encoding import force_str
8
9 from .const import (
10 GDAL_COLOR_TYPES,
11 GDAL_INTEGER_TYPES,
12 GDAL_PIXEL_TYPES,
13 GDAL_TO_CTYPES,
14 )
15
16
17 class GDALBand(GDALRasterBase):
18 """
19 Wrap a GDAL raster band, needs to be obtained from a GDALRaster object.
20 """
21
22 def __init__(self, source, index):
23 self.source = source
24 self._ptr = capi.get_ds_raster_band(source._ptr, index)
25
26 def _flush(self):
27 """
28 Call the flush method on the Band's parent raster and force a refresh
29 of the statistics attribute when requested the next time.
30 """
31 self.source._flush()
32 self._stats_refresh = True
33
34 @property
35 def description(self):
36 """
37 Return the description string of the band.
38 """
39 return force_str(capi.get_band_description(self._ptr))
40
41 @property
42 def width(self):
43 """
44 Width (X axis) in pixels of the band.
45 """
46 return capi.get_band_xsize(self._ptr)
47
48 @property
49 def height(self):
50 """
51 Height (Y axis) in pixels of the band.
52 """
53 return capi.get_band_ysize(self._ptr)
54
55 @property
56 def pixel_count(self):
57 """
58 Return the total number of pixels in this band.
59 """
60 return self.width * self.height
61
62 _stats_refresh = False
63
64 def statistics(self, refresh=False, approximate=False):
65 """
66 Compute statistics on the pixel values of this band.
67
68 The return value is a tuple with the following structure:
69 (minimum, maximum, mean, standard deviation).
70
71 If approximate=True, the statistics may be computed based on overviews
72 or a subset of image tiles.
73
74 If refresh=True, the statistics will be computed from the data directly,
75 and the cache will be updated where applicable.
76
77 For empty bands (where all pixel values are nodata), all statistics
78 values are returned as None.
79
80 For raster formats using Persistent Auxiliary Metadata (PAM) services,
81 the statistics might be cached in an auxiliary file.
82 """
83 # Prepare array with arguments for capi function
84 smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double()
85 stats_args = [
86 self._ptr,
87 c_int(approximate),
88 byref(smin),
89 byref(smax),
90 byref(smean),
91 byref(sstd),
92 c_void_p(),
93 c_void_p(),
94 ]
95
96 if refresh or self._stats_refresh:
97 func = capi.compute_band_statistics
98 else:
99 # Add additional argument to force computation if there is no
100 # existing PAM file to take the values from.
101 force = True
102 stats_args.insert(2, c_int(force))
103 func = capi.get_band_statistics
104
105 # Computation of statistics fails for empty bands.
106 try:
107 func(*stats_args)
108 result = smin.value, smax.value, smean.value, sstd.value
109 except GDALException:
110 result = (None, None, None, None)
111
112 self._stats_refresh = False
113
114 return result
115
116 @property
117 def min(self):
118 """
119 Return the minimum pixel value for this band.
120 """
121 return self.statistics()[0]
122
123 @property
124 def max(self):
125 """
126 Return the maximum pixel value for this band.
127 """
128 return self.statistics()[1]
129
130 @property
131 def mean(self):
132 """
133 Return the mean of all pixel values of this band.
134 """
135 return self.statistics()[2]
136
137 @property
138 def std(self):
139 """
140 Return the standard deviation of all pixel values of this band.
141 """
142 return self.statistics()[3]
143
144 @property
145 def nodata_value(self):
146 """
147 Return the nodata value for this band, or None if it isn't set.
148 """
149 # Get value and nodata exists flag
150 nodata_exists = c_int()
151 value = capi.get_band_nodata_value(self._ptr, nodata_exists)
152 if not nodata_exists:
153 value = None
154 # If the pixeltype is an integer, convert to int
155 elif self.datatype() in GDAL_INTEGER_TYPES:
156 value = int(value)
157 return value
158
159 @nodata_value.setter
160 def nodata_value(self, value):
161 """
162 Set the nodata value for this band.
163 """
164 if value is None:
165 capi.delete_band_nodata_value(self._ptr)
166 elif not isinstance(value, (int, float)):
167 raise ValueError("Nodata value must be numeric or None.")
168 else:
169 capi.set_band_nodata_value(self._ptr, value)
170 self._flush()
171
172 def datatype(self, as_string=False):
173 """
174 Return the GDAL Pixel Datatype for this band.
175 """
176 dtype = capi.get_band_datatype(self._ptr)
177 if as_string:
178 dtype = GDAL_PIXEL_TYPES[dtype]
179 return dtype
180
181 def color_interp(self, as_string=False):
182 """Return the GDAL color interpretation for this band."""
183 color = capi.get_band_color_interp(self._ptr)
184 if as_string:
185 color = GDAL_COLOR_TYPES[color]
186 return color
187
188 def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False):
189 """
190 Read or writes pixel values for this band. Blocks of data can
191 be accessed by specifying the width, height and offset of the
192 desired block. The same specification can be used to update
193 parts of a raster by providing an array of values.
194
195 Allowed input data types are bytes, memoryview, list, tuple, and array.
196 """
197 offset = offset or (0, 0)
198 size = size or (self.width - offset[0], self.height - offset[1])
199 shape = shape or size
200 if any(x <= 0 for x in size):
201 raise ValueError("Offset too big for this raster.")
202
203 if size[0] > self.width or size[1] > self.height:
204 raise ValueError("Size is larger than raster.")
205
206 # Create ctypes type array generator
207 ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (shape[0] * shape[1])
208
209 if data is None:
210 # Set read mode
211 access_flag = 0
212 # Prepare empty ctypes array
213 data_array = ctypes_array()
214 else:
215 # Set write mode
216 access_flag = 1
217
218 # Instantiate ctypes array holding the input data
219 if isinstance(data, (bytes, memoryview)) or (
220 numpy and isinstance(data, numpy.ndarray)
221 ):
222 data_array = ctypes_array.from_buffer_copy(data)
223 else:
224 data_array = ctypes_array(*data)
225
226 # Access band
227 capi.band_io(
228 self._ptr,
229 access_flag,
230 offset[0],
231 offset[1],
232 size[0],
233 size[1],
234 byref(data_array),
235 shape[0],
236 shape[1],
237 self.datatype(),
238 0,
239 0,
240 )
241
242 # Return data as numpy array if possible, otherwise as list
243 if data is None:
244 if as_memoryview:
245 return memoryview(data_array)
246 elif numpy:
247 # reshape() needs a reshape parameter with the height first.
248 return numpy.frombuffer(
249 data_array, dtype=numpy.dtype(data_array)
250 ).reshape(tuple(reversed(size)))
251 else:
252 return list(data_array)
253 else:
254 self._flush()
255
256
257 class BandList(list):
258 def __init__(self, source):
259 self.source = source
260 super().__init__()
261
262 def __iter__(self):
263 for idx in range(1, len(self) + 1):
264 yield GDALBand(self.source, idx)
265
266 def __len__(self):
267 return capi.get_ds_raster_count(self.source._ptr)
268
269 def __getitem__(self, index):
270 try:
271 return GDALBand(self.source, index + 1)
272 except GDALException:
273 raise GDALException("Unable to get band index %d" % index)