Python Raster API

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

Driver

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

Python proxy of a GDALDriver.

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, default = GDT_Byte) -- Raster data type. Set to GDT_Unknown for vector datasets.

  • options (list/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/dict) -- List of driver-specific options

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

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

Return type:

Dataset

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 (dict/list) -- Driver-specific options regarding the creation of the root group.

  • options (list/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'}}
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

Deregister(Driver self)

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

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

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

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().

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()
227
>>> gdal.GetDriverByName('ESRI Shapefile').Deregister()
>>> gdal.GetDriverCount()
226
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().

Return type:

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

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/list) -- 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 (ogr.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().

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::BuildOveriews().

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

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

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

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

Return type:

CE_Failure if an error occurs, otherwise CE_None.

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 GDALDatset::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.

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 (ogr.Layer) -- source layer

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

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

Return type:

ogr.Layer, or None if an error occurs

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 (string) -- the name for the new layer. This should ideally not match any existing layer on the datasource.

  • srs (osr.SpatialReference, default=None) -- the coordinate system to use for the new layer, or None if no coordinate system is available.

  • 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/list, optional) -- Driver-specific dict or list of name=value options

Return type:

ogr.Layer or None on failure.

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/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

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 -- the SQL statement to execute (e.g "SELECT * FROM layer")

  • spatialFilter -- a geometry which represents a spatial filter. Can be None

  • dialect -- 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 -- whether the returned layer should keep a (strong) reference on the current dataset. Cf example 2 for a use case.

Returns:

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

Return type:

ogr.Layer

Examples

  1. Use as a context manager:

>>> with ds.ExecuteSQL("SELECT * FROM layer") as lyr:
...     print(lyr.GetFeatureCount())
  1. Use keep_ref_on_ds=True to return an object that keeps a reference to its dataset:

>>> def get_sql_lyr():
...     return gdal.OpenEx("test.shp").ExecuteSQL("SELECT * FROM test", keep_ref_on_ds=True)
...
... with get_sql_lyr() as lyr:
...     print(lyr.GetFeatureCount())
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.

GetFieldDomain(Dataset self, char const * name) FieldDomain

Get a field domain from its name.

Parameters:

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

Return type:

ogr.FieldDomain, or None if it is not found.

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

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

Parameters:

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

Return type:

list, or None if no field domains are stored in the dataset.

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:

string

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/str) -- Name or 0-based index of the layer to delete.

Return type:

ogr.Layer, or None on error

GetLayerByIndex(Dataset self, int index=0) Layer

Fetch a layer by index.

Parameters:

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

Return type:

ogr.Layer

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

Get the number of layers in this dataset.

Return type:

int

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:

ogr.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

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/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:

osr.SpatialReference

GetStyleTable(Dataset self) StyleTable

Returns dataset style table.

Return type:

ogr.StyleTable

GetSubDatasets()

Return a list of Subdatasets.

Return type:

list

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

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 (function, optional) -- A progress callback function

  • callback_data (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)
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
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 -- 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/osr.SpatialReference) -- spatial reference of the GCPs

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) --

Return type:

CE_Failure if an error occurs, otherwise CE_None.

SetProjection(Dataset self, char const * prj) CPLErr

Set the spatial reference system for this dataset.

See GDALDataset::SetProjection().

Parameters:

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

Return type:

CE_Failure if an error occurs, otherwise CE_None.

SetSpatialRef(Dataset self, SpatialReference srs) CPLErr

Set the spatial reference system for this dataset.

Parameters:

srs (SpatialReference) --

Return type:

CE_Failure if an error occurs, otherwise CE_None.

SetStyleTable(Dataset self, StyleTable table)

Set dataset style table

Parameters:

table (ogr.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

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 datasset capability.

Parameters:

fieldDomain (ogr.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 (function, optional) -- A progress callback function

  • callback_data (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) --

Return type:

Dataset, or None on failure

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/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

Return type:

Dataset, or None on failure.

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) --

Return type:

Dataset, or None on failure

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
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

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

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

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

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

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

  • callback_data (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

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 (function, optional) -- A progress callback function

  • callback_data (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

>>> import numpy as np
>>> 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, 0, 3, 9, 13, 12, 25, 22, 9, 6, 0, 1, 0]  # random
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/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

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

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

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 (function, optional) -- A progress callback function

  • callback_data (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, 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.

See ReadAsArray() for a description of 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) CPLErr

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

Parameters:

value (float/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

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 (function, optional) -- A progress callback function

  • callback_data (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

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

Other

class osgeo.gdal.RasterAttributeTable(*args)

Proxy of C++ GDALRasterAttributeTableShadow class.

ChangesAreWrittenToFile(RasterAttributeTable self) int
Clone(RasterAttributeTable self) RasterAttributeTable
CreateColumn(RasterAttributeTable self, char const * pszName, GDALRATFieldType eType, GDALRATFieldUsage eUsage) int
DumpReadable(RasterAttributeTable self)
GetColOfUsage(RasterAttributeTable self, GDALRATFieldUsage eUsage) int
GetColumnCount(RasterAttributeTable self) int
GetLinearBinning(RasterAttributeTable self) bool
GetNameOfCol(RasterAttributeTable self, int iCol) char const *
GetRowCount(RasterAttributeTable self) int
GetRowOfValue(RasterAttributeTable self, double dfValue) int
GetTableType(RasterAttributeTable self) GDALRATTableType
GetTypeOfCol(RasterAttributeTable self, int iCol) GDALRATFieldType
GetUsageOfCol(RasterAttributeTable self, int iCol) GDALRATFieldUsage
GetValueAsDouble(RasterAttributeTable self, int iRow, int iCol) double
GetValueAsInt(RasterAttributeTable self, int iRow, int iCol) int
GetValueAsString(RasterAttributeTable self, int iRow, int iCol) char const *
ReadAsArray(field, start=0, length=None)
ReadValuesIOAsDouble(RasterAttributeTable self, int iField, int iStartRow, int iLength) CPLErr
ReadValuesIOAsInteger(RasterAttributeTable self, int iField, int iStartRow, int iLength) CPLErr
ReadValuesIOAsString(RasterAttributeTable self, int iField, int iStartRow, int iLength) CPLErr
RemoveStatistics(RasterAttributeTable self)
SetLinearBinning(RasterAttributeTable self, double dfRow0Min, double dfBinSize) int
SetRowCount(RasterAttributeTable self, int nCount)
SetTableType(RasterAttributeTable self, GDALRATTableType eTableType)
SetValueAsDouble(RasterAttributeTable self, int iRow, int iCol, double dfValue)
SetValueAsInt(RasterAttributeTable self, int iRow, int iCol, int nValue)
SetValueAsString(RasterAttributeTable self, int iRow, int iCol, char const * pszValue)
WriteArray(array, field, start=0)
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)