# Raster API

This page contains classes, methods, functions that relate to the GDAL Raster Data Model:

- Driver

- Dataset

- Band

- Band Algebra

- Other

## Driver

class osgeo.gdal.Driver(*args, **kwargs)

  Python proxy of a `GDALDriver`.

  CopyDataSource(ds, utf8_path, options=None)

    Synonym for `CreateCopy()`.

  CopyFiles(Driver self, char const * newName, char const * oldName) → CPLErr

    Copy all the files associated with a `Dataset`.

    Parameters:

      - newName (str) -- new path for the dataset

      - oldName (str) -- old path for the dataset

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  Create(Driver self, char const * utf8_path, int xsize, int ysize, int bands=1, GDALDataType eType=GDT_Byte, char ** options=None) → Dataset

    Create a new `Dataset` with this driver. See `GDALDriver::Create()`.

    Parameters:

      - utf8_path (str) -- Path of the dataset to create.

      - xsize (int) -- Width of created raster in pixels. Set to zero for vector datasets.

      - ysize (int) -- Height of created raster in pixels. Set to zero for vector datasets.

      - bands (int, default = 1) -- Number of bands. Set to zero for vector datasets.

      - eType (int or numpy.dtype, default = `GDT_Byte`) -- Raster data type. Set to `GDT_Unknown` for vector datasets.

      - options (list or dict) -- List of driver-specific options

    Return type:

      Dataset

    Examples

        >>> with gdal.GetDriverByName('GTiff').Create('test.tif', 12, 4, 2, gdal.GDT_Float32, {'COMPRESS': 'DEFLATE'}) as ds:
        ...     print(gdal.Info(ds))
        ...
        Driver: GTiff/GeoTIFF
        Files: test.tif
        Size is 12, 4
        Image Structure Metadata:
          INTERLEAVE=PIXEL
        Corner Coordinates:
        Upper Left  (    0.0,    0.0)
        Lower Left  (    0.0,    4.0)
        Upper Right (   12.0,    0.0)
        Lower Right (   12.0,    4.0)
        Center      (    6.0,    2.0)
        Band 1 Block=12x4 Type=Float32, ColorInterp=Gray
        Band 2 Block=12x4 Type=Float32, ColorInterp=Undefined

        >>> with gdal.GetDriverByName('ESRI Shapefile').Create('test.shp', 0, 0, 0, gdal.GDT_Unknown) as ds:
        ...     print(gdal.VectorInfo(ds))
        ...
        INFO: Open of `test.shp'
              using driver `ESRI Shapefile' successful.

  CreateCopy(Driver self, char const * utf8_path, Dataset src, int strict=1, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) → Dataset

    Create a copy of a `Dataset`. See `GDALDriver::CreateCopy()`.

    Parameters:

      - utf8_path (str) -- Path of the dataset to create.

      - src (Dataset) -- The dataset being duplicated.

      - strict (bool, default=1) -- Indicates whether the copy must be strictly equivalent or if it may be adapted as needed for the output format.

      - options (list or dict) -- List of driver-specific options

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Return type:

      Dataset

  CreateDataSource(utf8_path, options=None)

    Synonym for `CreateVector()`.

  CreateMultiDimensional(Driver self, char const * utf8_path, char ** root_group_options=None, char ** options=None) → Dataset

    Create a new multidimensional dataset. See `GDALDriver::CreateMultiDimensional()`.

    Parameters:

      - utf8_path (str) -- Path of the dataset to create.

      - root_group_options (list or dict) -- Driver-specific options regarding the creation of the root group.

      - options (list or dict) -- List of driver-specific options regarding the creation of the Dataset.

    Return type:

      Dataset

    Examples

        >>> with gdal.GetDriverByName('netCDF').CreateMultiDimensional('test.nc') as ds:
        ...     gdal.MultiDimInfo(ds)
        ...
        {'type': 'group', 'driver': 'netCDF', 'name': '/', 'attributes': {'Conventions': 'CF-1.6'}, 'structural_info': {'NC_FORMAT': 'NETCDF4'}}

  CreateVector(Driver self, char const * utf8_path, char ** options=None) → Dataset

    Create a new vector `Dataset` with this driver. This method is an alias for `Create(name, 0, 0, 0, gdal.GDT_Unknown)`.

    Parameters:

      utf8_path (str) -- Path of the dataset to create.

    Return type:

      Dataset

    Examples

        >>> with gdal.GetDriverByName('ESRI Shapefile').CreateVector('test.shp') as ds:
        ...     print(ds.GetLayerCount())
        ...
        0

  Delete(Driver self, char const * utf8_path) → CPLErr

    Delete a `Dataset`. See `GDALDriver::Delete()`.

    Parameters:

      utf8_path (str) -- Path of the dataset to delete.

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  DeleteDataSource(utf8_path)

    Synonym for `Delete()`.

  Deregister(Driver self)

    Deregister the driver. See `GDALDriverManager::DeregisterDriver()`.

  GetName()

    Synonym for `GetDescription()`.

  HasOpenOption(Driver self, char const * openOptionName) → bool

    Reports whether the driver supports a specified open option.

    Parameters:

      openOptionName (str) -- The name of the option to test

    Returns:

      `True`, if the option is supported by this driver, `False` otherwise.

    Return type:

      bool

    Examples

        >>> gdal.GetDriverByName('GPKG').HasOpenOption('PRELUDE_STATEMENTS')
        True
        >>> gdal.GetDriverByName('GPKG').HasOpenOption('CLOSING_STATEMENTS')
        False

  property HelpTopic

    p.q(const).char

    The URL for driver documentation, relative to the GDAL documentation directory. See `GDALGetDriverHelpTopic()`.

    Type:

      HelpTopic

  property LongName

    p.q(const).char

    The long name of the driver. See `GDALGetDriverLongName()`.

    Type:

      LongName

  Open(utf8_path, update=False)

    Attempt to open a specified path with this driver.

    Parameters:

      - utf8_path (str) -- The path to open

      - update (bool, default = False) -- Whether to open the dataset in update mode.

    Returns:

      `None` on error

    Return type:

      Dataset or None

  Register(Driver self) → int

    Register the driver for use. See `GDALDriverManager::RegisterDriver()`.

  Rename(Driver self, char const * newName, char const * oldName) → CPLErr

    Rename a `Dataset`. See `GDALDriver::Rename()`.

    Parameters:

      - newName (str) -- new path for the dataset

      - oldName (str) -- old path for the dataset

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  property ShortName

    p.q(const).char

    The short name of a `Driver` that can be passed to `GetDriverByName()`. See `GDALGetDriverShortName()`.

    Type:

      ShortName

  TestCapability(Driver self, char const * cap) → bool

    Check whether the driver supports a specified capability (`ogr.ODrCCreateDataSource` or `ogr.ODrCDeleteDataSource`)`.

    Parameters:

      cap (str) -- The name of the capability to test

    Returns:

      `True` if the driver supports the capability, `False` otherwise.

    Return type:

      bool

    Examples

        >>> gdal.GetDriverByName('ESRI Shapefile').TestCapability(ogr.ODrCCreateDataSource)
        True
        >>> gdal.GetDriverByName('GTiff').TestCapability(ogr.ODrCCreateDataSource)
        True

osgeo.gdal.AllRegister()

  Register all known configured GDAL drivers. Automatically called when the `gdal` module is loaded. Does not need to be called in user code unless a driver was deregistered and needs to be re-registered. See `GDALAllRegister()`.

  See also

  `Driver.Register()`

osgeo.gdal.GetDriver(int i) → Driver

osgeo.gdal.GetDriverByName(char const * name) → Driver

osgeo.gdal.GetDriverCount() → int

  Return the number of registered drivers. See `GDALGetDriverCount()`.

  Examples

      >>> gdal.GetDriverCount()
      >>> 124
      >>> gdal.GetDriverByName('MapInfo File').Deregister()
      >>> gdal.GetDriverCount()
      >>> 123

osgeo.gdal.IdentifyDriver(char const * utf8_path, char ** papszSiblings=None) → Driver

osgeo.gdal.IdentifyDriverEx(char const * utf8_path, unsigned int nIdentifyFlags=0, char ** allowed_drivers=None, char ** sibling_files=None) → Driver

## Dataset

class osgeo.gdal.Dataset(*args, **kwargs)

  Python proxy of a `GDALDataset`.

  Since GDAL 3.8, a Dataset can be used as a context manager. When exiting the context, the Dataset will be closed and data will be written to disk.

  AbortSQL(Dataset self) → OGRErr

    Abort any SQL statement running in the data store.

    Not implemented by all drivers. See `GDALDataset::AbortSQL()`.

    Returns:

      `ogr.OGRERR_NONE` on success, or `ogr.OGRERR_UNSUPPORTED_OPERATION` if AbortSQL is not supported for this dataset.

    Return type:

      int

  AddBand(Dataset self, GDALDataType datatype=GDT_Byte, char ** options=None) → CPLErr

    Adds a band to a `Dataset`.

    Not supported by all drivers.

    Parameters:

      - datatype (int) -- the data type of the pixels in the new band

      - options (dict or list, optional) -- an optional dict or list of format-specific `NAME=VALUE` option strings.

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

    Examples

        >>> ds=gdal.GetDriverByName('MEM').Create('', 10, 10)
        >>> ds.RasterCount
        1
        >>> ds.AddBand(gdal.GDT_Float32)
        0
        >>> ds.RasterCount
        2

  AddFieldDomain(Dataset self, FieldDomain fieldDomain) → bool

    Add a `ogr.FieldDomain` to the dataset.

    Only a few drivers support this operation. See `GDALDataset::AddFieldDomain()`.

    Parameters:

      fieldDomain (FieldDomain) -- The field domain to add

    Returns:

      `True` if the field domain was added, `False` in case of error.

    Return type:

      bool

  AddRelationship(Dataset self, Relationship relationship) → bool

    Add a `Relationship` to the dataset.

    See `GDALDataset::AddRelationship()`.

    Parameters:

      relationship (Relationship) -- The relationship to add

    Returns:

      `True` if the field domain was added, `False` in case of error.

    Return type:

      bool

  AdviseRead(Dataset self, int xoff, int yoff, int xsize, int ysize, int * buf_xsize=None, int * buf_ysize=None, GDALDataType * buf_type=None, int band_list=0, char ** options=None) → CPLErr

    Advise driver of upcoming read requests.

    See `GDALDataset::AdviseRead()`.

  AsMDArray(Dataset self, char ** options=None) → MDArray
  BeginAsyncReader(xoff, yoff, xsize, ysize, buf_obj=None, buf_xsize=None, buf_ysize=None, buf_type=None, band_list=None, options=None)
  BuildOverviews(Dataset self, char const * resampling="NEAREST", int overviewlist=0, GDALProgressFunc callback=0, void * callback_data=None, char ** options=None) → int

    Build raster overview(s) for all bands.

    See `GDALDataset::BuildOverviews()`

    Parameters:

      - resampling (str, optional) -- The resampling method to use. See `GDALDataset::BuildOverviews()`.

      - overviewlist (list) -- A list of overview levels (decimation factors) to build, or an empty list to clear existing overviews.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

      - options (dict or list, optional) -- A dict or list of key=value options

    Returns:

      `CE_Failure` if an error occurs, otherwise `CE_None`.

    Return type:

      int

    Examples

        >>> import numpy as np
        >>> ds = gdal.GetDriverByName('GTiff').Create('test.tif', 12, 12)
        >>> ds.GetRasterBand(1).WriteArray(np.arange(12*12).reshape((12, 12)))
        0
        >>> ds.BuildOverviews('AVERAGE', [2, 4])
        0
        >>> ds.GetRasterBand(1).GetOverviewCount()
        2
        >>> ds.BuildOverviews(overviewlist=[])
        0
        >>> ds.GetRasterBand(1).GetOverviewCount()
        0

  ClearStatistics(Dataset self)

    Clear statistics

    See `GDALDataset::ClearStatistics()`.

  Close(Dataset self) → CPLErr

    Closes opened dataset and releases allocated resources.

    This method can be used to force the dataset to close when one more references to the dataset are still reachable. If `Close()` is never called, the dataset will be closed automatically during garbage collection.

    It is illegal to call any method on the dataset or objects derived from it (bands, layers, etc.) afterwards.

    In most cases, it is preferable to open or create a dataset using a context manager instead of calling `Close()` directly.

  CommitTransaction(Dataset self) → OGRErr

    Commits a transaction, for Datasets that support transactions.

    See `GDALDataset::CommitTransaction()`.

  CopyLayer(Dataset self, Layer src_layer, char const * new_name, char ** options=None) → Layer

    Duplicate an existing `ogr.Layer`.

    See `GDALDataset::CopyLayer()`.

    Parameters:

      - src_layer (Layer) -- source layer

      - new_name (str) -- name of the layer to create

      - options (dict or list) -- a dict or list of name=value driver-specific creation options

    Returns:

      A layer if successful, or `None` if an error occurs.

    Return type:

      Layer or None

  CreateLayer(Dataset self, char const * name, SpatialReference srs=None, OGRwkbGeometryType geom_type=wkbUnknown, char ** options=None) → Layer

    Create a new layer in a vector Dataset.

    Parameters:

      - name (str) -- the name for the new layer. This should ideally not match any existing layer on the datasource.

      - srs (SpatialReference, optional) -- The coordinate system to use for the new layer, or `None` if no coordinate system is available. Defaults to `None`.

      - geom_type (int, default = `ogr.wkbUnknown`) -- geometry type for the layer. Use `ogr.wkbUnknown` if there are no constraints on the types geometry to be written.

      - options (dict or list, optional) -- Driver-specific dict or list of name=value options

    Returns:

      The layer object if successful, or `None` on failure.

    Return type:

      Layer or None

    Examples

        >>> ds = gdal.GetDriverByName('GPKG').Create('test.gpkg', 0, 0)
        >>> ds.GetLayerCount()
        0
        >>> lyr = ds.CreateLayer('poly', geom_type=ogr.wkbPolygon)
        >>> ds.GetLayerCount()
        1

  CreateLayerFromGeomFieldDefn(Dataset self, char const * name, GeomFieldDefn geom_field, char ** options=None) → Layer
  CreateMaskBand(Dataset self, int nFlags) → CPLErr

    Adds a mask band to the dataset.

    See `GDALDataset::CreateMaskBand()`.

    Parameters:

      flags (int)

    Returns:

      `CE_Failure` if an error occurs, otherwise `CE_None`.

    Return type:

      int

  DeleteFieldDomain(Dataset self, char const * name) → bool

    Removes a field domain from the Dataset.

    Parameters:

      name (str) -- Name of the field domain to delete

    Returns:

      `True` if the field domain was removed, otherwise `False`.

    Return type:

      bool

  DeleteLayer(value)

    Delete the indicated layer from the Dataset.

    Parameters:

      value (int or str) -- Name or 0-based index of the layer to delete.

    Returns:

      `ogr.OGRERR_NONE` on success or `ogr.OGRERR_UNSUPPORTED_OPERATION` if DeleteLayer is not supported for this dataset.

    Return type:

      int

  DeleteRelationship(Dataset self, char const * name) → bool

    Removes a relationship from the Dataset.

    Parameters:

      name (str) -- Name of the relationship to remove.

    Returns:

      `True` if the relationship was removed, otherwise `False`.

    Return type:

      bool

  Destroy()
  EndAsyncReader(Dataset self, AsyncReader ario)
  ExecuteSQL(self, statement, spatialFilter: ogr.Geometry = None, dialect: str | None = '', keep_ref_on_ds=False) → ogr.Layer

    Execute a SQL statement against the dataset

    The result of a SQL query is:

      - None (or an exception if exceptions are enabled) for statements that are in error

      - or None for statements that have no results set,

      - or a `ogr.Layer` handle representing a results set from the query.

    Note that this `ogr.Layer` is in addition to the layers in the data store and must be released with `ReleaseResultSet()` before the data source is closed (destroyed).

    Starting with GDAL 3.7, this method can also be used as a context manager, as a convenient way of automatically releasing the returned result layer.

    For more information on the SQL dialect supported internally by OGR review the OGR SQL document (OGR SQL dialect and SQLITE SQL dialect) Some drivers (i.e. Oracle and PostGIS) pass the SQL directly through to the underlying RDBMS.

    The SQLITE dialect can also be used (SQL SQLite dialect)

    Parameters:

      - statement (str) -- the SQL statement to execute (e.g "SELECT * FROM layer")

      - spatialFilter (any) -- a geometry which represents a spatial filter. Can be None

      - dialect (str) -- allows control of the statement dialect. If set to None or empty string, the OGR SQL engine will be used, except for RDBMS drivers that will use their dedicated SQL engine, unless OGRSQL is explicitly passed as the dialect. The SQLITE dialect can also be used.

      - keep_ref_on_ds (bool) -- whether the returned layer should keep a (strong) reference on the current dataset. Cf example 2 for a use case.

    Returns:

      a layer containing the results of the query, that will be automatically released when the context manager goes out of scope.

    Return type:

      Layer

    Examples

    1. Use as a context manager:

        >>> with ds.ExecuteSQL("SELECT * FROM layer") as lyr:
        ...     print(lyr.GetFeatureCount())
        10

    2. Use keep_ref_on_ds=True to return an object that keeps a reference to its dataset:

        >>> def get_sql_lyr():
        ...     return gdal.OpenEx("poly.shp", gdal.OF_VECTOR).ExecuteSQL("SELECT * FROM poly", keep_ref_on_ds=True)
        ...
        >>> with get_sql_lyr() as lyr:
        ...     print(lyr.GetFeatureCount())
        10

  FlushCache(Dataset self) → CPLErr

    Flush all write-cached data to disk.

    See `GDALDataset::FlushCache()`.

    Returns:

      gdal.CE_None in case of success

    Return type:

      int

  GetDriver(Dataset self) → Driver

    Fetch the driver used to open or create this `Dataset`.

  GetExtent(Dataset self, SpatialReference srs=None)

    Get the extent of the dataset.

    See `GDALDataset::GetExtent()`

    Added in version 3.12.

    Warning

    Check the return order of the bounds.

    Parameters:

      srs (SpatialReference, optional) -- Optional spatial reference in which the bounds should be returned. Defaults to `None`.

    Returns:

      tuple of (minx, maxx, miny, maxy) or None if the extent cannot be determined in the specified spatial reference system

    Return type:

      tuple or None

    Examples

        >>> # Get extent in native SRS (NAD27 / UTM 11N)
        >>> with gdal.Open('byte.tif') as ds:
        ...     ds.GetExtent()
        (440720.0, 441920.0, 3750120.0, 3751320.0)

        >>> # Get extent in US National Atlas Equal Area
        >>> with gdal.Open('byte.tif') as ds:
        ...     ds.GetExtent(osr.SpatialReference(epsg=9311))
        ...
        (-1621603.0, -1620214.9, -1064263.1, -1062837.1)

    See also

    `GetExtentWGS84LongLat()`

  GetExtentWGS84LongLat(Dataset self)

    Return the extent of the dataset in WGS84, with the x-axis representing longitude and the y-axis representing latitude.

    See `GDALDataset::GetExtentWGS84LongLat()`

    Added in version 3.12.

    Warning

    Check the return order of the bounds.

    Returns:

      tuple of (minlon, maxlon, minlat, maxlat) or None if the extent cannot be determined in WGS84

    Return type:

      tuple or None

    Examples

        >>> with gdal.Open('byte.tif') as ds:
        ...     ds.GetExtentWGS84LongLat()
        ...
        (-117.642, -117.629, 33.892, 33.902)

    See also

    `GetExtent()`

  GetFieldDomain(Dataset self, char const * name) → FieldDomain

    Get a field domain from its name.

    Parameters:

      name (str) -- The name of the field domain

    Returns:

      An FieldDomain instance if found, or `None` if it is not found.

    Return type:

      FieldDomain or None

  GetFieldDomainNames(Dataset self, char ** options=None) → char **

    Get a list of the names of all field domains stored in the dataset.

    Parameters:

      options (dict or list, optional) -- Driver-specific options determining how attributes should be retrieved.

    Returns:

      `None` if no field domains are stored in the dataset.

    Return type:

      list or None

  GetFileList(Dataset self) → char **

    Returns a list of files believed to be part of this dataset. See `GDALGetFileList()`.

  GetGCPCount(Dataset self) → int

    Get number of GCPs. See `GDALGetGCPCount()`.

    Return type:

      int

  GetGCPProjection(Dataset self) → char const *

    Return a WKT representation of the GCP spatial reference.

    Return type:

      str

  GetGCPSpatialRef(Dataset self) → SpatialReference

    Get output spatial reference system for GCPs.

    See `GDALGetGCPSpatialRef()`

  GetGCPs(Dataset self)

    Get the GCPs. See `GDALGetGCPs()`.

    Returns:

      a tuple of `GCP` objects.

    Return type:

      tuple

  GetGeoTransform(Dataset self, int * can_return_null=None)

    Fetch the affine transformation coefficients.

    See `GDALGetGeoTransform()`.

    Parameters:

      can_return_null (bool, default=False) -- if `True`, return `None` instead of the default transformation if the transformation for this `Dataset` has not been defined.

    Returns:

      a 6-member tuple representing the transformation coefficients

    Return type:

      tuple

  GetLayer(iLayer=0)

    Get the indicated layer from the Dataset

    Parameters:

      value (int or str) -- Name or 0-based index of the layer to delete.

    Returns:

      A layer if successful, or `None` on error.

    Return type:

      Layer

  GetLayerByIndex(Dataset self, int index=0) → Layer

    Fetch a layer by index.

    Parameters:

      index (int) -- A layer number between 0 and `GetLayerCount() - 1`

    Returns:

      An layer if successful, or `None` on error.

    Return type:

      Layer or None

  GetLayerByName(Dataset self, char const * layer_name) → Layer
  GetLayerCount(Dataset self) → int

    Get the number of layers in this dataset.

    Return type:

      int

  GetName()
  GetNextFeature(Dataset self, bool include_layer=True, bool include_pct=False, GDALProgressFunc callback=0, void * callback_data=None) → Feature

    Fetch the next available feature from this dataset.

    This method is intended for the few drivers where `OGRLayer.GetNextFeature()` is not efficient, but in general `OGRLayer.GetNextFeature()` is a more natural API.

    See `GDALDataset::GetNextFeature()`.

    Return type:

      Feature

  GetProjection(Dataset self) → char const *

    Return a WKT representation of the dataset spatial reference. Equivalent to `GetProjectionRef()`.

    Return type:

      str

  GetProjectionRef(Dataset self) → char const *

    Return a WKT representation of the dataset spatial reference.

    Return type:

      str

  GetRasterBand(Dataset self, int nBand) → Band

    Fetch a `Band` band from a `Dataset`. See `GDALGetRasterBand()`.

    Parameters:

      nBand (int) -- the index of the band to fetch, from 1 to `RasterCount`

    Returns:

      the `Band`, or `None` on error.

    Return type:

      Band

  GetRefCount(Dataset self) → int
  GetRelationship(Dataset self, char const * name) → Relationship

    Get a relationship from its name.

    Return type:

      Relationship, or `None` if not found.

  GetRelationshipNames(Dataset self, char ** options=None) → char **

    Get a list of the names of all relationships stored in the dataset.

    Parameters:

      options (dict or list, optional) -- driver-specific options determining how the relationships should be retrieved

  GetRootGroup(Dataset self) → Group

    Return the root `Group` of this dataset. Only value for multidimensional datasets.

    Return type:

      Group

  GetSpatialRef(Dataset self) → SpatialReference

    Fetch the spatial reference for this dataset.

    Return type:

      SpatialReference

  GetStyleTable(Dataset self) → StyleTable

    Returns dataset style table.

    Return type:

      StyleTable

  GetSubDatasets()

    Return a list of Subdatasets.

    Return type:

      list

  GetSummaryRefCount(Dataset self) → int
  GetThreadSafeDataset(Dataset self, int nScopeFlags) → Dataset
  GetTiledVirtualMem(Dataset self, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nTileXSize, int nTileYSize, GDALDataType eBufType, int band_list, GDALTileOrganization eTileOrganization, size_t nCacheSize, char ** options=None) → VirtualMem
  GetTiledVirtualMemArray(eAccess=0, xoff=0, yoff=0, xsize=None, ysize=None, tilexsize=256, tileysize=256, datatype=None, band_list=None, tile_organization=2, cache_size=10485760, options=None)

    Return a NumPy array for the dataset, seen as a virtual memory mapping with a tile organization. If there are several bands and tile_organization = gdal.GTO_TIP, an element is accessed with array[tiley][tilex][y][x][band]. If there are several bands and tile_organization = gdal.GTO_BIT, an element is accessed with array[tiley][tilex][band][y][x]. If there are several bands and tile_organization = gdal.GTO_BSQ, an element is accessed with array[band][tiley][tilex][y][x]. If there is only one band, an element is accessed with array[tiley][tilex][y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.

  GetVirtualMem(Dataset self, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eBufType, int band_list, int bIsBandSequential, size_t nCacheSize, size_t nPageSizeHint, char ** options=None) → VirtualMem
  GetVirtualMemArray(eAccess=0, xoff=0, yoff=0, xsize=None, ysize=None, bufxsize=None, bufysize=None, datatype=None, band_list=None, band_sequential=True, cache_size=10485760, page_size_hint=0, options=None)

    Return a NumPy array for the dataset, seen as a virtual memory mapping. If there are several bands and band_sequential = True, an element is accessed with array[band][y][x]. If there are several bands and band_sequential = False, an element is accessed with array[y][x][band]. If there is only one band, an element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.

  IsLayerPrivate(Dataset self, int index) → bool
    Parameters:

      index (int) -- Index o layer to check

    Returns:

      `True` if the layer is a private or system table, `False` otherwise

    Return type:

      bool

  IsThreadSafe(Dataset self, int nScopeFlags) → bool
  MarkSuppressOnClose(Dataset self)
  property RasterCount

    int

    The number of bands in this dataset.

    Type:

      RasterCount

  property RasterXSize

    int

    Raster width in pixels. See `GDALGetRasterXSize()`.

    Type:

      RasterXSize

  property RasterYSize

    int

    Raster height in pixels. See `GDALGetRasterYSize()`.

    Type:

      RasterYSize

  ReadAsArray(xoff=0, yoff=0, xsize=None, ysize=None, buf_obj=None, buf_xsize=None, buf_ysize=None, buf_type=None, resample_alg=0, callback=None, callback_data=None, interleave='band', band_list=None)

    Read a window from raster bands into a NumPy array.

    Parameters:

      - xoff (float, default=0) -- The pixel offset to left side of the region of the band to be read. This would be zero to start from the left side.

      - yoff (float, default=0) -- The line offset to top side of the region of the band to be read. This would be zero to start from the top side.

      - xsize (float, optional) -- The number of pixels to read in the x direction. By default, equal to the number of columns in the raster.

      - ysize (float, optional) -- The number of rows to read in the y direction. By default, equal to the number of bands in the raster.

      - buf_xsize (int, optional) -- The number of columns in the returned array. If not equal to `win_xsize`, the returned values will be determined by `resample_alg`.

      - buf_ysize (int, optional) -- The number of rows in the returned array. If not equal to `win_ysize`, the returned values will be determined by `resample_alg`.

      - buf_type (int, optional) -- The data type of the returned array

      - buf_obj (np.ndarray, optional) -- Optional buffer into which values will be read. If `buf_obj` is specified, then `buf_xsize`/`buf_ysize`/`buf_type` should generally not be specified.

      - resample_alg (int, default = `gdal.GRIORA_NearestNeighbour`.) -- Specifies the resampling algorithm to use when the size of the read window and the buffer are not equal.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

      - band_list (list, optional) -- Indexes of bands from which data should be read. By default, data will be read from all bands.

    Return type:

      np.ndarray

    Examples

        >>> ds = gdal.GetDriverByName("GTiff").Create("test.tif", 4, 4, bands=2)
        >>> ds.WriteArray(np.arange(32).reshape(2, 4, 4))
        0
        >>> ds.ReadAsArray()
        array([[[ 0,  1,  2,  3],
                [ 4,  5,  6,  7],
                [ 8,  9, 10, 11],
                [12, 13, 14, 15]],
               [[16, 17, 18, 19],
                [20, 21, 22, 23],
                [24, 25, 26, 27],
                [28, 29, 30, 31]]], dtype=uint8)
        >>> ds.ReadAsArray(xoff=2, yoff=2, xsize=2, ysize=2)
        array([[[10, 11],
                [14, 15]],
               [[26, 27],
                [30, 31]]], dtype=uint8)
        >>> ds.ReadAsArray(buf_xsize=2, buf_ysize=2, buf_type=gdal.GDT_Float64, resample_alg=gdal.GRIORA_Average)
        array([[[ 3.,  5.],
                [11., 13.]],
               [[19., 21.],
                [27., 29.]]])
        >>> buf = np.zeros((2,2,2))
        >>> ds.ReadAsArray(buf_obj=buf)
        array([[[ 5.,  7.],
                [13., 15.]],
               [[21., 23.],
                [29., 31.]]])
        >>> ds.ReadAsArray(band_list=[2,1])
        array([[[16, 17, 18, 19],
                [20, 21, 22, 23],
                [24, 25, 26, 27],
                [28, 29, 30, 31]],
               [[ 0,  1,  2,  3],
                [ 4,  5,  6,  7],
                [ 8,  9, 10, 11],
                [12, 13, 14, 15]]], dtype=uint8)

  ReadAsMaskedArray(xoff=0, yoff=0, xsize=None, ysize=None, buf_xsize=None, buf_ysize=None, buf_type=None, resample_alg=0, mask_resample_alg=0, callback=None, callback_data=None, band_list=None)

    Read a window from raster bands into a NumPy masked array.

    Values of the mask will be `True` where pixels are invalid.

    If resampling (`buf_xsize` != `xsize`, or `buf_ysize` != `ysize`) the mask band will be resampled using the algorithm specified by `mask_resample_alg`.

    See `ReadAsArray()` for a description of additional arguments.

  ReadRaster(xoff=0, yoff=0, xsize=None, ysize=None, buf_xsize=None, buf_ysize=None, buf_type=None, band_list=None, buf_pixel_space=None, buf_line_space=None, buf_band_space=None, resample_alg=0, callback=None, callback_data=None, buf_obj=None)
  ReadRaster1(Dataset self, double xoff, double yoff, double xsize, double ysize, int * buf_xsize=None, int * buf_ysize=None, GDALDataType * buf_type=None, int band_list=0, GIntBig * buf_pixel_space=None, GIntBig * buf_line_space=None, GIntBig * buf_band_space=None, GDALRIOResampleAlg resample_alg=GRIORA_NearestNeighbour, GDALProgressFunc callback=0, void * callback_data=None, void * inputOutputBuf=None) → CPLErr
  Release()
  ReleaseResultSet(self, sql_lyr: ogr.Layer)

    Release `ogr.Layer` returned by `ExecuteSQL()` (when not called as a context manager)

    The sql_lyr object is invalidated after this call.

    Parameters:

      sql_lyr (Layer) -- `ogr.Layer` got with `ExecuteSQL()`

  ResetReading(Dataset self)

    Reset feature reading to start on the first feature.

    This affects `GetNextFeature()`.

    Depending on drivers, this may also have the side effect of calling `OGRLayer.ResetReading()` on the layers of this dataset.

  RollbackTransaction(Dataset self) → OGRErr

    Roll back a Dataset to its state before the start of the current transaction.

    For datasets that support transactions.

    Returns:

      If no transaction is active, or the rollback fails, will return `OGRERR_FAILURE`. Datasources which do not support transactions will always return `OGRERR_UNSUPPORTED_OPERATION`.

    Return type:

      int

  SetGCPs(gcps, wkt_or_spatial_ref)

    Assign GCPs.

    See `GDALSetGCPs()`.

    Parameters:

      - gcps (list) -- a list of `GCP` objects

      - wkt_or_spatial_ref (str or SpatialReference) -- spatial reference of the GCPs as a string, or a `osr.SpatialReference`

  SetGeoTransform(Dataset self, double [6] argin) → CPLErr

    Set the affine transformation coefficients.

    See `GetGeoTransform()` for details on the meaning of the coefficients.

    Parameters:

      argin (tuple)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetProjection(Dataset self, char const * prj) → CPLErr

    Set the spatial reference system for this dataset.

    See `GDALDataset::SetProjection()`.

    Parameters:

      prj (str) -- The projection string in OGC WKT or PROJ.4 format

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetSpatialRef(Dataset self, SpatialReference srs) → CPLErr

    Set the spatial reference system for this dataset.

    Parameters:

      srs (SpatialReference)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetStyleTable(Dataset self, StyleTable table)

    Set dataset style table

    Parameters:

      table (StyleTable)

  StartTransaction(Dataset self, int force=FALSE) → OGRErr

    Creates a transaction. See `GDALDataset::StartTransaction()`.

    Returns:

      If starting the transaction fails, will return `ogr.OGRERR_FAILURE`. Datasources which do not support transactions will always return `OGRERR_UNSUPPORTED_OPERATION`.

    Return type:

      int

  SyncToDisk()
  TestCapability(Dataset self, char const * cap) → bool

    Test if a capability is available.

    Parameters:

      cap (str) -- Name of the capability (e.g., `ogr.ODsCTransactions`)

    Returns:

      `True` if the capability is available, `False` if invalid or unavailable

    Return type:

      bool

    Examples

        >>> ds = gdal.GetDriverByName('ESRI Shapefile').Create('test.shp', 0, 0, 0, gdal.GDT_Unknown)
        >>> ds.TestCapability(ogr.ODsCTransactions)
        False
        >>> ds.TestCapability(ogr.ODsCMeasuredGeometries)
        True
        >>> ds.TestCapability(gdal.GDsCAddRelationship)
        False

  UpdateFieldDomain(Dataset self, FieldDomain fieldDomain) → bool

    Update an existing field domain by replacing its definition.

    The existing field domain with matching name will be replaced.

    Requires the `ogr.ODsCUpdateFieldDomain` dataset capability.

    Parameters:

      fieldDomain (FieldDomain) -- Updated field domain.

    Returns:

      `True` in case of success

    Return type:

      bool

  UpdateRelationship(Dataset self, Relationship relationship) → bool

    Update an existing relationship by replacing its definition.

    The existing relationship with matching name will be replaced.

    Requires the `gdal.GDsCUpdateFieldDomain` dataset capability.

    Parameters:

      relationship (Relationship) -- Updated relationship

    Returns:

      `True` in case of success

    Return type:

      bool

  WriteArray(array, xoff=0, yoff=0, band_list=None, interleave='band', resample_alg=0, callback=None, callback_data=None)

    Write the contents of a NumPy array to a Dataset.

    Parameters:

      - array (np.ndarray) -- Two- or three-dimensional array containing values to write

      - xoff (int, default=0) -- The pixel offset to left side of the region of the band to be written. This would be zero to start from the left side.

      - yoff (int, default=0) -- The line offset to top side of the region of the band to be written. This would be zero to start from the top side.

      - band_list (list, optional) -- Indexes of bands to which data should be written. By default, it is assumed that the Dataset contains the same number of bands as levels in `array`.

      - interleave (str, default="band") -- Interleaving, "band" or "pixel". For band-interleaved writing, `array` should have shape `(nband, ny, nx)`. For pixel- interleaved-writing, `array` should have shape `(ny, nx, nbands)`.

      - resample_alg (int, default = `gdal.GRIORA_NearestNeighbour`) -- Resampling algorithm. Placeholder argument, not currently supported.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Returns:

      Error code, or `gdal.CE_None` if no error occurred.

    Return type:

      int

    Examples

        >>> import numpy as np
        >>>
        >>> nx = 4
        >>> ny = 3
        >>> nbands = 2
        >>> with gdal.GetDriverByName("GTiff").Create("band3_px.tif", nx, ny, bands=nbands) as ds:
        ...     data = np.arange(nx*ny*nbands).reshape(ny,nx,nbands)
        ...     ds.WriteArray(data, interleave="pixel")
        ...     ds.ReadAsArray()
        ...
        0
        array([[[ 0,  2,  4,  6],
                [ 8, 10, 12, 14],
                [16, 18, 20, 22]],
               [[ 1,  3,  5,  7],
                [ 9, 11, 13, 15],
                [17, 19, 21, 23]]], dtype=uint8)
        >>> with gdal.GetDriverByName("GTiff").Create("band3_band.tif", nx, ny, bands=nbands) as ds:
        ...     data = np.arange(nx*ny*nbands).reshape(nbands, ny, nx)
        ...     ds.WriteArray(data, interleave="band")
        ...     ds.ReadAsArray()
        ...
        0
        array([[[ 0,  1,  2,  3],
                [ 4,  5,  6,  7],
                [ 8,  9, 10, 11]],
               [[12, 13, 14, 15],
                [16, 17, 18, 19],
                [20, 21, 22, 23]]], dtype=uint8)

  WriteRaster(xoff, yoff, xsize, ysize, buf_string, buf_xsize=None, buf_ysize=None, buf_type=None, band_list=None, buf_pixel_space=None, buf_line_space=None, buf_band_space=None)

osgeo.gdal.Open(char const * utf8_path, GDALAccess eAccess=GA_ReadOnly) → Dataset

  Opens a raster file as a `Dataset` using default options. See `GDALOpen()`. For more control over how the file is opened, use `OpenEx()`.

  Parameters:

    - utf8_path (str) -- name of the file to open

    - eAccess (int, default = `gdal.GA_ReadOnly`)

  Returns:

    A dataset if successful, or `None` on failure.

  Return type:

    Dataset or None

  See also

  `OpenEx()`, `OpenShared()`

osgeo.gdal.OpenEx(char const * utf8_path, unsigned int nOpenFlags=0, char ** allowed_drivers=None, char ** open_options=None, char ** sibling_files=None) → Dataset

  Open a raster or vector file as a `Dataset`. See `GDALOpenEx()`.

  Parameters:

    - utf8_path (str) -- name of the file to open

    - flags (int) -- Flags controlling how the Dataset is opened. Multiple `gdal.OF_XXX` flags may be combined using the `|` operator. See `GDALOpenEx()`.

    - allowed_drivers (list, optional) -- A list of the names of drivers that may attempt to open the dataset.

    - open_options (dict or list, optional) -- A dict or list of name=value driver-specific opening options.

    - sibling_files (list, optional) -- A list of filenames that are auxiliary to the main filename

  Returns:

    A dataset if successful, or `None` on failure.

  Return type:

    Dataset or None

  See also

  `Open()`, `OpenShared()`

osgeo.gdal.OpenShared(char const * utf8_path, GDALAccess eAccess=GA_ReadOnly) → Dataset

  Open a raster file as a `Dataset`. If the file has already been opened in the current thread, return a reference to the already-opened `Dataset`. See `GDALOpenShared()`.

  Parameters:

    - utf8_path (str) -- name of the file to open

    - eAccess (int, default = `gdal.GA_ReadOnly`)

  Returns:

    A dataset if successful, or `None` on failure.

  Return type:

    Dataset or None

  See also

  `Open()`, `OpenEx()`

## Band

class osgeo.gdal.Band(*args, **kwargs)

  Python proxy of a `GDALRasterBand`.

  AdviseRead(Band self, int xoff, int yoff, int xsize, int ysize, int * buf_xsize=None, int * buf_ysize=None, GDALDataType * buf_type=None, char ** options=None) → CPLErr
  AsMDArray(Band self) → MDArray
  BlockWindows()

    Yield a window `(xOff, yOff, xSize, ySize)` corresponding to each block in this `Band`. Iteration order is from left to right, then from top to bottom.

    Examples

        >>> for window in src_band.BlockWindows():
        ...    values = src_band.ReadAsArray(*window)
        ...    dst_band.WriteArray(values + 20, window.xoff, window.yoff)
        0

  Checksum(Band self, int xoff=0, int yoff=0, int * xsize=None, int * ysize=None) → int

    Computes a checksum from a region of a RasterBand. See `GDALChecksumImage()`.

    Parameters:

      - xoff (int, default=0) -- The pixel offset to left side of the region of the band to be read. This would be zero to start from the left side.

      - yoff (int, default=0) -- The line offset to top side of the region of the band to be read. This would be zero to start from the top side.

      - xsize (int, optional) -- The number of pixels to read in the x direction. By default, equal to the number of columns in the raster.

      - ysize (int, optional) -- The number of rows to read in the y direction. By default, equal to the number of bands in the raster.

    Returns:

      checksum value, or -1 in case of error

    Return type:

      int

  ComputeBandStats(Band self, int samplestep=1)

    Computes the mean and standard deviation of values in this Band. See `GDALComputeBandStats()`.

    Parameters:

      samplestep (int, default=1) -- Step between scanlines used to compute statistics.

    Returns:

      tuple of length 2 with value of mean and standard deviation

    Return type:

      tuple

    See also

    `ComputeRasterMinMax()`, `ComputeStatistics()`, `GetMaximum()`, `GetMinimum()`, `GetStatistics()`, `SetStatistics()`

  ComputeMinMaxLocation(*args, **kwargs)

    Compute the min/max values for a band, and their location.

    Pixels whose value matches the nodata value or are masked by the mask band are ignored.

    If the minimum or maximum value is hit in several locations, it is not specified which one will be returned.

    This is a mapping of `GDALRasterBand::ComputeRasterMinMaxLocation()`.

    Parameters:

      None

    Returns:

      a named tuple (min, max, minX, minY, maxX, maxY) or `None` in case of error or no valid pixel.

    Return type:

      tuple or None

  ComputeRasterMinMax(Band self, bool approx_ok=False, bool can_return_none=False) → (min, max) or None

    Computes the minimum and maximum values for this Band. See `GDALComputeRasterMinMax()`.

    Parameters:

      - approx_ok (bool, default=False) -- If `False`, read all pixels in the band. If `True`, check `GetMinimum()`/`GetMaximum()` or read a subsample.

      - can_return_none (bool, default=False) -- If `True`, return `None` on error. Otherwise, return a tuple with NaN values.

    Return type:

      tuple

    See also

    `ComputeBandStats()`, `ComputeStatistics()`, `GetMaximum()`, `GetMinimum()`, `GetStatistics()`, `SetStatistics()`

  ComputeStatistics(Band self, bool approx_ok, callback=None, callback_data=None)

    Compute image statistics. See `GDALRasterBand::ComputeStatistics()`.

    Parameters:

      - approx_ok (bool) -- If `True`, compute statistics based on overviews or a subset of tiles.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Returns:

      a list with the min, max, mean, and standard deviation of values in the Band.

    Return type:

      list

    See also

    `ComputeBandStats()`, `ComputeRasterMinMax()`, `GetMaximum()`, `GetMinimum()`, `GetStatistics()`, `SetStatistics()`

  CreateMaskBand(Band self, int nFlags) → CPLErr

    Add a mask band to the current band. See `GDALRasterBand::CreateMaskBand()`.

    Parameters:

      nFlags (int)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  property DataType

    GDALDataType

    Type:

      DataType

  DeleteNoDataValue(Band self) → CPLErr

    Remove the nodata value for this band.

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  Fill(Band self, double real_fill, double imag_fill=0.0) → CPLErr

    Fill this band with a constant value. See `GDALRasterBand::Fill()`.

    Parameters:

      - real_fill (float) -- real component of the fill value

      - imag_fill (float, default = 0.0) -- imaginary component of the fill value

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  FlushCache(Band self)

    Flush raster data cache. See `GDALRasterBand::FlushCache()`.

  GetActualBlockSize(Band self, int nXBlockOff, int nYBlockOff)

    Fetch the actual block size for a given block offset. See `GDALRasterBand::GetActualBlockSize()`.

    Parameters:

      - nXBlockOff (int) -- the horizontal block offset for which to calculate the number of valid pixels, with zero indicating the left most block, 1 the next block and so forth.

      - nYBlockOff (int) -- the vertical block offset, with zero indicating the top most block, 1 the next block and so forth.

    Returns:

      tuple with the x and y dimensions of the block

    Return type:

      tuple

  GetBand(Band self) → int

    Return the index of this band. See `GDALRasterBand::GetBand()`.

    Returns:

      the (1-based) index of this band

    Return type:

      int

  GetBlockSize(Band self)

    Fetch the natural block size of this band. See `GDALRasterBand::GetBlockSize()`.

    Returns:

      list with the x and y dimensions of a block

    Return type:

      list

  GetCategoryNames(Band self) → char **

    Fetch the list of category names for this raster. See `GDALRasterBand::GetCategoryNames()`.

    Returns:

      A list of category names, or `None`

    Return type:

      list

  GetColorInterpretation(Band self) → GDALColorInterp

    Get the `GDALColorInterp` value for this band. See `GDALRasterBand::GetColorInterpretation()`.

    Return type:

      int

  GetColorTable(Band self) → ColorTable

    Get the color table associated with this band. See `GDALRasterBand::GetColorTable()`.

    Return type:

      ColorTable or `None`

  GetDataCoverageStatus(Band self, int nXOff, int nYOff, int nXSize, int nYSize, int nMaskFlagStop=0) → int

    Determine whether a sub-window of the Band contains only data, only empty blocks, or a mix of both. See `GDALRasterBand::GetDataCoverageStatus()`.

    Parameters:

      - nXOff (int)

      - nYOff (int)

      - nXSize (int)

      - nYSize (int)

      - nMaskFlagStop (int, default=0)

    Returns:

      First value represents a bitwise-or value of the following constants - `gdalconst.GDAL_DATA_COVERAGE_STATUS_DATA` - `gdalconst.GDAL_DATA_COVERAGE_STATUS_EMPTY` - `gdalconst.GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED` Second value represents the approximate percentage in [0, 100] of pixels in the window that have valid values

    Return type:

      list

    Examples

        >>> import numpy as np
        >>> # Create a raster with four blocks
        >>> ds = gdal.GetDriverByName('GTiff').Create('test.tif', 64, 64, options = {'SPARSE_OK':True, 'TILED':True, 'BLOCKXSIZE':32, 'BLOCKYSIZE':32})
        >>> band = ds.GetRasterBand(1)
        >>> # Write some data to upper-left block
        >>> band.WriteArray(np.array([[1, 2], [3, 4]]))
        0
        >>> # Check status of upper-left block
        >>> flags, pct = band.GetDataCoverageStatus(0, 0, 32, 32)
        >>> flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA
        True
        >>> pct
        100.0
        >>> # Check status of upper-right block
        >>> flags, pct = band.GetDataCoverageStatus(32, 0, 32, 32)
        >>> flags == gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY
        True
        >>> pct
        0.0
        >>> # Check status of window touching all four blocks
        >>> flags, pct = band.GetDataCoverageStatus(16, 16, 32, 32)
        >>> flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA | gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY
        True
        >>> pct
        25.0

  GetDataset(Band self) → Dataset

    Fetch the `Dataset` associated with this Band. See `GDALRasterBand::GetDataset()`.

  GetDefaultHistogram(Band self, double * min_ret=None, double * max_ret=None, int * buckets_ret=None, GUIntBig ** ppanHistogram=None, int force=1, GDALProgressFunc callback=0, void * callback_data=None) → CPLErr

    Fetch the default histogram for this band. See `GDALRasterBand::GetDefaultHistogram()`.

    Returns:

      List with the following four elements: - lower bound of histogram - upper bound of histogram - number of buckets in histogram - tuple with counts for each bucket

    Return type:

      list

  GetDefaultRAT(Band self) → RasterAttributeTable
  GetHistogram(Band self, double min=-0.5, double max=255.5, int buckets=256, int include_out_of_range=0, int approx_ok=1, GDALProgressFunc callback=0, void * callback_data=None) → CPLErr

    Compute raster histogram. See `GDALRasterBand::GetHistogram()`.

    Parameters:

      - min (float, default=-0.05) -- the lower bound of the histogram

      - max (float, default=255.5) -- the upper bound of the histogram

      - buckets (int, default=256) -- the number of buckets int he histogram

      - include_out_of_range (bool, default=False) -- if `True`, add out-of-range values into the first and last buckets

      - approx_ok (bool, default=True) -- if `True`, compute an approximate histogram by using subsampling or overviews

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Returns:

      list with length equal to `buckets`. If `approx_ok` is `False`, each the value of each list item will equal the number of pixels in that bucket.

    Return type:

      list

    Examples

        >>> np.random.seed(123)
        >>> ds = gdal.GetDriverByName('MEM').Create('', 10, 10, eType=gdal.GDT_Float32)
        >>> ds.WriteArray(np.random.normal(size=100).reshape(10, 10))
        0
        >>> ds.GetRasterBand(1).GetHistogram(min=-3.5, max=3.5, buckets=13, approx_ok=False)
        [0, 2, 1, 6, 17, 18, 13, 14, 16, 8, 5, 0, 0]

  GetMaskBand(Band self) → Band

    Return the mask band associated with this band. See `GDALRasterBand::GetMaskBand()`.

    Return type:

      Band

  GetMaskFlags(Band self) → int

    Return the status flags of the mask band. See `GDALRasterBand::GetMaskFlags()`.

    Return type:

      int

    Examples

        >>> import numpy as np
        >>> ds = gdal.GetDriverByName('MEM').Create('', 10, 10)
        >>> band = ds.GetRasterBand(1)
        >>> band.GetMaskFlags() == gdal.GMF_ALL_VALID
        True
        >>> band.SetNoDataValue(22)
        0
        >>> band.WriteArray(np.array([[22]]))
        0
        >>> band.GetMaskBand().ReadAsArray(win_xsize=2,win_ysize=2)
        array([[  0, 255],
               [255, 255]], dtype=uint8)
        >>> band.GetMaskFlags() == gdal.GMF_NODATA
        True

  GetMaximum(Band self)

    Fetch a previously stored maximum value for this band. See `GDALRasterBand::GetMaximum()`.

    Returns:

      The stored maximum value, or `None` if no value has been stored.

    Return type:

      float

  GetMinimum(Band self)

    Fetch a previously stored maximum value for this band. See `GDALRasterBand::GetMinimum()`.

    Returns:

      The stored minimum value, or `None` if no value has been stored.

    Return type:

      float

  GetNoDataValue(Band self) → value

    Fetch the nodata value for this band. Unlike `GDALRasterBand::GetNoDataValue()`, this method handles 64-bit integer data types.

    Returns:

      The nodata value, or `None` if it has not been set.

    Return type:

      float or int

  GetNoDataValueAsInt64(Band self)

    Fetch the nodata value for this band. See `GDALRasterBand::GetNoDataValueAsInt64()`.

    Returns:

      The nodata value, or `None` if it has not been set or the data type of this band is not `gdal.GDT_Int64`.

    Return type:

      int

  GetNoDataValueAsUInt64(Band self)

    Fetch the nodata value for this band. See `GDALRasterBand::GetNoDataValueAsUInt64()`.

    Returns:

      The nodata value, or `None` if it has not been set or the data type of this band is not `gdal.GDT_UInt64`.

    Return type:

      int

  GetOffset(Band self)

    Fetch the raster value offset. See `GDALRasterBand::GetOffset()`.

    Returns:

      The offset value, or `0.0`.

    Return type:

      double

  GetOverview(Band self, int i) → Band

    Fetch a raster overview. See `GDALRasterBand::GetOverview()`.

    Parameters:

      i (int) -- Overview index between 0 and `GetOverviewCount() - 1`.

    Return type:

      Band

  GetOverviewCount(Band self) → int

    Return the number of overview layers available. See `GDALRasterBand::GetOverviewCount()`.

    Return type:

      int

  GetRasterCategoryNames(Band self) → char **

    Fetch the list of category names for this band. See `GDALRasterBand::GetCategoryNames()`.

    Returns:

      The list of names, or `None` if no names exist.

    Return type:

      list

  GetRasterColorInterpretation(Band self) → GDALColorInterp

    Return the color interpretation code for this band. See `GDALRasterBand::GetColorInterpretation()`.

    Returns:

      The color interpretation code (default `gdal.GCI_Undefined`)

    Return type:

      int

  GetRasterColorTable(Band self) → ColorTable

    Fetch the color table associated with this band. See `GDALRasterBand::GetColorTable()`.

    Returns:

      The `ColorTable`, or `None` if it has not been defined.

    Return type:

      ColorTable

  GetSampleOverview(Band self, GUIntBig nDesiredSamples) → Band
  GetScale(Band self)

    Fetch the band scale value. See `GDALRasterBand::GetScale()`.

    Returns:

      The scale value, or `1.0`.

    Return type:

      double

  GetStatistics(Band self, int approx_ok, int force) → CPLErr

    Return the minimum, maximum, mean, and standard deviation of all pixel values in this band. See `GDALRasterBand::GetStatistics()`

    Parameters:

      - approx_ok (bool) -- If `True`, allow overviews or a subset of image tiles to be used in computing the statistics.

      - force (bool) -- If `False`, only return a result if it can be obtained without scanning the image, i.e. from pre-existing metadata.

    Returns:

      a list with the min, max, mean, and standard deviation of values in the Band.

    Return type:

      list

    See also

    `ComputeBandStats()`, `ComputeRasterMinMax()`, `GetMaximum()`, `GetMinimum()`, `GetStatistics()`

  GetTiledVirtualMem(Band self, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nTileXSize, int nTileYSize, GDALDataType eBufType, size_t nCacheSize, char ** options=None) → VirtualMem
  GetTiledVirtualMemArray(eAccess=0, xoff=0, yoff=0, xsize=None, ysize=None, tilexsize=256, tileysize=256, datatype=None, cache_size=10485760, options=None)

    Return a NumPy array for the band, seen as a virtual memory mapping with a tile organization. An element is accessed with array[tiley][tilex][y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.

  GetUnitType(Band self) → char const *

    Return a name for the units of this raster's values. See `GDALRasterBand::GetUnitType()`.

    Return type:

      str

    Examples

        >>> ds = gdal.GetDriverByName('MEM').Create('', 10, 10)
        >>> ds.GetRasterBand(1).SetUnitType('ft')
        0
        >>> ds.GetRasterBand(1).GetUnitType()
        'ft'

  GetVirtualMem(Band self, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eBufType, size_t nCacheSize, size_t nPageSizeHint, char ** options=None) → VirtualMem
  GetVirtualMemArray(eAccess=0, xoff=0, yoff=0, xsize=None, ysize=None, bufxsize=None, bufysize=None, datatype=None, cache_size=10485760, page_size_hint=0, options=None)

    Return a NumPy array for the band, seen as a virtual memory mapping. An element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.

  GetVirtualMemAuto(Band self, GDALRWFlag eRWFlag, char ** options=None) → VirtualMem
  GetVirtualMemAutoArray(eAccess=0, options=None)

    Return a NumPy array for the band, seen as a virtual memory mapping. An element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.

  HasArbitraryOverviews(Band self) → bool

    Check for arbitrary overviews. See `GDALRasterBand::HasArbitraryOverviews()`.

    Return type:

      bool

  InterpolateAtGeolocation(*args, **kwargs)

    Return the interpolated value at georeferenced coordinates. See `GDALRasterBand::InterpolateAtGeolocation()`.

    When srs is None, those georeferenced coordinates (geolocX, geolocY) must be in the "natural" SRS of the dataset, that is the one returned by GetSpatialRef() if there is a geotransform, GetGCPSpatialRef() if there are GCPs, WGS 84 if there are RPC coefficients, or the SRS of the geolocation array (generally WGS 84) if there is a geolocation array. If that natural SRS is a geographic one, geolocX must be a longitude, and geolocY a latitude. If that natural SRS is a projected one, geolocX must be a easting, and geolocY a northing.

    When srs is set to a non-None value, (geolocX, geolocY) must be expressed in that CRS, and that tuple must be conformant with the data-axis-to-crs-axis setting of srs, that is the one returned by the `osgeo.osr.SpatialReference.GetDataAxisToSRSAxisMapping()`. If you want to be sure of the axis order, then make sure to call `srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)` before calling this method, and in that case, geolocX must be a longitude or an easting value, and geolocX a latitude or a northing value.

    Parameters:

      - geolocX (float) -- X coordinate of the position where interpolation should be done. Longitude or easting in "natural" CRS if srs is None, otherwise consistent with first axis of srs, taking into account the data-axis-to-crs-axis mapping

      - geolocY (float) -- Y coordinate of the position where interpolation should be done. Latitude or northing in "natural" CRS if srs is None, otherwise consistent with second axis of srs, taking into account the data-axis-to-crs-axis mapping

      - srs (object) -- `osr.SpatialReference`. If set, override the natural CRS in which geolocX, geolocY are expressed

      - interpolation (str) --

        Resampling algorithm to use. One of:

        - `nearest`

        - `bilinear`

        - `cubic`

        - `cubicspline`

    Returns:

      Interpolated value, or `None` if it has any error.

    Return type:

      float

    Examples

        >>> longitude_degree = -117.64
        >>> latitude_degree = 33.90
        >>> with gdal.Open("byte.tif") as ds:
        ...    wgs84_srs = osr.SpatialReference("WGS84")
        ...    wgs84_srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
        ...    ds.GetRasterBand(1).InterpolateAtGeolocation(longitude_degree,                                                                latitude_degree,                                                                wgs84_srs,                                                                gdal.GRIORA_Bilinear)
        135.62  # interpolated value, rtol: 1e-3

  InterpolateAtPoint(*args, **kwargs)

    Return the interpolated value at pixel and line raster coordinates. See `GDALRasterBand::InterpolateAtPoint()`.

    Parameters:

      - pixel (float)

      - line (float)

      - interpolation (str) --

        Resampling algorithm to use. One of:

        - `nearest`

        - `bilinear`

        - `cubic`

        - `cubicspline`

    Returns:

      Interpolated value, or `None` if it has any error.

    Return type:

      float

  IsMaskBand(Band self) → bool

    Returns whether the band is a mask band. See `GDALRasterBand::IsMaskBand()`.

    Return type:

      bool

  ReadAsArray(xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_xsize=None, buf_ysize=None, buf_type=None, buf_obj=None, resample_alg=0, callback=None, callback_data=None)

    Read a window of this raster band into a NumPy array.

    Parameters:

      - xoff (float, default=0) -- The pixel offset to left side of the region of the band to be read. This would be zero to start from the left side.

      - yoff (float, default=0) -- The line offset to top side of the region of the band to be read. This would be zero to start from the top side.

      - win_xsize (float, optional) -- The number of pixels to read in the x direction. By default, equal to the number of columns in the raster.

      - win_ysize (float, optional) -- The number of rows to read in the y direction. By default, equal to the number of bands in the raster.

      - buf_xsize (int, optional) -- The number of columns in the returned array. If not equal to `win_xsize`, the returned values will be determined by `resample_alg`.

      - buf_ysize (int, optional) -- The number of rows in the returned array. If not equal to `win_ysize`, the returned values will be determined by `resample_alg`.

      - buf_type (int, optional) -- The data type of the returned array

      - buf_obj (np.ndarray, optional) -- Optional buffer into which values will be read. If `buf_obj` is specified, then `buf_xsize`/`buf_ysize`/`buf_type` should generally not be specified.

      - resample_alg (int, default = `gdal.GRIORA_NearestNeighbour`.) -- Specifies the resampling algorithm to use when the size of the read window and the buffer are not equal.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Return type:

      np.ndarray

    Examples

        >>> import numpy as np
        >>> ds = gdal.GetDriverByName("GTiff").Create("test.tif", 4, 4, eType=gdal.GDT_Float32)
        >>> ds.WriteArray(np.arange(16).reshape(4, 4))
        0
        >>> band = ds.GetRasterBand(1)
        >>> # Reading an entire band
        >>> band.ReadAsArray()
        array([[ 0.,  1.,  2.,  3.],
               [ 4.,  5.,  6.,  7.],
               [ 8.,  9., 10., 11.],
               [12., 13., 14., 15.]], dtype=float32)
        >>> # Reading a window of a band
        >>> band.ReadAsArray(xoff=2, yoff=2, win_xsize=2, win_ysize=2)
        array([[10., 11.],
               [14., 15.]], dtype=float32)
        >>> # Reading a band into a new buffer at higher resolution
        >>> band.ReadAsArray(xoff=0.5, yoff=0.5, win_xsize=2.5, win_ysize=2.5, buf_xsize=5, buf_ysize=5)
        array([[ 0.,  1.,  1.,  2.,  2.],
               [ 4.,  5.,  5.,  6.,  6.],
               [ 4.,  5.,  5.,  6.,  6.],
               [ 8.,  9.,  9., 10., 10.],
               [ 8.,  9.,  9., 10., 10.]], dtype=float32)
        >>> # Reading a band into an existing buffer at lower resolution
        >>> band.ReadAsArray(buf_xsize=2, buf_ysize=2, buf_type=gdal.GDT_Float64, resample_alg=gdal.GRIORA_Average)
        array([[ 2.5,  4.5],
               [10.5, 12.5]])
        >>> buf = np.zeros((2,2))
        >>> band.ReadAsArray(buf_obj=buf)
        array([[ 5.,  7.],
               [13., 15.]])

  ReadAsMaskedArray(xoff=0, yoff=0, win_xsize=None, win_ysize=None, buf_xsize=None, buf_ysize=None, buf_type=None, resample_alg=0, mask_resample_alg=0, callback=None, callback_data=None)

    Read a window of this raster band into a NumPy masked array.

    Values of the mask will be `True` where pixels are invalid.

    Starting in GDAL 3.11, if resampling (`buf_xsize` != `xsize`, or `buf_ysize` != `ysize`) the mask band will be resampled using the algorithm specified by `mask_resample_alg`.

    See `ReadAsArray()` for a description of additional arguments.

  ReadBlock(Band self, int xoff, int yoff, void * buf_obj=None) → CPLErr
  ReadRaster(xoff=0, yoff=0, xsize=None, ysize=None, buf_xsize=None, buf_ysize=None, buf_type=None, buf_pixel_space=None, buf_line_space=None, resample_alg=0, callback=None, callback_data=None, buf_obj=None)
  ReadRaster1(Band self, double xoff, double yoff, double xsize, double ysize, int * buf_xsize=None, int * buf_ysize=None, GDALDataType * buf_type=None, GIntBig * buf_pixel_space=None, GIntBig * buf_line_space=None, GDALRIOResampleAlg resample_alg=GRIORA_NearestNeighbour, GDALProgressFunc callback=0, void * callback_data=None, void * inputOutputBuf=None) → CPLErr
  SetCategoryNames(Band self, char ** papszCategoryNames) → CPLErr

    Set the category names for this band. See `GDALRasterBand::SetCategoryNames()`.

    Parameters:

      papszCategoryNames (list)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetColorInterpretation(Band self, GDALColorInterp val) → CPLErr

    Set color interpretation of the band See `GDALRasterBand::SetColorInterpretation()`.

    Parameters:

      val (int) -- A color interpretation code such as `gdal.GCI_RedBand`

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetColorTable(Band self, ColorTable arg) → int

    Set the raster color table. See `GDALRasterBand::SetColorTable()`.

    Parameters:

      arg (ColorTable)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetDefaultHistogram(Band self, double min, double max, int buckets_in) → CPLErr

    Set default histogram. See `GDALRasterBand::SetDefaultHistogram()`.

    Parameters:

      - min (float) -- minimum value

      - max (float) -- maximum value

      - buckets_in (list) -- list of pixel counts for each bucket

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

    See also

    `SetHistogram()`

  SetDefaultRAT(Band self, RasterAttributeTable table) → int
  SetNoDataValue(Band self, value)

    Set the nodata value for this band. Unlike `GDALRasterBand::SetNoDataValue()`, this method handles 64-bit integer types.

    Parameters:

      value (float or int) -- The nodata value to set

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  SetNoDataValueAsInt64(Band self, GIntBig v) → CPLErr
  SetNoDataValueAsUInt64(Band self, GUIntBig v) → CPLErr
  SetOffset(Band self, double val) → CPLErr

    Set scaling offset. See `GDALRasterBand::SetOffset()`.

    Parameters:

      val (float)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

    See also

    `SetScale()`

  SetRasterCategoryNames(Band self, char ** names) → CPLErr

    Deprecated. Alternate name for `SetCategoryNames()`.

  SetRasterColorInterpretation(Band self, GDALColorInterp val) → CPLErr

    Deprecated. Alternate name for `SetColorInterpretation()`.

  SetRasterColorTable(Band self, ColorTable arg) → int

    Deprecated. Alternate name for `SetColorTable()`.

  SetScale(Band self, double val) → CPLErr

    Set scaling ratio. See `GDALRasterBand::SetScale()`.

    Parameters:

      val (float)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

    See also

    `SetOffset()`

  SetStatistics(Band self, double min, double max, double mean, double stddev) → CPLErr

    Set statistics on band. See `GDALRasterBand::SetStatistics()`.

    Parameters:

      - min (float)

      - max (float)

      - mean (float)

      - stdev (float)

    Returns:

      `CE_None` on apparent success or `CE_Failure` on failure. This method cannot detect whether metadata will be properly saved and so may return `gdal.`CE_None` even if the statistics will never be saved.

    Return type:

      int

    See also

    `ComputeBandStats()`, `ComputeRasterMinMax()`, `ComputeStatistics()`, `GetMaximum()`, `GetMinimum()`, `GetStatistics()`

  SetUnitType(Band self, char const * val) → CPLErr

    Set unit type. See `GDALRasterBand::SetUnitType()`.

    Parameters:

      val (str)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  WriteArray(array, xoff=0, yoff=0, resample_alg=0, callback=None, callback_data=None)

    Write the contents of a NumPy array to a Band.

    Parameters:

      - array (np.ndarray) -- Two-dimensional array containing values to write

      - xoff (int, default=0) -- The pixel offset to left side of the region of the band to be written. This would be zero to start from the left side.

      - yoff (int, default=0) -- The line offset to top side of the region of the band to be written. This would be zero to start from the top side.

      - resample_alg (int, default = `gdal.GRIORA_NearestNeighbour`) -- Resampling algorithm. Placeholder argument, not currently supported.

      - callback (callable, optional) -- A progress callback function

      - callback_data (any, optional) -- Optional data to be passed to callback function

    Returns:

      Error code, or `gdal.CE_None` if no error occurred.

    Return type:

      int

  WriteRaster(xoff, yoff, xsize, ysize, buf_string, buf_xsize=None, buf_ysize=None, buf_type=None, buf_pixel_space=None, buf_line_space=None)

    Write the contents of a buffer to a dataset.

  property XSize

    int

    Type:

      XSize

  property YSize

    int

    Type:

      YSize

  astype(dt)

    Cast this band to the specified data type

    The data type can be one of the constant of the GDAL `GDT_` enumeration or a numpy dtype.

    The resulting band is lazily evaluated.

