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  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
    104 -class VirtualMem(_object):
    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
    112 -    def __init__(self, *args, **kwargs):
    113          raise AttributeError("No constructor defined")
    114      __repr__ = _swig_repr
    115      __swig_destroy__ = _gdal_array.delete_VirtualMem
    116      __del__ = lambda self: None
    117
    118 -    def GetAddr(self):
    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
    136 -def _StoreLastException():
    137      """_StoreLastException()"""
    138      return _gdal_array._StoreLastException()
    139
    140 -def TermProgress_nocb(dfProgress, pszMessage=None, pData=None):
    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
    145 -def OpenNumPyArray(psArray, binterleave):
    146      """OpenNumPyArray(PyArrayObject * psArray, bool binterleave) -> Dataset"""
    147      return _gdal_array.OpenNumPyArray(psArray, binterleave)
    148
    149 -def OpenMultiDimensionalNumPyArray(psArray):
    150      """OpenMultiDimensionalNumPyArray(PyArrayObject * psArray) -> Dataset"""
    151      return _gdal_array.OpenMultiDimensionalNumPyArray(psArray)
    152
    153 -def GetArrayFilename(psArray):
    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
    169 -def VirtualMemGetArray(virtualmem):
    170      """VirtualMemGetArray(VirtualMem virtualmem)"""
    171      return _gdal_array.VirtualMemGetArray(virtualmem)
    172
    173 -def RATValuesIONumPyWrite(poRAT, nField, nStart, psArray):
    174      """RATValuesIONumPyWrite(RasterAttributeTable poRAT, int nField, int nStart, PyArrayObject * psArray) -> CPLErr"""
    175      return _gdal_array.RATValuesIONumPyWrite(poRAT, nField, nStart, psArray)
    176
    177 -def RATValuesIONumPyRead(poRAT, nField, nStart, nLength):
    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
    221 -def flip_code(code):
    222      if isinstance(code, (numpy.dtype, type)):
    223  # since several things map to complex64 we must carefully select
    224  # the opposite that is an exact match (ticket 1518)
    225          if code == numpy.int8:
    226              return gdalconst.GDT_Byte
    227          if code == numpy.complex64:
    228              return gdalconst.GDT_CFloat32
    229
    230          for key, value in codes.items():
    231              if value == code:
    232                  return key
    233          return None
    234      else:
    235          try:
    236              return codes[code]
    237          except KeyError:
    238              return None
    239
    240 -def NumericTypeCodeToGDALTypeCode(numeric_type):
    241      if not isinstance(numeric_type, (numpy.dtype, type)):
    242          raise TypeError("Input must be a type")
    243      return flip_code(numeric_type)
    244
    245 -def GDALTypeCodeToNumericTypeCode(gdal_code):
    246      return flip_code(gdal_code)
    247
    248 -def _RaiseException():
    249      if gdal.GetUseExceptions():
    250          _StoreLastException()
    251          raise RuntimeError(gdal.GetLastErrorMsg())
    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
    372 -def DatasetWriteArray(ds, array, xoff=0, yoff=0,
    373                        band_list=None,
    374                        interleave='band',
    375                        resample_alg=gdal.GRIORA_NearestNeighbour,
    376                        callback=None, callback_data=None):
    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  # if we receive some odd type, like int64, try casting to a very
    424  # generic type we do support (#2285)
    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
    503 -def BandWriteArray(band, array, xoff=0, yoff=0,
    504                     resample_alg=gdal.GRIORA_NearestNeighbour,
    505                     callback=None, callback_data=None):
    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  # if we receive some odd type, like int64, try casting to a very
    521  # generic type we do support (#2285)
    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
    536 -def _ExtendedDataTypeToNumPyDataType(dt):
    537      klass = dt.GetClass()
    538
    539      if klass == gdal.GEDTC_STRING:
    540          return numpy.bytes_, dt
    541
    542      if klass == gdal.GEDTC_NUMERIC:
    543          buf_type = dt.GetNumericDataType()
    544          typecode = GDALTypeCodeToNumericTypeCode(buf_type)
    545          if typecode is None:
    546              typecode = numpy.float32
    547              dt = gdal.ExtendedDataType.Create(gdal.GDT_Float32)
    548          else:
    549              dt = gdal.ExtendedDataType.Create(NumericTypeCodeToGDALTypeCode(typecode))
    550          return typecode, dt
    551
    552      assert klass == gdal.GEDTC_COMPOUND
    553      names = []
    554      formats = []
    555      offsets = []
    556      for comp in dt.GetComponents():
    557          names.append(comp.GetName())
    558          typecode, subdt = _ExtendedDataTypeToNumPyDataType(comp.GetType())
    559          if subdt != comp.GetType():
    560              raise Exception("Incompatible datatype")
    561          formats.append(typecode)
    562          offsets.append(comp.GetOffset())
    563
    564      return numpy.dtype({'names': names,
    565                          'formats': formats,
    566                          'offsets': offsets,
    567                          'itemsize': dt.GetSize()}), dt
    568
    569 -def ExtendedDataTypeToNumPyDataType(dt):
    570      typecode, _ = _ExtendedDataTypeToNumPyDataType(dt)
    571      return typecode
    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):
    579      if not array_start_idx:
    580          array_start_idx = [0] * mdarray.GetDimensionCount()
    581      if not count:
    582          count = [ dim.GetSize() for dim in mdarray.GetDimensions() ]
    583      if not array_step:
    584          array_step = [1] * mdarray.GetDimensionCount()
    585
    586      if buf_obj is None:
    587          if not buffer_datatype:
    588              buffer_datatype = mdarray.GetDataType()
    589          typecode, buffer_datatype = _ExtendedDataTypeToNumPyDataType(buffer_datatype)
    590          buf_obj = numpy.empty(count, dtype=typecode)
    591      else:
    592          datatype = NumericTypeCodeToGDALTypeCode(buf_obj.dtype.type)
    593          if not datatype:
    594              raise ValueError("array does not have corresponding GDAL data type")
    595
    596          buffer_datatype = gdal.ExtendedDataType.Create(datatype)
    597
    598      ret = MDArrayIONumPy(False, mdarray, buf_obj, array_start_idx, array_step, buffer_datatype)
    599      if ret != 0:
    600          _RaiseException()
    601      return buf_obj
    602
    603 -def MDArrayWriteArray(mdarray, array,
    604                          array_start_idx = None,
    605                          array_step = None):
    606      if not array_start_idx:
    607          array_start_idx = [0] * mdarray.GetDimensionCount()
    608      if not array_step:
    609          array_step = [1] * mdarray.GetDimensionCount()
    610
    611      buffer_datatype = mdarray.GetDataType()
    612      typecode = ExtendedDataTypeToNumPyDataType(buffer_datatype)
    613      if array.dtype != typecode:
    614          datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
    615
    616  # if we receive some odd type, like int64, try casting to a very
    617  # generic type we do support (#2285)
    618          if not datatype:
    619              gdal.Debug('gdal_array', 'force array to float64')
    620              array = array.astype(numpy.float64)
    621              datatype = NumericTypeCodeToGDALTypeCode(array.dtype.type)
    622
    623          if not datatype:
    624              raise ValueError("array does not have corresponding GDAL data type")
    625
    626          buffer_datatype = gdal.ExtendedDataType.Create(datatype)
    627
    628      ret = MDArrayIONumPy(True, mdarray, array, array_start_idx, array_step, buffer_datatype)
    629      if ret != 0:
    630          _RaiseException()
    631      return ret
    632
    633 -def RATWriteArray(rat, array, field, start=0):
    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  # if not the array type convert it to handle lists etc
    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  # is some type of integer - coerce to standard int
    654  # TODO: must check this is fine on all platforms
    655  # confusingly numpy.int 64 bit even if native type 32 bit
    656          array = array.astype(numpy.int32)
    657      elif numpy.issubdtype(array.dtype, numpy.floating):
    658  # is some type of floating point - coerce to double
    659          array = array.astype(numpy.double)
    660      elif numpy.issubdtype(array.dtype, numpy.character):
    661  # cast away any kind of Unicode etc
    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
    671 -def RATReadArray(rat, field, start=0, length=None):
    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
    684 -def CopyDatasetInfo(src, dst, xoff=0, yoff=0):
    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  #Check for geo transform
    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  #Check for GCPs
    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  #Shift gcps
    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  # This file is compatible with both classic and new-style classes.
    742