1
2
3
4
5
6
7 from sys import version_info as _swig_python_version_info
8 if _swig_python_version_info >= (2, 7, 0):
10 import importlib
11 pkg = __name__.rpartition('.')[0]
12 mname = '.'.join((pkg, '_gdal_array')).lstrip('.')
13 try:
14 return importlib.import_module(mname)
15 except ImportError:
16 return importlib.import_module('_gdal_array')
17 _gdal_array = swig_import_helper()
18 del swig_import_helper
19 elif _swig_python_version_info >= (2, 6, 0):
21 from os.path import dirname
22 import imp
23 fp = None
24 try:
25 fp, pathname, description = imp.find_module('_gdal_array', [dirname(__file__)])
26 except ImportError:
27 import _gdal_array
28 return _gdal_array
29 try:
30 _mod = imp.load_module('_gdal_array', fp, pathname, description)
31 finally:
32 if fp is not None:
33 fp.close()
34 return _mod
35 _gdal_array = swig_import_helper()
36 del swig_import_helper
37 else:
38 import _gdal_array
39 del _swig_python_version_info
40
41 try:
42 _swig_property = property
43 except NameError:
44 pass
45
46 try:
47 import builtins as __builtin__
48 except ImportError:
49 import __builtin__
50
52 if (name == "thisown"):
53 return self.this.own(value)
54 if (name == "this"):
55 if type(value).__name__ == 'SwigPyObject':
56 self.__dict__[name] = value
57 return
58 method = class_type.__swig_setmethods__.get(name, None)
59 if method:
60 return method(self, value)
61 if (not static):
62 if _newclass:
63 object.__setattr__(self, name, value)
64 else:
65 self.__dict__[name] = value
66 else:
67 raise AttributeError("You cannot add attributes to %s" % self)
68
69
72
73
75 if (name == "thisown"):
76 return self.this.own()
77 method = class_type.__swig_getmethods__.get(name, None)
78 if method:
79 return method(self)
80 raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))
81
82
84 try:
85 strthis = "proxy of " + self.this.__repr__()
86 except __builtin__.Exception:
87 strthis = ""
88 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
89
90 try:
91 _object = object
92 _newclass = 1
93 except __builtin__.Exception:
96 _newclass = 0
97
98 import osgeo.gdal
100 """Proxy of C++ CPLVirtualMemShadow class."""
101
102 __swig_setmethods__ = {}
103 __setattr__ = lambda self, name, value: _swig_setattr(self, VirtualMem, name, value)
104 __swig_getmethods__ = {}
105 __getattr__ = lambda self, name: _swig_getattr(self, VirtualMem, name)
106
108 raise AttributeError("No constructor defined")
109 __repr__ = _swig_repr
110 __swig_destroy__ = _gdal_array.delete_VirtualMem
111 __del__ = lambda self: None
112
114 """GetAddr(VirtualMem self)"""
115 return _gdal_array.VirtualMem_GetAddr(self)
116
117
118 - def Pin(self, start_offset=0, nsize=0, bWriteOp=0):
119 """
120 Pin(VirtualMem self, size_t start_offset=0, size_t nsize=0, int bWriteOp=0)
121 Pin(VirtualMem self, size_t start_offset=0, size_t nsize=0)
122 Pin(VirtualMem self, size_t start_offset=0)
123 Pin(VirtualMem self)
124 """
125 return _gdal_array.VirtualMem_Pin(self, start_offset, nsize, bWriteOp)
126
127 VirtualMem_swigregister = _gdal_array.VirtualMem_swigregister
128 VirtualMem_swigregister(VirtualMem)
129
130
134
136 """TermProgress_nocb(double dfProgress, char const * pszMessage=None, void * pData=None) -> int"""
137 return _gdal_array.TermProgress_nocb(dfProgress, pszMessage, pData)
138 TermProgress = _gdal_array.TermProgress
139
141 """OpenNumPyArray(PyArrayObject * psArray, bool binterleave) -> Dataset"""
142 return _gdal_array.OpenNumPyArray(psArray, binterleave)
143
147
149 """GetArrayFilename(PyArrayObject * psArray) -> retStringAndCPLFree *"""
150 return _gdal_array.GetArrayFilename(psArray)
151
152 -def BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None):
153 """BandRasterIONumPy(Band band, int bWrite, double xoff, double yoff, double xsize, double ysize, PyArrayObject * psArray, int buf_type, GDALRIOResampleAlg resample_alg, GDALProgressFunc callback=0, void * callback_data=None) -> CPLErr"""
154 return _gdal_array.BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data)
155
156 -def DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None, binterleave=True):
157 """DatasetIONumPy(Dataset ds, int bWrite, double xoff, double yoff, double xsize, double ysize, PyArrayObject * psArray, int buf_type, GDALRIOResampleAlg resample_alg, GDALProgressFunc callback=0, void * callback_data=None, bool binterleave=True) -> CPLErr"""
158 return _gdal_array.DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data, binterleave)
159
160 -def MDArrayIONumPy(bWrite, mdarray, psArray, nDims1, nDims3, buffer_datatype):
161 """MDArrayIONumPy(bool bWrite, GDALMDArrayHS * mdarray, PyArrayObject * psArray, int nDims1, int nDims3, GDALExtendedDataTypeHS * buffer_datatype) -> CPLErr"""
162 return _gdal_array.MDArrayIONumPy(bWrite, mdarray, psArray, nDims1, nDims3, buffer_datatype)
163
165 """VirtualMemGetArray(VirtualMem virtualmem)"""
166 return _gdal_array.VirtualMemGetArray(virtualmem)
167
169 """RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart, PyArrayObject * psArray) -> CPLErr"""
170 return _gdal_array.RATValuesIONumPyWrite(poRAT, nField, nStart, psArray)
171
173 """RATValuesIONumPyRead(RasterAttributeTable poRAT, int nField, int nStart, int nLength) -> PyObject *"""
174 return _gdal_array.RATValuesIONumPyRead(poRAT, nField, nStart, nLength)
175
176 import numpy
177
178 from osgeo import gdalconst
179 from osgeo import gdal
180 gdal.AllRegister()
181
182 codes = {gdalconst.GDT_Byte: numpy.uint8,
183 gdalconst.GDT_UInt16: numpy.uint16,
184 gdalconst.GDT_Int16: numpy.int16,
185 gdalconst.GDT_UInt32: numpy.uint32,
186 gdalconst.GDT_Int32: numpy.int32,
187 gdalconst.GDT_Float32: numpy.float32,
188 gdalconst.GDT_Float64: numpy.float64,
189 gdalconst.GDT_CInt16: numpy.complex64,
190 gdalconst.GDT_CInt32: numpy.complex64,
191 gdalconst.GDT_CFloat32: numpy.complex64,
192 gdalconst.GDT_CFloat64: numpy.complex128}
193
194
195 -def OpenArray(array, prototype_ds=None, interleave='band'):
196
197 interleave = interleave.lower()
198 if interleave == 'band':
199 interleave = True
200 elif interleave == 'pixel':
201 interleave = False
202 else:
203 raise ValueError('Interleave should be band or pixel')
204
205 ds = OpenNumPyArray(array, interleave)
206
207 if ds is not None and prototype_ds is not None:
208 if type(prototype_ds).__name__ == 'str':
209 prototype_ds = gdal.Open(prototype_ds)
210 if prototype_ds is not None:
211 CopyDatasetInfo(prototype_ds, ds)
212
213 return ds
214
215
234
236 if not isinstance(numeric_type, (numpy.dtype, type)):
237 raise TypeError("Input must be a type")
238 return flip_code(numeric_type)
239
242
247
248 -def LoadFile(filename, xoff=0, yoff=0, xsize=None, ysize=None,
249 buf_xsize=None, buf_ysize=None, buf_type=None,
250 resample_alg=gdal.GRIORA_NearestNeighbour,
251 callback=None, callback_data=None, interleave='band'):
252 ds = gdal.Open(filename)
253 if ds is None:
254 raise ValueError("Can't open "+filename+"\n\n"+gdal.GetLastErrorMsg())
255
256 return DatasetReadAsArray(ds, xoff, yoff, xsize, ysize,
257 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type,
258 resample_alg=resample_alg,
259 callback=callback, callback_data=callback_data, interleave=interleave)
260
261 -def SaveArray(src_array, filename, format="GTiff", prototype=None, interleave='band'):
262 driver = gdal.GetDriverByName(format)
263 if driver is None:
264 raise ValueError("Can't find driver "+format)
265
266 return driver.CreateCopy(filename, OpenArray(src_array, prototype, interleave))
267
268
269 -def DatasetReadAsArray(ds, xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_obj=None,
270 buf_xsize=None, buf_ysize=None, buf_type=None,
271 resample_alg=gdal.GRIORA_NearestNeighbour,
272 callback=None, callback_data=None, interleave='band'):
273 """Pure python implementation of reading a chunk of a GDAL file
274 into a numpy array. Used by the gdal.Dataset.ReadAsArray method."""
275
276 if win_xsize is None:
277 win_xsize = ds.RasterXSize
278 if win_ysize is None:
279 win_ysize = ds.RasterYSize
280
281 interleave = interleave.lower()
282 if interleave == 'band':
283 interleave = True
284 xdim = 2
285 ydim = 1
286 banddim = 0
287 elif interleave == 'pixel':
288 interleave = False
289 xdim = 1
290 ydim = 0
291 banddim = 2
292 else:
293 raise ValueError('Interleave should be band or pixel')
294
295 if ds.RasterCount == 0:
296 return None
297
298 if ds.RasterCount == 1:
299 return BandReadAsArray(ds.GetRasterBand(1), xoff, yoff, win_xsize, win_ysize,
300 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type,
301 buf_obj=buf_obj,
302 resample_alg=resample_alg,
303 callback=callback,
304 callback_data=callback_data)
305
306 if buf_obj is None:
307 if buf_xsize is None:
308 buf_xsize = win_xsize
309 if buf_ysize is None:
310 buf_ysize = win_ysize
311 if buf_type is None:
312 buf_type = ds.GetRasterBand(1).DataType
313 for band_index in range(2, ds.RasterCount + 1):
314 if buf_type != ds.GetRasterBand(band_index).DataType:
315 buf_type = gdalconst.GDT_Float32
316
317 typecode = GDALTypeCodeToNumericTypeCode(buf_type)
318 if typecode is None:
319 buf_type = gdalconst.GDT_Float32
320 typecode = numpy.float32
321 else:
322 buf_type = NumericTypeCodeToGDALTypeCode(typecode)
323
324 if buf_type == gdalconst.GDT_Byte and ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
325 typecode = numpy.int8
326 buf_shape = (ds.RasterCount, buf_ysize, buf_xsize) if interleave else (buf_ysize, buf_xsize, ds.RasterCount)
327 buf_obj = numpy.empty(buf_shape, dtype=typecode)
328
329 else:
330 if len(buf_obj.shape) != 3:
331 raise ValueError('Array should have 3 dimensions')
332
333 shape_buf_xsize = buf_obj.shape[xdim]
334 shape_buf_ysize = buf_obj.shape[ydim]
335 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
336 raise ValueError('Specified buf_xsize not consistent with array shape')
337 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
338 raise ValueError('Specified buf_ysize not consistent with array shape')
339 if buf_obj.shape[banddim] != ds.RasterCount:
340 raise ValueError('Dimension %d of array should have size %d to store bands)' % (banddim, ds.RasterCount))
341
342 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type)
343 if not datatype:
344 raise ValueError("array does not have corresponding GDAL data type")
345 if buf_type is not None and buf_type != datatype:
346 raise ValueError("Specified buf_type not consistent with array type")
347 buf_type = datatype
348
349 if DatasetIONumPy(ds, 0, xoff, yoff, win_xsize, win_ysize,
350 buf_obj, buf_type, resample_alg, callback, callback_data, interleave) != 0:
351 _RaiseException()
352 return None
353
354 return buf_obj
355
356 -def BandReadAsArray(band, xoff=0, yoff=0, win_xsize=None, win_ysize=None,
357 buf_xsize=None, buf_ysize=None, buf_type=None, buf_obj=None,
358 resample_alg=gdal.GRIORA_NearestNeighbour,
359 callback=None, callback_data=None):
360 """Pure python implementation of reading a chunk of a GDAL file
361 into a numpy array. Used by the gdal.Band.ReadAsArray method."""
362
363 if win_xsize is None:
364 win_xsize = band.XSize
365 if win_ysize is None:
366 win_ysize = band.YSize
367
368 if buf_obj is None:
369 if buf_xsize is None:
370 buf_xsize = win_xsize
371 if buf_ysize is None:
372 buf_ysize = win_ysize
373 if buf_type is None:
374 buf_type = band.DataType
375
376 typecode = GDALTypeCodeToNumericTypeCode(buf_type)
377 if typecode is None:
378 buf_type = gdalconst.GDT_Float32
379 typecode = numpy.float32
380 else:
381 buf_type = NumericTypeCodeToGDALTypeCode(typecode)
382
383 if buf_type == gdalconst.GDT_Byte and band.GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
384 typecode = numpy.int8
385 buf_obj = numpy.empty([buf_ysize, buf_xsize], dtype=typecode)
386
387 else:
388 if len(buf_obj.shape) == 2:
389 shape_buf_xsize = buf_obj.shape[1]
390 shape_buf_ysize = buf_obj.shape[0]
391 else:
392 shape_buf_xsize = buf_obj.shape[2]
393 shape_buf_ysize = buf_obj.shape[1]
394 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
395 raise ValueError('Specified buf_xsize not consistent with array shape')
396 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
397 raise ValueError('Specified buf_ysize not consistent with array shape')
398
399 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type)
400 if not datatype:
401 raise ValueError("array does not have corresponding GDAL data type")
402 if buf_type is not None and buf_type != datatype:
403 raise ValueError("Specified buf_type not consistent with array type")
404 buf_type = datatype
405
406 if BandRasterIONumPy(band, 0, xoff, yoff, win_xsize, win_ysize,
407 buf_obj, buf_type, resample_alg, callback, callback_data) != 0:
408 _RaiseException()
409 return None
410
411 return buf_obj
412
416 """Pure python implementation of writing a chunk of a GDAL file
417 from a numpy array. Used by the gdal.Band.WriteArray method."""
418
419 if array is None or len(array.shape) != 2:
420 raise ValueError("expected array of dim 2")
421
422 xsize = array.shape[1]
423 ysize = array.shape[0]
424
425 if xsize + xoff > band.XSize or ysize + yoff > band.YSize:
426 raise ValueError("array larger than output file, or offset off edge")
427
428 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
429
430
431
432 if not datatype:
433 gdal.Debug('gdal_array', 'force array to float64')
434 array = array.astype(numpy.float64)
435 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
436
437 if not datatype:
438 raise ValueError("array does not have corresponding GDAL data type")
439
440 ret = BandRasterIONumPy(band, 1, xoff, yoff, xsize, ysize,
441 array, datatype, resample_alg, callback, callback_data)
442 if ret != 0:
443 _RaiseException()
444 return ret
445
472
473 -def MDArrayReadAsArray(mdarray,
474 array_start_idx = None,
475 count = None,
476 array_step = None,
477 buffer_datatype = None,
478 buf_obj = None):
496
497 -def MDArrayWriteArray(mdarray, array,
498 array_start_idx = None,
499 array_step = None):
525
527 """
528 Pure Python implementation of writing a chunk of the RAT
529 from a numpy array. Type of array is coerced to one of the types
530 (int, double, string) supported. Called from RasterAttributeTable.WriteArray
531 """
532 if array is None:
533 raise ValueError("Expected array of dim 1")
534
535
536 if not isinstance(array, numpy.ndarray):
537 array = numpy.array(array)
538
539 if array.ndim != 1:
540 raise ValueError("Expected array of dim 1")
541
542 if (start + array.size) > rat.GetRowCount():
543 raise ValueError("Array too big to fit into RAT from start position")
544
545 if numpy.issubdtype(array.dtype, numpy.integer):
546
547
548
549 array = array.astype(numpy.int32)
550 elif numpy.issubdtype(array.dtype, numpy.floating):
551
552 array = array.astype(numpy.double)
553 elif numpy.issubdtype(array.dtype, numpy.character):
554
555 array = array.astype(numpy.character)
556 else:
557 raise ValueError("Array not of a supported type (integer, double or string)")
558
559 ret = RATValuesIONumPyWrite(rat, field, start, array)
560 if ret != 0:
561 _RaiseException()
562 return ret
563
565 """
566 Pure Python implementation of reading a chunk of the RAT
567 into a numpy array. Called from RasterAttributeTable.ReadAsArray
568 """
569 if length is None:
570 length = rat.GetRowCount() - start
571
572 ret = RATValuesIONumPyRead(rat, field, start, length)
573 if ret is None:
574 _RaiseException()
575 return ret
576
578 """
579 Copy georeferencing information and metadata from one dataset to another.
580 src: input dataset
581 dst: output dataset - It can be a ROI -
582 xoff, yoff: dst's offset with respect to src in pixel/line.
583
584 Notes: Destination dataset must have update access. Certain formats
585 do not support creation of geotransforms and/or gcps.
586
587 """
588
589 dst.SetMetadata(src.GetMetadata())
590
591
592
593
594 gt = src.GetGeoTransform()
595 if gt != (0, 1, 0, 0, 0, 1):
596 dst.SetProjection(src.GetProjectionRef())
597
598 if xoff == 0 and yoff == 0:
599 dst.SetGeoTransform(gt)
600 else:
601 ngt = [gt[0], gt[1], gt[2], gt[3], gt[4], gt[5]]
602 ngt[0] = gt[0] + xoff*gt[1] + yoff*gt[2]
603 ngt[3] = gt[3] + xoff*gt[4] + yoff*gt[5]
604 dst.SetGeoTransform((ngt[0], ngt[1], ngt[2], ngt[3], ngt[4], ngt[5]))
605
606
607 elif src.GetGCPCount() > 0:
608
609 if (xoff == 0) and (yoff == 0):
610 dst.SetGCPs(src.GetGCPs(), src.GetGCPProjection())
611 else:
612 gcps = src.GetGCPs()
613
614 new_gcps = []
615 for gcp in gcps:
616 ngcp = gdal.GCP()
617 ngcp.GCPX = gcp.GCPX
618 ngcp.GCPY = gcp.GCPY
619 ngcp.GCPZ = gcp.GCPZ
620 ngcp.GCPPixel = gcp.GCPPixel - xoff
621 ngcp.GCPLine = gcp.GCPLine - yoff
622 ngcp.Info = gcp.Info
623 ngcp.Id = gcp.Id
624 new_gcps.append(ngcp)
625
626 try:
627 dst.SetGCPs(new_gcps, src.GetGCPProjection())
628 except:
629 print("Failed to set GCPs")
630 return
631
632 return
633
634
635