Package osgeo :: Module gdal_array
[hide private]
[frames] | no frames]

Source Code for Module osgeo.gdal_array

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