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.12 
  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  from sys import version_info as _swig_python_version_info 
  8  if _swig_python_version_info >= (2, 7, 0): 
9 - def swig_import_helper():
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):
20 - def swig_import_helper():
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 # Python < 2.2 doesn't have 'property'. 45 46 try: 47 import builtins as __builtin__ 48 except ImportError: 49 import __builtin__ 50
51 -def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
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
70 -def _swig_setattr(self, class_type, name, value):
71 return _swig_setattr_nondynamic(self, class_type, name, value, 0)
72 73
74 -def _swig_getattr(self, class_type, name):
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
83 -def _swig_repr(self):
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:
94 - class _object:
95 pass
96 _newclass = 0 97 98 import osgeo.gdal
99 -class VirtualMem(_object):
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
107 - def __init__(self, *args, **kwargs):
108 raise AttributeError("No constructor defined")
109 __repr__ = _swig_repr 110 __swig_destroy__ = _gdal_array.delete_VirtualMem 111 __del__ = lambda self: None 112
113 - def GetAddr(self):
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
131 -def _StoreLastException():
132 """_StoreLastException()""" 133 return _gdal_array._StoreLastException()
134
135 -def TermProgress_nocb(dfProgress, pszMessage=None, pData=None):
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
140 -def OpenNumPyArray(psArray, binterleave):
141 """OpenNumPyArray(PyArrayObject * psArray, bool binterleave) -> Dataset""" 142 return _gdal_array.OpenNumPyArray(psArray, binterleave)
143
144 -def OpenMultiDimensionalNumPyArray(psArray):
145 """OpenMultiDimensionalNumPyArray(PyArrayObject * psArray) -> Dataset""" 146 return _gdal_array.OpenMultiDimensionalNumPyArray(psArray)
147
148 -def GetArrayFilename(psArray):
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
164 -def VirtualMemGetArray(virtualmem):
165 """VirtualMemGetArray(VirtualMem virtualmem)""" 166 return _gdal_array.VirtualMemGetArray(virtualmem)
167
168 -def RATValuesIONumPyWrite(poRAT, nField, nStart, psArray):
169 """RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart, PyArrayObject * psArray) -> CPLErr""" 170 return _gdal_array.RATValuesIONumPyWrite(poRAT, nField, nStart, psArray)
171
172 -def RATValuesIONumPyRead(poRAT, nField, nStart, nLength):
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
216 -def flip_code(code):
217 if isinstance(code, (numpy.dtype, type)): 218 # since several things map to complex64 we must carefully select 219 # the opposite that is an exact match (ticket 1518) 220 if code == numpy.int8: 221 return gdalconst.GDT_Byte 222 if code == numpy.complex64: 223 return gdalconst.GDT_CFloat32 224 225 for key, value in codes.items(): 226 if value == code: 227 return key 228 return None 229 else: 230 try: 231 return codes[code] 232 except KeyError: 233 return None
234
235 -def NumericTypeCodeToGDALTypeCode(numeric_type):
236 if not isinstance(numeric_type, (numpy.dtype, type)): 237 raise TypeError("Input must be a type") 238 return flip_code(numeric_type)
239
240 -def GDALTypeCodeToNumericTypeCode(gdal_code):
241 return flip_code(gdal_code)
242
243 -def _RaiseException():
244 if gdal.GetUseExceptions(): 245 _StoreLastException() 246 raise RuntimeError(gdal.GetLastErrorMsg())
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
413 -def BandWriteArray(band, array, xoff=0, yoff=0, 414 resample_alg=gdal.GRIORA_NearestNeighbour, 415 callback=None, callback_data=None):
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 # if we receive some odd type, like int64, try casting to a very 431 # generic type we do support (#2285) 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
446 -def ExtendedDataTypeToNumPyDataType(dt):
447 klass = dt.GetClass() 448 449 if klass == gdal.GEDTC_STRING: 450 return numpy.bytes_ 451 452 if klass == gdal.GEDTC_NUMERIC: 453 buf_type = dt.GetNumericDataType() 454 typecode = GDALTypeCodeToNumericTypeCode(buf_type) 455 if typecode is None: 456 typecode = numpy.float32 457 return typecode 458 459 assert klass == gdal.GEDTC_COMPOUND 460 names = [] 461 formats = [] 462 offsets = [] 463 for comp in dt.GetComponents(): 464 names.append(comp.GetName()) 465 formats.append(ExtendedDataTypeToNumPyDataType(comp.GetType())) 466 offsets.append(comp.GetOffset()) 467 468 return numpy.dtype({'names': names, 469 'formats': formats, 470 'offsets': offsets, 471 'itemsize': dt.GetSize()})
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):
479 if not array_start_idx: 480 array_start_idx = [0] * mdarray.GetDimensionCount() 481 if not count: 482 count = [ dim.GetSize() for dim in mdarray.GetDimensions() ] 483 if not array_step: 484 array_step = [1] * mdarray.GetDimensionCount() 485 if not buffer_datatype: 486 buffer_datatype = mdarray.GetDataType() 487 488 if buf_obj is None: 489 typecode = ExtendedDataTypeToNumPyDataType(buffer_datatype) 490 buf_obj = numpy.empty(count, dtype=typecode) 491 492 ret = MDArrayIONumPy(False, mdarray, buf_obj, array_start_idx, array_step, buffer_datatype) 493 if ret != 0: 494 _RaiseException() 495 return buf_obj
496
497 -def MDArrayWriteArray(mdarray, array, 498 array_start_idx = None, 499 array_step = None):
500 if not array_start_idx: 501 array_start_idx = [0] * mdarray.GetDimensionCount() 502 if not array_step: 503 array_step = [1] * mdarray.GetDimensionCount() 504 505 buffer_datatype = mdarray.GetDataType() 506 if array.dtype != ExtendedDataTypeToNumPyDataType(buffer_datatype): 507 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type) 508 509 # if we receive some odd type, like int64, try casting to a very 510 # generic type we do support (#2285) 511 if not datatype: 512 gdal.Debug('gdal_array', 'force array to float64') 513 array = array.astype(numpy.float64) 514 datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type) 515 516 if not datatype: 517 raise ValueError("array does not have corresponding GDAL data type") 518 519 buffer_datatype = gdal.ExtendedDataType.Create(datatype) 520 521 ret = MDArrayIONumPy(True, mdarray, array, array_start_idx, array_step, buffer_datatype) 522 if ret != 0: 523 _RaiseException() 524 return ret
525
526 -def RATWriteArray(rat, array, field, start=0):
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 # if not the array type convert it to handle lists etc 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 # is some type of integer - coerce to standard int 547 # TODO: must check this is fine on all platforms 548 # confusingly numpy.int 64 bit even if native type 32 bit 549 array = array.astype(numpy.int32) 550 elif numpy.issubdtype(array.dtype, numpy.floating): 551 # is some type of floating point - coerce to double 552 array = array.astype(numpy.double) 553 elif numpy.issubdtype(array.dtype, numpy.character): 554 # cast away any kind of Unicode etc 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
564 -def RATReadArray(rat, field, start=0, length=None):
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
577 -def CopyDatasetInfo(src, dst, xoff=0, yoff=0):
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 #Check for geo transform 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 #Check for GCPs 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 #Shift gcps 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 # This file is compatible with both classic and new-style classes. 635