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 from sys import version_info as _swig_python_version_info
99 if _swig_python_version_info >= (2, 7, 0):
100 from . import gdal
101 else:
102 import gdal
103 del _swig_python_version_info
105 """Proxy of C++ CPLVirtualMemShadow class."""
106
107 __swig_setmethods__ = {}
108 __setattr__ = lambda self, name, value: _swig_setattr(self, VirtualMem, name, value)
109 __swig_getmethods__ = {}
110 __getattr__ = lambda self, name: _swig_getattr(self, VirtualMem, name)
111
113 raise AttributeError("No constructor defined")
114 __repr__ = _swig_repr
115 __swig_destroy__ = _gdal_array.delete_VirtualMem
116 __del__ = lambda self: None
117
119 """GetAddr(VirtualMem self)"""
120 return _gdal_array.VirtualMem_GetAddr(self)
121
122
123 - def Pin(self, start_offset=0, nsize=0, bWriteOp=0):
124 """
125 Pin(VirtualMem self, size_t start_offset=0, size_t nsize=0, int bWriteOp=0)
126 Pin(VirtualMem self, size_t start_offset=0, size_t nsize=0)
127 Pin(VirtualMem self, size_t start_offset=0)
128 Pin(VirtualMem self)
129 """
130 return _gdal_array.VirtualMem_Pin(self, start_offset, nsize, bWriteOp)
131
132 VirtualMem_swigregister = _gdal_array.VirtualMem_swigregister
133 VirtualMem_swigregister(VirtualMem)
134
135
139
141 """TermProgress_nocb(double dfProgress, char const * pszMessage=None, void * pData=None) -> int"""
142 return _gdal_array.TermProgress_nocb(dfProgress, pszMessage, pData)
143 TermProgress = _gdal_array.TermProgress
144
146 """OpenNumPyArray(PyArrayObject * psArray, bool binterleave) -> Dataset"""
147 return _gdal_array.OpenNumPyArray(psArray, binterleave)
148
152
154 """GetArrayFilename(PyArrayObject * psArray) -> retStringAndCPLFree *"""
155 return _gdal_array.GetArrayFilename(psArray)
156
157 -def BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None):
158 """BandRasterIONumPy(Band band, int bWrite, double xoff, double yoff, double xsize, double ysize, PyArrayObject * psArray, GDALDataType buf_type, GDALRIOResampleAlg resample_alg, GDALProgressFunc callback=0, void * callback_data=None) -> CPLErr"""
159 return _gdal_array.BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data)
160
161 -def DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None, binterleave=True, band_list=0):
162 """DatasetIONumPy(Dataset ds, int bWrite, double xoff, double yoff, double xsize, double ysize, PyArrayObject * psArray, GDALDataType buf_type, GDALRIOResampleAlg resample_alg, GDALProgressFunc callback=0, void * callback_data=None, bool binterleave=True, int band_list=0) -> CPLErr"""
163 return _gdal_array.DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data, binterleave, band_list)
164
165 -def MDArrayIONumPy(bWrite, mdarray, psArray, nDims1, nDims3, buffer_datatype):
166 """MDArrayIONumPy(bool bWrite, GDALMDArrayHS * mdarray, PyArrayObject * psArray, int nDims1, int nDims3, GDALExtendedDataTypeHS * buffer_datatype) -> CPLErr"""
167 return _gdal_array.MDArrayIONumPy(bWrite, mdarray, psArray, nDims1, nDims3, buffer_datatype)
168
170 """VirtualMemGetArray(VirtualMem virtualmem)"""
171 return _gdal_array.VirtualMemGetArray(virtualmem)
172
174 """RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart, PyArrayObject * psArray) -> CPLErr"""
175 return _gdal_array.RATValuesIONumPyWrite(poRAT, nField, nStart, psArray)
176
178 """RATValuesIONumPyRead(RasterAttributeTable poRAT, int nField, int nStart, int nLength) -> PyObject *"""
179 return _gdal_array.RATValuesIONumPyRead(poRAT, nField, nStart, nLength)
180
181 import numpy
182
183 from osgeo import gdalconst
184 from osgeo import gdal
185 gdal.AllRegister()
186
187 codes = {gdalconst.GDT_Byte: numpy.uint8,
188 gdalconst.GDT_UInt16: numpy.uint16,
189 gdalconst.GDT_Int16: numpy.int16,
190 gdalconst.GDT_UInt32: numpy.uint32,
191 gdalconst.GDT_Int32: numpy.int32,
192 gdalconst.GDT_Float32: numpy.float32,
193 gdalconst.GDT_Float64: numpy.float64,
194 gdalconst.GDT_CInt16: numpy.complex64,
195 gdalconst.GDT_CInt32: numpy.complex64,
196 gdalconst.GDT_CFloat32: numpy.complex64,
197 gdalconst.GDT_CFloat64: numpy.complex128}
198
199
200 -def OpenArray(array, prototype_ds=None, interleave='band'):
201
202 interleave = interleave.lower()
203 if interleave == 'band':
204 interleave = True
205 elif interleave == 'pixel':
206 interleave = False
207 else:
208 raise ValueError('Interleave should be band or pixel')
209
210 ds = OpenNumPyArray(array, interleave)
211
212 if ds is not None and prototype_ds is not None:
213 if type(prototype_ds).__name__ == 'str':
214 prototype_ds = gdal.Open(prototype_ds)
215 if prototype_ds is not None:
216 CopyDatasetInfo(prototype_ds, ds)
217
218 return ds
219
220
239
241 if not isinstance(numeric_type, (numpy.dtype, type)):
242 raise TypeError("Input must be a type")
243 return flip_code(numeric_type)
244
247
252
253 -def LoadFile(filename, xoff=0, yoff=0, xsize=None, ysize=None,
254 buf_xsize=None, buf_ysize=None, buf_type=None,
255 resample_alg=gdal.GRIORA_NearestNeighbour,
256 callback=None, callback_data=None, interleave='band',
257 band_list=None):
258 ds = gdal.Open(filename)
259 if ds is None:
260 raise ValueError("Can't open "+filename+"\n\n"+gdal.GetLastErrorMsg())
261
262 return DatasetReadAsArray(ds, xoff, yoff, xsize, ysize,
263 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type,
264 resample_alg=resample_alg,
265 callback=callback, callback_data=callback_data,
266 interleave=interleave,
267 band_list=band_list)
268
269 -def SaveArray(src_array, filename, format="GTiff", prototype=None, interleave='band'):
270 driver = gdal.GetDriverByName(format)
271 if driver is None:
272 raise ValueError("Can't find driver "+format)
273
274 return driver.CreateCopy(filename, OpenArray(src_array, prototype, interleave))
275
276
277 -def DatasetReadAsArray(ds, xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_obj=None,
278 buf_xsize=None, buf_ysize=None, buf_type=None,
279 resample_alg=gdal.GRIORA_NearestNeighbour,
280 callback=None, callback_data=None, interleave='band',
281 band_list=None):
282 """Pure python implementation of reading a chunk of a GDAL file
283 into a numpy array. Used by the gdal.Dataset.ReadAsArray method."""
284
285 if win_xsize is None:
286 win_xsize = ds.RasterXSize
287 if win_ysize is None:
288 win_ysize = ds.RasterYSize
289
290 if band_list is None:
291 band_list = list(range(1, ds.RasterCount + 1))
292
293 interleave = interleave.lower()
294 if interleave == 'band':
295 interleave = True
296 xdim = 2
297 ydim = 1
298 banddim = 0
299 elif interleave == 'pixel':
300 interleave = False
301 xdim = 1
302 ydim = 0
303 banddim = 2
304 else:
305 raise ValueError('Interleave should be band or pixel')
306
307 nbands = len(band_list)
308 if nbands == 0:
309 return None
310
311 if nbands == 1:
312 return BandReadAsArray(ds.GetRasterBand(band_list[0]), xoff, yoff, win_xsize, win_ysize,
313 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type,
314 buf_obj=buf_obj,
315 resample_alg=resample_alg,
316 callback=callback,
317 callback_data=callback_data)
318
319 if buf_obj is None:
320 if buf_xsize is None:
321 buf_xsize = win_xsize
322 if buf_ysize is None:
323 buf_ysize = win_ysize
324 if buf_type is None:
325 buf_type = ds.GetRasterBand(band_list[0]).DataType
326 for idx in range(1, nbands):
327 band_index = band_list[idx]
328 if buf_type != ds.GetRasterBand(band_index).DataType:
329 buf_type = gdalconst.GDT_Float32
330
331 typecode = GDALTypeCodeToNumericTypeCode(buf_type)
332 if typecode is None:
333 buf_type = gdalconst.GDT_Float32
334 typecode = numpy.float32
335 else:
336 buf_type = NumericTypeCodeToGDALTypeCode(typecode)
337
338 if buf_type == gdalconst.GDT_Byte and ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
339 typecode = numpy.int8
340 buf_shape = (nbands, buf_ysize, buf_xsize) if interleave else (buf_ysize, buf_xsize, nbands)
341 buf_obj = numpy.empty(buf_shape, dtype=typecode)
342
343 else:
344 if len(buf_obj.shape) != 3:
345 raise ValueError('Array should have 3 dimensions')
346
347 shape_buf_xsize = buf_obj.shape[xdim]
348 shape_buf_ysize = buf_obj.shape[ydim]
349 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
350 raise ValueError('Specified buf_xsize not consistent with array shape')
351 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
352 raise ValueError('Specified buf_ysize not consistent with array shape')
353 if buf_obj.shape[banddim] != nbands:
354 raise ValueError('Dimension %d of array should have size %d to store bands)' % (banddim, nbands))
355
356 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type)
357 if not datatype:
358 raise ValueError("array does not have corresponding GDAL data type")
359 if buf_type is not None and buf_type != datatype:
360 raise ValueError("Specified buf_type not consistent with array type")
361 buf_type = datatype
362
363 if DatasetIONumPy(ds, 0, xoff, yoff, win_xsize, win_ysize,
364 buf_obj, buf_type, resample_alg, callback, callback_data,
365 interleave, band_list) != 0:
366 _RaiseException()
367 return None
368
369 return buf_obj
370
371
377 """Pure python implementation of writing a chunk of a GDAL file
378 from a numpy array. Used by the gdal.Dataset.WriteArray method."""
379
380 if band_list is None:
381 band_list = list(range(1, ds.RasterCount + 1))
382
383 interleave = interleave.lower()
384 if interleave == 'band':
385 interleave = True
386 xdim = 2
387 ydim = 1
388 banddim = 0
389 elif interleave == 'pixel':
390 interleave = False
391 xdim = 1
392 ydim = 0
393 banddim = 2
394 else:
395 raise ValueError('Interleave should be band or pixel')
396
397 if len(band_list) == 1:
398 if array is None or (len(array.shape) != 2 and len(array.shape) != 3):
399 raise ValueError("expected array of dim 2 or 3")
400 if len(array.shape) == 3:
401 if array.shape[banddim] != 1:
402 raise ValueError("expected size of dimension %d should be 1" % banddim)
403 array = array[banddim]
404
405 return BandWriteArray(ds.GetRasterBand(band_list[0]),
406 array,
407 xoff=xoff, yoff=yoff, resample_alg=resample_alg,
408 callback=callback, callback_data=callback_data)
409
410 if array is None or len(array.shape) != 3:
411 raise ValueError("expected array of dim 3")
412
413 xsize = array.shape[xdim]
414 ysize = array.shape[ydim]
415
416 if xsize + xoff > ds.RasterXSize or ysize + yoff > ds.RasterYSize:
417 raise ValueError("array larger than output file, or offset off edge")
418 if array.shape[banddim] != len(band_list):
419 raise ValueError('Dimension %d of array should have size %d to store bands)' % (banddim, len(band_list)))
420
421 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
422
423
424
425 if not datatype:
426 gdal.Debug('gdal_array', 'force array to float64')
427 array = array.astype(numpy.float64)
428 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
429
430 if not datatype:
431 raise ValueError("array does not have corresponding GDAL data type")
432
433 ret = DatasetIONumPy(ds, 1, xoff, yoff, xsize, ysize,
434 array, datatype, resample_alg, callback, callback_data,
435 interleave, band_list)
436 if ret != 0:
437 _RaiseException()
438 return ret
439
440
441 -def BandReadAsArray(band, xoff=0, yoff=0, win_xsize=None, win_ysize=None,
442 buf_xsize=None, buf_ysize=None, buf_type=None, buf_obj=None,
443 resample_alg=gdal.GRIORA_NearestNeighbour,
444 callback=None, callback_data=None):
445 """Pure python implementation of reading a chunk of a GDAL file
446 into a numpy array. Used by the gdal.Band.ReadAsArray method."""
447
448 if win_xsize is None:
449 win_xsize = band.XSize
450 if win_ysize is None:
451 win_ysize = band.YSize
452
453 if buf_obj is None:
454 if buf_xsize is None:
455 buf_xsize = win_xsize
456 if buf_ysize is None:
457 buf_ysize = win_ysize
458 if buf_type is None:
459 buf_type = band.DataType
460
461 typecode = GDALTypeCodeToNumericTypeCode(buf_type)
462 if typecode is None:
463 buf_type = gdalconst.GDT_Float32
464 typecode = numpy.float32
465 else:
466 buf_type = NumericTypeCodeToGDALTypeCode(typecode)
467
468 if buf_type == gdalconst.GDT_Byte and band.GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
469 typecode = numpy.int8
470 buf_obj = numpy.empty([buf_ysize, buf_xsize], dtype=typecode)
471
472 else:
473 if len(buf_obj.shape) not in (2, 3):
474 raise ValueError("expected array of dimension 2 or 3")
475
476 if len(buf_obj.shape) == 2:
477 shape_buf_xsize = buf_obj.shape[1]
478 shape_buf_ysize = buf_obj.shape[0]
479 else:
480 if buf_obj.shape[0] != 1:
481 raise ValueError("expected size of first dimension should be 0")
482 shape_buf_xsize = buf_obj.shape[2]
483 shape_buf_ysize = buf_obj.shape[1]
484 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
485 raise ValueError('Specified buf_xsize not consistent with array shape')
486 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
487 raise ValueError('Specified buf_ysize not consistent with array shape')
488
489 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type)
490 if not datatype:
491 raise ValueError("array does not have corresponding GDAL data type")
492 if buf_type is not None and buf_type != datatype:
493 raise ValueError("Specified buf_type not consistent with array type")
494 buf_type = datatype
495
496 if BandRasterIONumPy(band, 0, xoff, yoff, win_xsize, win_ysize,
497 buf_obj, buf_type, resample_alg, callback, callback_data) != 0:
498 _RaiseException()
499 return None
500
501 return buf_obj
502
506 """Pure python implementation of writing a chunk of a GDAL file
507 from a numpy array. Used by the gdal.Band.WriteArray method."""
508
509 if array is None or len(array.shape) != 2:
510 raise ValueError("expected array of dim 2")
511
512 xsize = array.shape[1]
513 ysize = array.shape[0]
514
515 if xsize + xoff > band.XSize or ysize + yoff > band.YSize:
516 raise ValueError("array larger than output file, or offset off edge")
517
518 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
519
520
521
522 if not datatype:
523 gdal.Debug('gdal_array', 'force array to float64')
524 array = array.astype(numpy.float64)
525 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
526
527 if not datatype:
528 raise ValueError("array does not have corresponding GDAL data type")
529
530 ret = BandRasterIONumPy(band, 1, xoff, yoff, xsize, ysize,
531 array, datatype, resample_alg, callback, callback_data)
532 if ret != 0:
533 _RaiseException()
534 return ret
535
568
572
573 -def MDArrayReadAsArray(mdarray,
574 array_start_idx = None,
575 count = None,
576 array_step = None,
577 buffer_datatype = None,
578 buf_obj = None):
602
603 -def MDArrayWriteArray(mdarray, array,
604 array_start_idx = None,
605 array_step = None):
632
634 """
635 Pure Python implementation of writing a chunk of the RAT
636 from a numpy array. Type of array is coerced to one of the types
637 (int, double, string) supported. Called from RasterAttributeTable.WriteArray
638 """
639 if array is None:
640 raise ValueError("Expected array of dim 1")
641
642
643 if not isinstance(array, numpy.ndarray):
644 array = numpy.array(array)
645
646 if array.ndim != 1:
647 raise ValueError("Expected array of dim 1")
648
649 if (start + array.size) > rat.GetRowCount():
650 raise ValueError("Array too big to fit into RAT from start position")
651
652 if numpy.issubdtype(array.dtype, numpy.integer):
653
654
655
656 array = array.astype(numpy.int32)
657 elif numpy.issubdtype(array.dtype, numpy.floating):
658
659 array = array.astype(numpy.double)
660 elif numpy.issubdtype(array.dtype, numpy.character):
661
662 array = array.astype(bytes)
663 else:
664 raise ValueError("Array not of a supported type (integer, double or string)")
665
666 ret = RATValuesIONumPyWrite(rat, field, start, array)
667 if ret != 0:
668 _RaiseException()
669 return ret
670
672 """
673 Pure Python implementation of reading a chunk of the RAT
674 into a numpy array. Called from RasterAttributeTable.ReadAsArray
675 """
676 if length is None:
677 length = rat.GetRowCount() - start
678
679 ret = RATValuesIONumPyRead(rat, field, start, length)
680 if ret is None:
681 _RaiseException()
682 return ret
683
685 """
686 Copy georeferencing information and metadata from one dataset to another.
687 src: input dataset
688 dst: output dataset - It can be a ROI -
689 xoff, yoff: dst's offset with respect to src in pixel/line.
690
691 Notes: Destination dataset must have update access. Certain formats
692 do not support creation of geotransforms and/or gcps.
693
694 """
695
696 dst.SetMetadata(src.GetMetadata())
697
698
699
700
701 gt = src.GetGeoTransform()
702 if gt != (0, 1, 0, 0, 0, 1):
703 dst.SetProjection(src.GetProjectionRef())
704
705 if xoff == 0 and yoff == 0:
706 dst.SetGeoTransform(gt)
707 else:
708 ngt = [gt[0], gt[1], gt[2], gt[3], gt[4], gt[5]]
709 ngt[0] = gt[0] + xoff*gt[1] + yoff*gt[2]
710 ngt[3] = gt[3] + xoff*gt[4] + yoff*gt[5]
711 dst.SetGeoTransform((ngt[0], ngt[1], ngt[2], ngt[3], ngt[4], ngt[5]))
712
713
714 elif src.GetGCPCount() > 0:
715
716 if (xoff == 0) and (yoff == 0):
717 dst.SetGCPs(src.GetGCPs(), src.GetGCPProjection())
718 else:
719 gcps = src.GetGCPs()
720
721 new_gcps = []
722 for gcp in gcps:
723 ngcp = gdal.GCP()
724 ngcp.GCPX = gcp.GCPX
725 ngcp.GCPY = gcp.GCPY
726 ngcp.GCPZ = gcp.GCPZ
727 ngcp.GCPPixel = gcp.GCPPixel - xoff
728 ngcp.GCPLine = gcp.GCPLine - yoff
729 ngcp.Info = gcp.Info
730 ngcp.Id = gcp.Id
731 new_gcps.append(ngcp)
732
733 try:
734 dst.SetGCPs(new_gcps, src.GetGCPProjection())
735 except:
736 print("Failed to set GCPs")
737 return
738
739 return
740
741
742