osgeo.gdal.RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) → int

osgeo.gdal.RegenerateOverviews(Band srcBand, int overviewBandCount, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) → int

## Band Algebra

class osgeo.gdal.ComputedBand(*args, **kwargs)

  Proxy of C++ GDALComputedRasterBandShadow class.

osgeo.gdal.abs(band)

  Return the absolute value (or module for complex data type) of a raster band or a numpy array.

  The resulting band is lazily evaluated.

osgeo.gdal.log(band)

  Return the natural logarithm of a raster band or a numpy array.

  The resulting band is lazily evaluated.

osgeo.gdal.log10(band)

  Return the logarithm base 10 of a raster band or a numpy array.

  The resulting band is lazily evaluated.

osgeo.gdal.logical_and(x1, x2)

  Perform a logical and between two objects, such objects being a raster band a numpy array or a constant

  The resulting band is lazily evaluated.

osgeo.gdal.logical_or(x1, x2)

  Perform a logical or between two objects, such objects being a raster band a numpy array or a constant

  The resulting band is lazily evaluated.

osgeo.gdal.logical_not(band)

  Perform a logical not on a raster band or a numpy array.

  The resulting band is lazily evaluated.

osgeo.gdal.maximum(*args)

  Return a band whose each pixel value is the maximum of the corresponding pixel values in the input arguments which may be gdal.Band or a numeric constant.

  The resulting band is lazily evaluated.

  Since:

    3.12

