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 osgeo.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 _StoreLastException():
127 """_StoreLastException()""" 128 return _gdal_array._StoreLastException()
129
130 -def TermProgress_nocb(dfProgress, pszMessage=None, pData=None):
131 """TermProgress_nocb(double dfProgress, char const * pszMessage=None, void * pData=None) -> int""" 132 return _gdal_array.TermProgress_nocb(dfProgress, pszMessage, pData)
133 134 _gdal_array.TermProgress_swigconstant(_gdal_array) 135 TermProgress = _gdal_array.TermProgress 136
137 -def OpenNumPyArray(psArray, binterleave):
138 """OpenNumPyArray(PyArrayObject * psArray, bool binterleave) -> Dataset""" 139 return _gdal_array.OpenNumPyArray(psArray, binterleave)
140
141 -def GetArrayFilename(psArray):
142 """GetArrayFilename(PyArrayObject * psArray) -> retStringAndCPLFree *""" 143 return _gdal_array.GetArrayFilename(psArray)
144
145 -def BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None):
146 """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""" 147 return _gdal_array.BandRasterIONumPy(band, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data)
148
149 -def DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback=0, callback_data=None, binterleave=True):
150 """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, bool binterleave=True) -> CPLErr""" 151 return _gdal_array.DatasetIONumPy(ds, bWrite, xoff, yoff, xsize, ysize, psArray, buf_type, resample_alg, callback, callback_data, binterleave)
152
153 -def VirtualMemGetArray(virtualmem):
154 """VirtualMemGetArray(VirtualMem virtualmem)""" 155 return _gdal_array.VirtualMemGetArray(virtualmem)
156
157 -def RATValuesIONumPyWrite(poRAT, nField, nStart, psArray):
158 """RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart, PyArrayObject * psArray) -> CPLErr""" 159 return _gdal_array.RATValuesIONumPyWrite(poRAT, nField, nStart, psArray)
160
161 -def RATValuesIONumPyRead(poRAT, nField, nStart, nLength):
162 """RATValuesIONumPyRead(RasterAttributeTable poRAT, int nField, int nStart, int nLength) -> PyObject *""" 163 return _gdal_array.RATValuesIONumPyRead(poRAT, nField, nStart, nLength)
164 165 import numpy 166 167 from osgeo import gdalconst 168 from osgeo import gdal 169 gdal.AllRegister() 170 171 codes = {gdalconst.GDT_Byte: numpy.uint8, 172 gdalconst.GDT_UInt16: numpy.uint16, 173 gdalconst.GDT_Int16: numpy.int16, 174 gdalconst.GDT_UInt32: numpy.uint32, 175 gdalconst.GDT_Int32: numpy.int32, 176 gdalconst.GDT_Float32: numpy.float32, 177 gdalconst.GDT_Float64: numpy.float64, 178 gdalconst.GDT_CInt16: numpy.complex64, 179 gdalconst.GDT_CInt32: numpy.complex64, 180 gdalconst.GDT_CFloat32: numpy.complex64, 181 gdalconst.GDT_CFloat64: numpy.complex128} 182 183
184 -def OpenArray(array, prototype_ds=None, interleave='band'):
185 186 interleave = interleave.lower() 187 if interleave == 'band': 188 interleave = True 189 elif interleave == 'pixel': 190 interleave = False 191 else: 192 raise ValueError('Interleave should be band or pixel') 193 194 ds = OpenNumPyArray(array, interleave) 195 196 if ds is not None and prototype_ds is not None: 197 if type(prototype_ds).__name__ == 'str': 198 prototype_ds = gdal.Open(prototype_ds) 199 if prototype_ds is not None: 200 CopyDatasetInfo(prototype_ds, ds) 201 202 return ds
203 204
205 -def flip_code(code):
206 if isinstance(code, (numpy.dtype, type)): 207 # since several things map to complex64 we must carefully select 208 # the opposite that is an exact match (ticket 1518) 209 if code == numpy.int8: 210 return gdalconst.GDT_Byte 211 if code == numpy.complex64: 212 return gdalconst.GDT_CFloat32 213 214 for key, value in codes.items(): 215 if value == code: 216 return key 217 return None 218 else: 219 try: 220 return codes[code] 221 except KeyError: 222 return None
223
224 -def NumericTypeCodeToGDALTypeCode(numeric_type):
225 if not isinstance(numeric_type, (numpy.dtype, type)): 226 raise TypeError("Input must be a type") 227 return flip_code(numeric_type)
228
229 -def GDALTypeCodeToNumericTypeCode(gdal_code):
230 return flip_code(gdal_code)
231
232 -def _RaiseException():
233 if gdal.GetUseExceptions(): 234 _StoreLastException() 235 raise RuntimeError(gdal.GetLastErrorMsg())
236
237 -def LoadFile(filename, xoff=0, yoff=0, xsize=None, ysize=None, 238 buf_xsize=None, buf_ysize=None, buf_type=None, 239 resample_alg=gdal.GRIORA_NearestNeighbour, 240 callback=None, callback_data=None, interleave='band'):
241 ds = gdal.Open(filename) 242 if ds is None: 243 raise ValueError("Can't open "+filename+"\n\n"+gdal.GetLastErrorMsg()) 244 245 return DatasetReadAsArray(ds, xoff, yoff, xsize, ysize, 246 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type, 247 resample_alg=resample_alg, 248 callback=callback, callback_data=callback_data, interleave=interleave)
249
250 -def SaveArray(src_array, filename, format="GTiff", prototype=None, interleave='band'):
251 driver = gdal.GetDriverByName(format) 252 if driver is None: 253 raise ValueError("Can't find driver "+format) 254 255 return driver.CreateCopy(filename, OpenArray(src_array, prototype, interleave))
256 257
258 -def DatasetReadAsArray(ds, xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_obj=None, 259 buf_xsize=None, buf_ysize=None, buf_type=None, 260 resample_alg=gdal.GRIORA_NearestNeighbour, 261 callback=None, callback_data=None, interleave='band'):
262 """Pure python implementation of reading a chunk of a GDAL file 263 into a numpy array. Used by the gdal.Dataset.ReadAsArray method.""" 264 265 if win_xsize is None: 266 win_xsize = ds.RasterXSize 267 if win_ysize is None: 268 win_ysize = ds.RasterYSize 269 270 interleave = interleave.lower() 271 if interleave == 'band': 272 interleave = True 273 xdim = 2 274 ydim = 1 275 elif interleave == 'pixel': 276 interleave = False 277 xdim = 1 278 ydim = 0 279 else: 280 raise ValueError('Interleave should be band or pixel') 281 282 if ds.RasterCount == 0: 283 return None 284 285 if ds.RasterCount == 1: 286 return BandReadAsArray(ds.GetRasterBand(1), xoff, yoff, win_xsize, win_ysize, 287 buf_xsize=buf_xsize, buf_ysize=buf_ysize, buf_type=buf_type, 288 buf_obj=buf_obj, 289 resample_alg=resample_alg, 290 callback=callback, 291 callback_data=callback_data) 292 293 if buf_obj is None: 294 if buf_xsize is None: 295 buf_xsize = win_xsize 296 if buf_ysize is None: 297 buf_ysize = win_ysize 298 if buf_type is None: 299 buf_type = ds.GetRasterBand(1).DataType 300 for band_index in range(2, ds.RasterCount + 1): 301 if buf_type != ds.GetRasterBand(band_index).DataType: 302 buf_type = gdalconst.GDT_Float32 303 304 typecode = GDALTypeCodeToNumericTypeCode(buf_type) 305 if typecode is None: 306 buf_type = gdalconst.GDT_Float32 307 typecode = numpy.float32 308 else: 309 buf_type = NumericTypeCodeToGDALTypeCode(typecode) 310 311 if buf_type == gdalconst.GDT_Byte and ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE': 312 typecode = numpy.int8 313 buf_shape = (ds.RasterCount, buf_ysize, buf_xsize) if interleave else (buf_ysize, buf_xsize, ds.RasterCount) 314 buf_obj = numpy.empty(buf_shape, dtype=typecode) 315 316 else: 317 if len(buf_obj.shape) != 3: 318 raise ValueError('Array should have 3 dimensions') 319 320 shape_buf_xsize = buf_obj.shape[xdim] 321 shape_buf_ysize = buf_obj.shape[ydim] 322 if buf_xsize is not None and buf_xsize != shape_buf_xsize: 323 raise ValueError('Specified buf_xsize not consistent with array shape') 324 if buf_ysize is not None and buf_ysize != shape_buf_ysize: 325 raise ValueError('Specified buf_ysize not consistent with array shape') 326 if buf_obj.shape[0] != ds.RasterCount: 327 raise ValueError('Array should have space for %d bands' % ds.RasterCount) 328 329 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type) 330 if not datatype: 331 raise ValueError("array does not have corresponding GDAL data type") 332 if buf_type is not None and buf_type != datatype: 333 raise ValueError("Specified buf_type not consistent with array type") 334 buf_type = datatype 335 336 if DatasetIONumPy(ds, 0, xoff, yoff, win_xsize, win_ysize, 337 buf_obj, buf_type, resample_alg, callback, callback_data, interleave) != 0: 338 _RaiseException() 339 return None 340 341 return buf_obj
342
343 -def BandReadAsArray(band, xoff=0, yoff=0, win_xsize=None, win_ysize=None, 344 buf_xsize=None, buf_ysize=None, buf_type=None, buf_obj=None, 345 resample_alg=gdal.GRIORA_NearestNeighbour, 346 callback=None, callback_data=None):
347 """Pure python implementation of reading a chunk of a GDAL file 348 into a numpy array. Used by the gdal.Band.ReadAsArray method.""" 349 350 if win_xsize is None: 351 win_xsize = band.XSize 352 if win_ysize is None: 353 win_ysize = band.YSize 354 355 if buf_obj is None: 356 if buf_xsize is None: 357 buf_xsize = win_xsize 358 if buf_ysize is None: 359 buf_ysize = win_ysize 360 if buf_type is None: 361 buf_type = band.DataType 362 363 typecode = GDALTypeCodeToNumericTypeCode(buf_type) 364 if typecode is None: 365 buf_type = gdalconst.GDT_Float32 366 typecode = numpy.float32 367 else: 368 buf_type = NumericTypeCodeToGDALTypeCode(typecode) 369 370 if buf_type == gdalconst.GDT_Byte and band.GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE': 371 typecode = numpy.int8 372 buf_obj = numpy.empty([buf_ysize, buf_xsize], dtype=typecode) 373 374 else: 375 if len(buf_obj.shape) == 2: 376 shape_buf_xsize = buf_obj.shape[1] 377 shape_buf_ysize = buf_obj.shape[0] 378 else: 379 shape_buf_xsize = buf_obj.shape[2] 380 shape_buf_ysize = buf_obj.shape[1] 381 if buf_xsize is not None and buf_xsize != shape_buf_xsize: 382 raise ValueError('Specified buf_xsize not consistent with array shape') 383 if buf_ysize is not None and buf_ysize != shape_buf_ysize: 384 raise ValueError('Specified buf_ysize not consistent with array shape') 385 386 datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type) 387 if not datatype: 388 raise ValueError("array does not have corresponding GDAL data type") 389 if buf_type is not None and buf_type != datatype: 390 raise ValueError("Specified buf_type not consistent with array type") 391 buf_type = datatype 392 393 if BandRasterIONumPy(band, 0, xoff, yoff, win_xsize, win_ysize, 394 buf_obj, buf_type, resample_alg, callback, callback_data) != 0: 395 _RaiseException() 396 return None 397 398 return buf_obj
399
400 -def BandWriteArray(band, array, xoff=0, yoff=0, 401 resample_alg=gdal.GRIORA_NearestNeighbour, 402 callback=None, callback_data=None):
403 """Pure python implementation of writing a chunk of a GDAL file 404 from a numpy array. Used by the gdal.Band.WriteArray method.""" 405 406 if array is None or len(array.shape) != 2: 407 raise ValueError("expected array of dim 2") 408 409 xsize = array.shape[1] 410 ysize = array.shape[0] 411 412 if xsize + xoff > band.XSize or ysize + yoff > band.YSize: 413 raise ValueError("array larger than output file, or offset off edge") 414 415 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type) 416 417 # if we receive some odd type, like int64, try casting to a very 418 # generic type we do support (#2285) 419 if not datatype: 420 gdal.Debug('gdal_array', 'force array to float64') 421 array = array.astype(numpy.float64) 422 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type) 423 424 if not datatype: 425 raise ValueError("array does not have corresponding GDAL data type") 426 427 ret = BandRasterIONumPy(band, 1, xoff, yoff, xsize, ysize, 428 array, datatype, resample_alg, callback, callback_data) 429 if ret != 0: 430 _RaiseException() 431 return ret
432
433 -def RATWriteArray(rat, array, field, start=0):
434 """ 435 Pure Python implementation of writing a chunk of the RAT 436 from a numpy array. Type of array is coerced to one of the types 437 (int, double, string) supported. Called from RasterAttributeTable.WriteArray 438 """ 439 if array is None: 440 raise ValueError("Expected array of dim 1") 441 442 # if not the array type convert it to handle lists etc 443 if not isinstance(array, numpy.ndarray): 444 array = numpy.array(array) 445 446 if array.ndim != 1: 447 raise ValueError("Expected array of dim 1") 448 449 if (start + array.size) > rat.GetRowCount(): 450 raise ValueError("Array too big to fit into RAT from start position") 451 452 if numpy.issubdtype(array.dtype, numpy.integer): 453 # is some type of integer - coerce to standard int 454 # TODO: must check this is fine on all platforms 455 # confusingly numpy.int 64 bit even if native type 32 bit 456 array = array.astype(numpy.int32) 457 elif numpy.issubdtype(array.dtype, numpy.floating): 458 # is some type of floating point - coerce to double 459 array = array.astype(numpy.double) 460 elif numpy.issubdtype(array.dtype, numpy.character): 461 # cast away any kind of Unicode etc 462 array = array.astype(numpy.character) 463 else: 464 raise ValueError("Array not of a supported type (integer, double or string)") 465 466 ret = RATValuesIONumPyWrite(rat, field, start, array) 467 if ret != 0: 468 _RaiseException() 469 return ret
470
471 -def RATReadArray(rat, field, start=0, length=None):
472 """ 473 Pure Python implementation of reading a chunk of the RAT 474 into a numpy array. Called from RasterAttributeTable.ReadAsArray 475 """ 476 if length is None: 477 length = rat.GetRowCount() - start 478 479 ret = RATValuesIONumPyRead(rat, field, start, length) 480 if ret is None: 481 _RaiseException() 482 return ret
483
484 -def CopyDatasetInfo(src, dst, xoff=0, yoff=0):
485 """ 486 Copy georeferencing information and metadata from one dataset to another. 487 src: input dataset 488 dst: output dataset - It can be a ROI - 489 xoff, yoff: dst's offset with respect to src in pixel/line. 490 491 Notes: Destination dataset must have update access. Certain formats 492 do not support creation of geotransforms and/or gcps. 493 494 """ 495 496 dst.SetMetadata(src.GetMetadata()) 497 498 499 500 #Check for geo transform 501 gt = src.GetGeoTransform() 502 if gt != (0, 1, 0, 0, 0, 1): 503 dst.SetProjection(src.GetProjectionRef()) 504 505 if xoff == 0 and yoff == 0: 506 dst.SetGeoTransform(gt) 507 else: 508 ngt = [gt[0], gt[1], gt[2], gt[3], gt[4], gt[5]] 509 ngt[0] = gt[0] + xoff*gt[1] + yoff*gt[2] 510 ngt[3] = gt[3] + xoff*gt[4] + yoff*gt[5] 511 dst.SetGeoTransform((ngt[0], ngt[1], ngt[2], ngt[3], ngt[4], ngt[5])) 512 513 #Check for GCPs 514 elif src.GetGCPCount() > 0: 515 516 if (xoff == 0) and (yoff == 0): 517 dst.SetGCPs(src.GetGCPs(), src.GetGCPProjection()) 518 else: 519 gcps = src.GetGCPs() 520 #Shift gcps 521 new_gcps = [] 522 for gcp in gcps: 523 ngcp = gdal.GCP() 524 ngcp.GCPX = gcp.GCPX 525 ngcp.GCPY = gcp.GCPY 526 ngcp.GCPZ = gcp.GCPZ 527 ngcp.GCPPixel = gcp.GCPPixel - xoff 528 ngcp.GCPLine = gcp.GCPLine - yoff 529 ngcp.Info = gcp.Info 530 ngcp.Id = gcp.Id 531 new_gcps.append(ngcp) 532 533 try: 534 dst.SetGCPs(new_gcps, src.GetGCPProjection()) 535 except: 536 print("Failed to set GCPs") 537 return 538 539 return
540 541 # This file is compatible with both classic and new-style classes. 542