1
2
3
4
5
6
7
8 from sys import version_info
9 if version_info >= (2,6,0):
11 from os.path import dirname
12 import imp
13 fp = None
14 try:
15 fp, pathname, description = imp.find_module('_gdal_array', [dirname(__file__)])
16 except ImportError:
17 import _gdal_array
18 return _gdal_array
19 if fp is not None:
20 try:
21 _mod = imp.load_module('_gdal_array', fp, pathname, description)
22 finally:
23 fp.close()
24 return _mod
25 _gdal_array = swig_import_helper()
26 del swig_import_helper
27 else:
28 import _gdal_array
29 del version_info
30 try:
31 _swig_property = property
32 except NameError:
33 pass
35 if (name == "thisown"): return self.this.own(value)
36 if (name == "this"):
37 if type(value).__name__ == 'SwigPyObject':
38 self.__dict__[name] = value
39 return
40 method = class_type.__swig_setmethods__.get(name,None)
41 if method: return method(self,value)
42 if (not static) or hasattr(self,name):
43 self.__dict__[name] = value
44 else:
45 raise AttributeError("You cannot add attributes to %s" % self)
46
49
51 if (name == "thisown"): return self.this.own()
52 method = class_type.__swig_getmethods__.get(name,None)
53 if method: return method(self)
54 raise AttributeError(name)
55
57 try: strthis = "proxy of " + self.this.__repr__()
58 except: strthis = ""
59 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
60
61 try:
62 _object = object
63 _newclass = 1
64 except AttributeError:
66 _newclass = 0
67
68
69 import gdal
71 """Proxy of C++ CPLVirtualMemShadow class"""
72 __swig_setmethods__ = {}
73 __setattr__ = lambda self, name, value: _swig_setattr(self, VirtualMem, name, value)
74 __swig_getmethods__ = {}
75 __getattr__ = lambda self, name: _swig_getattr(self, VirtualMem, name)
76 - def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
77 __repr__ = _swig_repr
78 __swig_destroy__ = _gdal_array.delete_VirtualMem
79 __del__ = lambda self : None;
81 """GetAddr(self)"""
82 return _gdal_array.VirtualMem_GetAddr(self)
83
84 - def Pin(self, start_offset = 0, nsize = 0, bWriteOp = 0):
85 """
86 Pin(self, size_t start_offset = 0, size_t nsize = 0, int bWriteOp = 0)
87 Pin(self, size_t start_offset = 0, size_t nsize = 0)
88 Pin(self, size_t start_offset = 0)
89 Pin(self)
90 """
91 return _gdal_array.VirtualMem_Pin(self, start_offset, nsize, bWriteOp)
92
93 VirtualMem_swigregister = _gdal_array.VirtualMem_swigregister
94 VirtualMem_swigregister(VirtualMem)
95
96
98 """TermProgress_nocb(double dfProgress, char pszMessage = None, void pData = None) -> int"""
99 return _gdal_array.TermProgress_nocb(*args, **kwargs)
100 TermProgress = _gdal_array.TermProgress
101
103 """OpenNumPyArray(PyArrayObject psArray) -> Dataset"""
104 return _gdal_array.OpenNumPyArray(*args)
105 OpenNumPyArray = _gdal_array.OpenNumPyArray
106
108 """GetArrayFilename(PyArrayObject psArray) -> retStringAndCPLFree"""
109 return _gdal_array.GetArrayFilename(*args)
110 GetArrayFilename = _gdal_array.GetArrayFilename
111
113 """
114 BandRasterIONumPy(Band band, int bWrite, double xoff, double yoff, double xsize,
115 double ysize, PyArrayObject psArray,
116 int buf_type, GDALRIOResampleAlg resample_alg,
117 GDALProgressFunc callback = None, void callback_data = None) -> CPLErr
118 """
119 return _gdal_array.BandRasterIONumPy(*args, **kwargs)
120 BandRasterIONumPy = _gdal_array.BandRasterIONumPy
121
123 """
124 DatasetIONumPy(Dataset ds, int bWrite, int xoff, int yoff, int xsize,
125 int ysize, PyArrayObject psArray, int buf_type,
126 GDALRIOResampleAlg resample_alg, GDALProgressFunc callback = None,
127 void callback_data = None) -> CPLErr
128 """
129 return _gdal_array.DatasetIONumPy(*args, **kwargs)
130 DatasetIONumPy = _gdal_array.DatasetIONumPy
131
133 """VirtualMemGetArray(VirtualMem virtualmem)"""
134 return _gdal_array.VirtualMemGetArray(*args)
135 VirtualMemGetArray = _gdal_array.VirtualMemGetArray
136
138 """
139 RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart,
140 PyArrayObject psArray) -> CPLErr
141 """
142 return _gdal_array.RATValuesIONumPyWrite(*args, **kwargs)
143 RATValuesIONumPyWrite = _gdal_array.RATValuesIONumPyWrite
144
146 """
147 RATValuesIONumPyRead(RasterAttributeTable poRAT, int nField, int nStart,
148 int nLength) -> PyObject
149 """
150 return _gdal_array.RATValuesIONumPyRead(*args, **kwargs)
151 RATValuesIONumPyRead = _gdal_array.RATValuesIONumPyRead
152 import numpy
153 import _gdal_array
154
155 import gdalconst
156 import gdal
157 gdal.AllRegister()
158
159 codes = { gdalconst.GDT_Byte : numpy.uint8,
160 gdalconst.GDT_UInt16 : numpy.uint16,
161 gdalconst.GDT_Int16 : numpy.int16,
162 gdalconst.GDT_UInt32 : numpy.uint32,
163 gdalconst.GDT_Int32 : numpy.int32,
164 gdalconst.GDT_Float32 : numpy.float32,
165 gdalconst.GDT_Float64 : numpy.float64,
166 gdalconst.GDT_CInt16 : numpy.complex64,
167 gdalconst.GDT_CInt32 : numpy.complex64,
168 gdalconst.GDT_CFloat32 : numpy.complex64,
169 gdalconst.GDT_CFloat64 : numpy.complex128
170 }
171
173
174 ds = OpenNumPyArray( array )
175
176 if ds is not None and prototype_ds is not None:
177 if type(prototype_ds).__name__ == 'str':
178 prototype_ds = gdal.Open( prototype_ds )
179 if prototype_ds is not None:
180 CopyDatasetInfo( prototype_ds, ds )
181
182 return ds
183
184
186 if isinstance(code, (numpy.dtype,type)):
187
188
189 if code == numpy.int8:
190 return gdalconst.GDT_Byte
191 if code == numpy.complex64:
192 return gdalconst.GDT_CFloat32
193
194 for key, value in codes.items():
195 if value == code:
196 return key
197 return None
198 else:
199 try:
200 return codes[code]
201 except KeyError:
202 return None
203
205 if not isinstance(numeric_type, (numpy.dtype,type)):
206 raise TypeError("Input must be a type")
207 return flip_code(numeric_type)
208
211
212 -def LoadFile( filename, xoff=0, yoff=0, xsize=None, ysize=None,
213 buf_xsize=None, buf_ysize=None, buf_type=None,
214 resample_alg = gdal.GRIORA_NearestNeighbour,
215 callback=None, callback_data=None ):
216 ds = gdal.Open( filename )
217 if ds is None:
218 raise ValueError("Can't open "+filename+"\n\n"+gdal.GetLastErrorMsg())
219
220 return DatasetReadAsArray( ds, xoff, yoff, xsize, ysize,
221 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type,
222 resample_alg=resample_alg,
223 callback = callback, callback_data = callback_data )
224
225 -def SaveArray( src_array, filename, format = "GTiff", prototype = None ):
226 driver = gdal.GetDriverByName( format )
227 if driver is None:
228 raise ValueError("Can't find driver "+format)
229
230 return driver.CreateCopy( filename, OpenArray(src_array,prototype) )
231
232
233 -def DatasetReadAsArray( ds, xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_obj=None,
234 buf_xsize = None, buf_ysize = None, buf_type = None,
235 resample_alg = gdal.GRIORA_NearestNeighbour,
236 callback=None, callback_data=None ):
237 """Pure python implementation of reading a chunk of a GDAL file
238 into a numpy array. Used by the gdal.Dataset.ReadAsArray method."""
239
240 if win_xsize is None:
241 win_xsize = ds.RasterXSize
242 if win_ysize is None:
243 win_ysize = ds.RasterYSize
244
245 if ds.RasterCount == 0:
246 return None
247
248 if ds.RasterCount == 1:
249 return BandReadAsArray( ds.GetRasterBand(1), xoff, yoff, win_xsize, win_ysize,
250 buf_xsize = buf_xsize, buf_ysize = buf_ysize, buf_type = buf_type,
251 buf_obj = buf_obj,
252 resample_alg = resample_alg,
253 callback = callback,
254 callback_data = callback_data )
255
256 if buf_obj is None:
257 if buf_xsize is None:
258 buf_xsize = win_xsize
259 if buf_ysize is None:
260 buf_ysize = win_ysize
261 if buf_type is None:
262 buf_type = ds.GetRasterBand(1).DataType
263 for band_index in range(2,ds.RasterCount+1):
264 if buf_type != ds.GetRasterBand(band_index).DataType:
265 buf_type = gdalconst.GDT_Float32
266
267 typecode = GDALTypeCodeToNumericTypeCode( buf_type )
268 if typecode == None:
269 buf_type = gdalconst.GDT_Float32
270 typecode = numpy.float32
271 if buf_type == gdalconst.GDT_Byte and ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
272 typecode = numpy.int8
273 buf_obj = numpy.empty([ds.RasterCount, buf_ysize,buf_xsize], dtype = typecode)
274
275 else:
276 if len(buf_obj.shape) != 3:
277 raise ValueError('Array should have 3 dimensions')
278
279 shape_buf_xsize = buf_obj.shape[2]
280 shape_buf_ysize = buf_obj.shape[1]
281 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
282 raise ValueError('Specified buf_xsize not consistent with array shape')
283 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
284 raise ValueError('Specified buf_ysize not consistent with array shape')
285 if buf_obj.shape[0] != ds.RasterCount:
286 raise ValueError('Array should have space for %d bands' % ds.RasterCount)
287
288 datatype = NumericTypeCodeToGDALTypeCode( buf_obj.dtype.type )
289 if not datatype:
290 raise ValueError("array does not have corresponding GDAL data type")
291 if buf_type is not None and buf_type != datatype:
292 raise ValueError("Specified buf_type not consistent with array type")
293 buf_type = datatype
294
295 if DatasetIONumPy( ds, 0, xoff, yoff, win_xsize, win_ysize,
296 buf_obj, buf_type, resample_alg, callback, callback_data ) != 0:
297 return None
298
299 return buf_obj
300
301 -def BandReadAsArray( band, xoff = 0, yoff = 0, win_xsize = None, win_ysize = None,
302 buf_xsize=None, buf_ysize=None, buf_type=None, buf_obj=None,
303 resample_alg = gdal.GRIORA_NearestNeighbour,
304 callback=None, callback_data=None):
305 """Pure python implementation of reading a chunk of a GDAL file
306 into a numpy array. Used by the gdal.Band.ReadAsArray method."""
307
308 if win_xsize is None:
309 win_xsize = band.XSize
310 if win_ysize is None:
311 win_ysize = band.YSize
312
313 if buf_obj is None:
314 if buf_xsize is None:
315 buf_xsize = win_xsize
316 if buf_ysize is None:
317 buf_ysize = win_ysize
318 if buf_type is None:
319 buf_type = band.DataType
320
321 typecode = GDALTypeCodeToNumericTypeCode( buf_type )
322 if typecode == None:
323 buf_type = gdalconst.GDT_Float32
324 typecode = numpy.float32
325 else:
326 buf_type = NumericTypeCodeToGDALTypeCode( typecode )
327
328 if buf_type == gdalconst.GDT_Byte and band.GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE':
329 typecode = numpy.int8
330 buf_obj = numpy.empty([buf_ysize,buf_xsize], dtype = typecode)
331
332 else:
333 if len(buf_obj.shape) == 2:
334 shape_buf_xsize = buf_obj.shape[1]
335 shape_buf_ysize = buf_obj.shape[0]
336 else:
337 shape_buf_xsize = buf_obj.shape[2]
338 shape_buf_ysize = buf_obj.shape[1]
339 if buf_xsize is not None and buf_xsize != shape_buf_xsize:
340 raise ValueError('Specified buf_xsize not consistent with array shape')
341 if buf_ysize is not None and buf_ysize != shape_buf_ysize:
342 raise ValueError('Specified buf_ysize not consistent with array shape')
343
344 datatype = NumericTypeCodeToGDALTypeCode( buf_obj.dtype.type )
345 if not datatype:
346 raise ValueError("array does not have corresponding GDAL data type")
347 if buf_type is not None and buf_type != datatype:
348 raise ValueError("Specified buf_type not consistent with array type")
349 buf_type = datatype
350
351 if BandRasterIONumPy( band, 0, xoff, yoff, win_xsize, win_ysize,
352 buf_obj, buf_type, resample_alg, callback, callback_data ) != 0:
353 return None
354
355 return buf_obj
356
360 """Pure python implementation of writing a chunk of a GDAL file
361 from a numpy array. Used by the gdal.Band.WriteArray method."""
362
363 if array is None or len(array.shape) != 2:
364 raise ValueError("expected array of dim 2")
365
366 xsize = array.shape[1]
367 ysize = array.shape[0]
368
369 if xsize + xoff > band.XSize or ysize + yoff > band.YSize:
370 raise ValueError("array larger than output file, or offset off edge")
371
372 datatype = NumericTypeCodeToGDALTypeCode( array.dtype.type )
373
374
375
376 if not datatype:
377 gdal.Debug( 'gdal_array', 'force array to float64' )
378 array = array.astype( numpy.float64 )
379 datatype = NumericTypeCodeToGDALTypeCode( array.dtype.type )
380
381 if not datatype:
382 raise ValueError("array does not have corresponding GDAL data type")
383
384 return BandRasterIONumPy( band, 1, xoff, yoff, xsize, ysize,
385 array, datatype, resample_alg, callback, callback_data )
386
388 """
389 Pure Python implementation of writing a chunk of the RAT
390 from a numpy array. Type of array is coerced to one of the types
391 (int, double, string) supported. Called from RasterAttributeTable.WriteArray
392 """
393 if array is None:
394 raise ValueError("Expected array of dim 1")
395
396
397 if not isinstance(array, numpy.ndarray):
398 array = numpy.array(array)
399
400 if array.ndim != 1:
401 raise ValueError("Expected array of dim 1")
402
403 if (start + array.size) > rat.GetRowCount():
404 raise ValueError("Array too big to fit into RAT from start position")
405
406 if numpy.issubdtype(array.dtype, numpy.integer):
407
408
409
410 array = array.astype(numpy.int32)
411 elif numpy.issubdtype(array.dtype, numpy.floating):
412
413 array = array.astype(numpy.double)
414 elif numpy.issubdtype(array.dtype, numpy.character):
415
416 array = array.astype(numpy.character)
417 else:
418 raise ValueError("Array not of a supported type (integer, double or string)")
419
420 return RATValuesIONumPyWrite(rat, field, start, array)
421
423 """
424 Pure Python implementation of reading a chunk of the RAT
425 into a numpy array. Called from RasterAttributeTable.ReadAsArray
426 """
427 if length is None:
428 length = rat.GetRowCount() - start
429
430 return RATValuesIONumPyRead(rat, field, start, length)
431
433 """
434 Copy georeferencing information and metadata from one dataset to another.
435 src: input dataset
436 dst: output dataset - It can be a ROI -
437 xoff, yoff: dst's offset with respect to src in pixel/line.
438
439 Notes: Destination dataset must have update access. Certain formats
440 do not support creation of geotransforms and/or gcps.
441
442 """
443
444 dst.SetMetadata( src.GetMetadata() )
445
446
447
448
449 gt = src.GetGeoTransform()
450 if gt != (0,1,0,0,0,1):
451 dst.SetProjection( src.GetProjectionRef() )
452
453 if (xoff == 0) and (yoff == 0):
454 dst.SetGeoTransform( gt )
455 else:
456 ngt = [gt[0],gt[1],gt[2],gt[3],gt[4],gt[5]]
457 ngt[0] = gt[0] + xoff*gt[1] + yoff*gt[2];
458 ngt[3] = gt[3] + xoff*gt[4] + yoff*gt[5];
459 dst.SetGeoTransform( ( ngt[0], ngt[1], ngt[2], ngt[3], ngt[4], ngt[5] ) )
460
461
462 elif src.GetGCPCount() > 0:
463
464 if (xoff == 0) and (yoff == 0):
465 dst.SetGCPs( src.GetGCPs(), src.GetGCPProjection() )
466 else:
467 gcps = src.GetGCPs()
468
469 new_gcps = []
470 for gcp in gcps:
471 ngcp = gdal.GCP()
472 ngcp.GCPX = gcp.GCPX
473 ngcp.GCPY = gcp.GCPY
474 ngcp.GCPZ = gcp.GCPZ
475 ngcp.GCPPixel = gcp.GCPPixel - xoff
476 ngcp.GCPLine = gcp.GCPLine - yoff
477 ngcp.Info = gcp.Info
478 ngcp.Id = gcp.Id
479 new_gcps.append(ngcp)
480
481 try:
482 dst.SetGCPs( new_gcps , src.GetGCPProjection() )
483 except:
484 print ("Failed to set GCPs")
485 return
486
487 return
488