osgeo.gdal.mean(*args)

  Return a band whose each pixel value is the arithmetic mean of the corresponding pixel values in the input bands.

  The resulting band is lazily evaluated.

  Since:

    3.12

osgeo.gdal.minimum(*args)

  Return a band whose each pixel value is the minimum of the corresponding pixel values in the input arguments which may be gdal.Band or a numeric constant.

  The resulting band is lazily evaluated.

  Since:

    3.12

osgeo.gdal.pow(x1, x2)

  Raise x1 to the power of x2 between two objects, such objects being a raster band a numpy array or a constant

  The resulting band is lazily evaluated.

osgeo.gdal.sqrt(band)

  Return the square root of a raster band or a numpy array.

  The resulting band is lazily evaluated.

osgeo.gdal.where(cond_band, then_band, else_band)

  Ternary operator. Return a band whose value is then_band if the corresponding pixel in cond_band is not zero, or the one from else_band otherwise.

  cond_band must be a band or convertible to a band. then_band or else_band can be band, convertible to band or numeric constants.

  The resulting band is lazily evaluated.

  Since:

    3.12

## Other

osgeo.gdal.ApplyGeoTransform(double [6] padfGeoTransform, double dfPixel, double dfLine)

  Apply a geotransform to convert a (col, row) location into a georeferenced (x, y) coordinate. To perform the inverse transformation, see `InvGeoTransform()`.

  See `GDALApplyGeoTransform()`.

  Parameters:

    - gt (tuple) -- Geotransform array, as described in Geotransform Tutorial.

    - dfPixel (float) -- (Fractional) column in image coordinates (0.0 at the left edge of the image)

    - dfLine (float) -- (Fractional) row in image coordinates (0.0 at the top of the image)

  Returns:

    x, y values corresponding to the input location

  Return type:

    List

  Examples

      >>> ds = gdal.Open('byte.tif')
      >>> gt = ds.GetGeoTransform()
      >>> gdal.ApplyGeoTransform(gt, 5, 7)
      [441020.0, 3750900.0]

osgeo.gdal.InvGeoTransform(double [6] gt_in) → RETURN_NONE

  Invert a geotransform array so that it represents a conversion from georeferenced (x, y) coordinates to image (col, row) coordinates.

  Parameters:

    gt (tuple) -- Geotransform array, as described in Geotransform Tutorial.

  Returns:

    Geotransform array representing the inverse transformation

  Return type:

    tuple

  Examples

      >>> ds = gdal.Open('byte.tif')
      >>> inv_gt = gdal.InvGeoTransform(ds.GetGeoTransform())
      >>> inv_gt
      (-7345.333333333333, 0.016666666666666666, 0.0, 62522.0, 0.0, -0.016666666666666666)
      >>> gdal.ApplyGeoTransform(inv_gt, 441020, 3750900)
      [5.0, 7.0]

class osgeo.gdal.RasterAttributeTable(*args)

  Proxy of C++ GDALRasterAttributeTableShadow class.

  ChangesAreWrittenToFile(RasterAttributeTable self) → int
  Clone(RasterAttributeTable self) → RasterAttributeTable

    Create a copy of the RAT.

    Returns:

      A Python proxy of a `GDALRasterAttributeTable`

    Return type:

      RasterAttributeTable

  CreateColumn(RasterAttributeTable self, char const * pszName, GDALRATFieldType eType, GDALRATFieldUsage eUsage) → int

    Create a new column in the RAT.

    If the table already has rows, all row values for the new column will be initialized to the default value ('', or zero). The new column is always created as the last column.

    Parameters:

      - pszName (str) -- Name of the new column

      - eType (int) -- Data type of the new column (one of `GFT_Integer`, `GFT_Real`, or `GFT_String`).

      - eUsage (int) -- Usage of the new column (see `GDALRATFieldUsage`)

    Returns:

      `CE_None` on success or `CE_Failure` on failure.

    Return type:

      int

  DumpReadable(RasterAttributeTable self)

    Return an XML representation of the RAT.

    Return type:

      str

  GetColOfUsage(RasterAttributeTable self, GDALRATFieldUsage eUsage) → int

    Return the first column of a specified usage the a RAT.

    See `GDALRasterAttributeTable::GetColOfUsage()`.

    Parameters:

      eUsage (int) -- Usage code such as `gdal.GFU_Red`.

    Returns:

      Index of the column, or -1 if no such column can be found.

    Return type:

      int

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.GetColOfUsage(gdal.GFU_Name)
        2
        >>> rat.GetColOfUsage(gdal.GFU_RedMin)
        -1

  GetColumnCount(RasterAttributeTable self) → int

    Return the number of columns in the RAT.

    See `GDALRasterAttributeTable::GetColumnCount()`.

    Returns:

      The number of columns in the RAT

    Return type:

      int

    Examples

        >>> with gdal.Open('testrat.tif') as ds:
        ...     ds.GetRasterBand(1).GetDefaultRAT().GetColumnCount()
        ...
        9

  GetLinearBinning(RasterAttributeTable self) → bool

    Get linear binning information, if any.

    See `GDALRasterAttributeTable::GetLinearBinning()`.

    Returns:

      a three-element list indicating whether linear binning information is available, the minimum value associated with the smallest bin, and the size of each bin.

    Return type:

      list

  GetNameOfCol(RasterAttributeTable self, int iCol) → char const *

    Get the name of a specified column (0-indexed).

    See `GDALRasterAttributeTable::GetNameOfCol()`.

    Parameters:

      iCol (int) -- The index of the column (starting at 0)

    Returns:

      The name of the column

    Return type:

      str

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> [rat.GetNameOfCol(i) for i in range(rat.GetColumnCount())]
        ['VALUE', 'COUNT', 'CLASS', 'Red', 'Green', 'Blue', 'OtherInt', 'OtherReal', 'OtherStr']

  GetRowCount(RasterAttributeTable self) → int

    Return the number of rows in the RAT.

    See `GDALRasterAttributeTable::GetRowCount()`.

    Returns:

      The number of rows in the RAT

    Return type:

      int

    Examples

        >>> with gdal.Open('testrat.tif') as ds:
        ...     ds.GetRasterBand(1).GetDefaultRAT().GetRowCount()
        ...
        2

  GetRowOfValue(RasterAttributeTable self, double dfValue) → int

    Return the index of the row that applies to a specific value, or -1 of no such row exists.

    See `GDALRasterAttributeTable::GetRowOfValue()`.

    Parameters:

      dfValue (float) -- Value for which a row should be found

    Returns:

      Index of the row (0-based), or -1 of no row was found

    Return type:

      int

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.GetValueAsString(rat.GetRowOfValue(2), 2)
        'my class2'
        >>> rat.GetValueAsString(rat.GetRowOfValue(802), 2)
        ''

    See also

    `SetLinearBinning()`

  GetTableType(RasterAttributeTable self) → GDALRATTableType

    Returns the type of the RAT (`GRTT_THEMATIC` or `GRTT_ATHEMATIC`).

    See `GDALRasterAttributeTable::GetTableType()`.

    Returns:

      table type code

    Return type:

      int

  GetTypeOfCol(RasterAttributeTable self, int iCol) → GDALRATFieldType

    Return the data type of a column in the RAT (one of `GFT_Integer`, `GFT_Real`, or `GFT_String`).

    See `GDALRasterAttributeTable::GetTypeOfCol()`.

    Parameters:

      iCol (int) -- The index of the column (starting at 0)

    Returns:

      type code for the specified column

    Return type:

      int

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.GetTypeOfCol(2) == gdal.GFT_String
        True

  GetUsageOfCol(RasterAttributeTable self, int iCol) → GDALRATFieldUsage

    Return the usage of a column in the RAT.

    See `GDALRasterAttributeTable::GetUsageOfCol()`.

    Parameters:

      iCol (int) -- The index of the column (starting at 0)

    Returns:

      Usage code for the specified column

    Return type:

      int

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> [rat.GetUsageOfCol(i) for i in range(rat.GetColumnCount())]
        [5, 1, 2, 6, 7, 8, 0, 0, 0]
        >>> [rat.GetUsageOfCol(i) == gdal.GFU_Red for i in range(rat.GetColumnCount())]
        [False, False, False, True, False, False, False, False, False]

  GetValueAsBoolean(RasterAttributeTable self, int iRow, int iCol) → bool
  GetValueAsDateTime(iRow, iCol)

    Fetch field value as a datetime.

    The value of the requested column in the requested row is returned as a Python datetime. Besides being called on a GFT_DateTime field, it is also possible to call this method on a string field that contains a ISO-8601 encoded datetime.

    Parameters:

      - iRow (int) -- The index of the row to read (starting at 0)

      - iCol (int) -- The index of the column to read (starting at 0)

    Returns:

      Datetime value, or None if it is invalid

    Return type:

      datetime.datetime

  GetValueAsDouble(RasterAttributeTable self, int iRow, int iCol) → double

    Get the value of a single cell in the RAT.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

  GetValueAsInt(RasterAttributeTable self, int iRow, int iCol) → int

    Get the value of a single cell in the RAT.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

  GetValueAsString(RasterAttributeTable self, int iRow, int iCol) → char const *

    Get the value of a single cell in the RAT.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

  GetValueAsWKBGeometry(RasterAttributeTable self, int iRow, int iCol) → CPLErr
  ReadAsArray(field, start=0, length=None)

    Read a single column of a RAT into a NumPy array.

    Parameters:

      - field (int) -- The index of the column to read (starting at 0)

      - start (int, default = 0) -- The index of the first row to read (starting at 0)

      - length (int, default = None) -- The number of rows to read

    Return type:

      np.ndarray

    Examples

        >>> ds = gdal.Open('clc2018_v2020_20u1.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.ReadAsArray(0)
        array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
               18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
               35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 48], dtype=int32)
        >>> rat.ReadAsArray(0, 5, 3)
        array([6, 7, 8], dtype=int32)

  ReadValuesIOAsBoolean(RasterAttributeTable self, int iField, int iStartRow, int iLength) → CPLErr
  ReadValuesIOAsDouble(RasterAttributeTable self, int iField, int iStartRow, int iLength) → CPLErr

    Read a single column of a RAT into a list of floats.

    Parameters:

      - iField (int) -- The index of the column (starting at 0)

      - iStartRow (int, default = 0) -- The index of the first row to read (starting at 0)

      - iLength (int, default = None) -- The number of rows to read

    Return type:

      list

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.ReadValuesIOAsDouble(3, 0, 2)
        [26.0, 26.0]

    See also

    `ReadAsArray()`

  ReadValuesIOAsInteger(RasterAttributeTable self, int iField, int iStartRow, int iLength) → CPLErr

    Read a single column of a RAT into a list of ints.

    Parameters:

      - iField (int) -- The index of the column (starting at 0)

      - iStartRow (int, default = 0) -- The index of the first row to read (starting at 0)

      - iLength (int, default = None) -- The number of rows to read

    Return type:

      list

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.ReadValuesIOAsInteger(3, 0, 2)
        [26, 26]

    See also

    `ReadAsArray()`

  ReadValuesIOAsString(RasterAttributeTable self, int iField, int iStartRow, int iLength) → CPLErr

    Read a single column of a RAT into a list of strings.

    Parameters:

      - iField (int) -- The index of the column (starting at 0)

      - iStartRow (int, default = 0) -- The index of the first row to read (starting at 0)

      - iLength (int, default = None) -- The number of rows to read

    Return type:

      list

    Examples

        >>> ds = gdal.Open('testrat.tif')
        >>> rat = ds.GetRasterBand(1).GetDefaultRAT()
        >>> rat.ReadValuesIOAsString(2, 0, 2)
        ['my class', 'my class2']

    See also

    `ReadAsArray()`

  RemoveStatistics(RasterAttributeTable self)

    Remove statistics information, such as a histogram, from the RAT.

    See `GDALRasterAttributeTable::RemoveStatistics()`.

  SetLinearBinning(RasterAttributeTable self, double dfRow0Min, double dfBinSize) → int

    Set linear binning information.

    This can be used to provide optimized table look-ups (via `GetRowOfValue()`) when the rows of the table represent uniformly sized bins.

    It is the responsibility of the user to actually define the appropriate bins. If the bins do not correspond to the provided binning information, lookup values will be incorrect.

    See `GDALRasterAttributeTable::SetLinearBinning()`.

    Parameters:

      - dfRow0Min (float) -- Minimum value associated with the smallest bin

      - dfBinSize (float) -- Size of each bin

  SetRowCount(RasterAttributeTable self, int nCount)

    Resizes the table to include the indicated number of rows. Newly created rows will be initialized to '' for strings and zero for numeric fields.

    See `GDALRasterAttributeTable::SetRowCount()`.

    Parameters:

      nCount (int) -- The number of rows in the resized table

  SetTableType(RasterAttributeTable self, GDALRATTableType eTableType)

    Set the type of the RAT (thematic or athematic).

    Parameters:

      eTableType (int) -- Table type (`GRTT_THEMATIC` or `GRTT_ATHEMATIC`)

  SetValueAsBoolean(RasterAttributeTable self, int iRow, int iCol, bool value)
  SetValueAsDateTime(iRow, iCol, dt)

    Set field value from a datetime.

    The indicated field (column) on the indicated row is set from the passed value. The value will be automatically converted for other field types, with a possible loss of precision.

    Parameters:

      - iRow (int) -- The index of the row to read (starting at 0)

      - iCol (int) -- The index of the column to read (starting at 0)

      - dt (datetime.datetime | RATDateTime | None) -- The datetime value

  SetValueAsDouble(RasterAttributeTable self, int iRow, int iCol, double dfValue)

    Set the value of a single cell in the RAT.

    If `iRow` is equal to the number of rows in the table, the table size will be increased by one. However, it is more efficient to call `SetRowCount()` before repeated insertions.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

      - dfValue (float) -- Cell value

  SetValueAsInt(RasterAttributeTable self, int iRow, int iCol, int nValue)

    Set the value of a single cell in the RAT.

    If `iRow` is equal to the number of rows in the table, the table size will be increased by one. However, it is more efficient to call `SetRowCount()` before repeated insertions.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

      - nValue (int) -- Cell value

  SetValueAsString(RasterAttributeTable self, int iRow, int iCol, char const * pszValue)

    Set the value of a single cell in the RAT.

    If `iRow` is equal to the number of rows in the table, the table size will be increased by one. However, it is more efficient to call `SetRowCount()` before repeated insertions.

    Parameters:

      - iRow (int) -- Row index (0-based)

      - iCol (int) -- Column index (0-based)

      - pszValue (str) -- Cell value

  SetValueAsWKBGeometry(RasterAttributeTable self, int iRow, int iCol, int nLen) → CPLErr
  WriteArray(array, field, start=0)

    Write a NumPy array to a single column of a RAT.

    Parameters:

      - array (np.ndarray) -- One-dimensional array of values to write

      - field (int) -- The index of the column to write (starting at 0)

      - start (int, default = 0) -- The index of the first row to write (starting at 0)

    Returns:

      Error code, or `gdal.CE_None` if no error occurred.

    Return type:

      int

class osgeo.gdal.ColorTable(*args, **kwargs)

  Proxy of C++ GDALColorTableShadow class.

  Clone(ColorTable self) → ColorTable
  CreateColorRamp(ColorTable self, int nStartIndex, ColorEntry startcolor, int nEndIndex, ColorEntry endcolor)
  GetColorEntry(ColorTable self, int entry) → ColorEntry
  GetColorEntryAsRGB(ColorTable self, int entry, ColorEntry centry) → int
  GetCount(ColorTable self) → int
  GetPaletteInterpretation(ColorTable self) → GDALPaletteInterp
  SetColorEntry(ColorTable self, int entry, ColorEntry centry)

class osgeo.gdal.ColorEntry(*args, **kwargs)

  Proxy of C++ GDALColorEntry class.

  property c1

    short

    Type:

      c1

  property c2

    short

    Type:

      c2

  property c3

    short

    Type:

      c3

  property c4

    short

    Type:

      c4

class osgeo.gdal.GCP(*args)

  Proxy of C++ GDAL_GCP class.

  property GCPLine

    double

    Type:

      GCPLine

  property GCPPixel

    double

    Type:

      GCPPixel

  property GCPX

    double

    Type:

      GCPX

  property GCPY

    double

    Type:

      GCPY

  property GCPZ

    double

    Type:

      GCPZ

  property Id

    p.char

    Type:

      Id

  property Info

    p.char

    Type:

      Info

  serialize(with_Z=0)