Class: QgsRasterLayer¶
Represents a raster layer.
A QgsRasterLayer
is instantiated by specifying the name of a
data provider, such as “gdal” or “wms”, and a url defining the specific
data set to connect to. The raster layer constructor in turn
instantiates a QgsRasterDataProvider
subclass corresponding
to the provider type, and passes it the url. The data provider connects
to the data source.
Sample usage of the QgsRasterLayer
class:
my_raster_layer = QgsRasterLayer("/path/to/file.tif", "my layer")
Class Hierarchy¶
Base classes¶
Base class for all map layer types. This is the base class for all map layer types (vector, raster). |
|
Interface for classes which can generate elevation profiles. |
Enums
alias of |
Methods
Returns the layer data as a numpy array. |
|
Returns the (possibly NULL) raster attribute table for the given band bandNumber. |
|
Returns the number of attribute tables for the raster by counting the number of bands that have an associated attribute table. |
|
Returns the number of bands in this layer. |
|
Returns the name of a band given its number. |
|
Returns the raster's brightness/contrast filter. |
|
Returns |
|
Returns a new instance equivalent to this one. |
|
Returns the source data provider. |
|
Returns the source data provider. |
|
This is an overloaded version of the |
|
Returns the height of the (unclipped) raster. |
|
Returns the raster's hue/saturation filter. |
|
If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the data provider. |
|
Returns a list with classification items (Text and color). |
|
Returns a 100x100 pixmap of the color palette. |
|
Returns the raster pipe. |
|
Draws a preview of the rasterlayer into a QImage |
|
Returns the raster layer type (which is a read only property). |
|
Returns the number of raster units per each raster pixel in X axis. |
|
Returns the number of raster units per each raster pixel in Y axis. |
|
Returns the raster's renderer. |
|
Returns the raster's resample filter. |
|
Returns which stage of the pipe should apply resampling. |
|
Set contrast enhancement algorithm |
|
Set the data provider. |
|
Sets the default contrast enhancement |
|
Sets the raster's renderer. |
|
Select which stage of the pipe should apply resampling. |
|
Sets the string (typically sql) used to define a subset of the layer |
|
Returns the string (typically sql) used to define a subset of the layer. |
|
Returns the width of the (unclipped) raster. |
|
Writes the symbology of the layer into the document provided in SLD 1.0.0 format |
Static Methods
This helper checks to see whether the file name appears to be a valid raster file name. |
|
Returns time stamp for given file name |
Signals
Emitted when the layer's subset string has changed. |
Attributes
Default enhancement algorithm for multiple band raster of type different from Byte |
|
Default enhancement limits for multiple band raster of type different from Byte |
|
Default enhancement algorithm for multiple band raster of type Byte |
|
Default enhancement limits for multiple band raster of type Byte |
|
Default sample size (number of pixels) for estimated statistics/histogram calculation |
|
Default enhancement algorithm for single band raster |
|
Default enhancement limits for single band raster |
- class qgis.core.QgsRasterLayer[source]¶
Bases:
QgsMapLayer
,QgsAbstractProfileSource
- __init__()
Constructor. Provider is not set.
- __init__(uri: str | None, baseName: str | None = '', providerType: str | None = '', options: QgsRasterLayer.LayerOptions = QgsRasterLayer.LayerOptions())
This is the constructor for the RasterLayer class.
The main tasks carried out by the constructor are:
Load the rasters default style (.qml) file if it exists
Populate the RasterStatsVector with initial values for each band.
Calculate the layer extents
Determine whether the layer is gray, paletted or multiband.
Assign sensible defaults for the red, green, blue and gray bands.
- Parameters:
uri (Optional[str])
baseName (Optional[str] = '')
providerType (Optional[str] = '')
options (QgsRasterLayer.LayerOptions = QgsRasterLayer.LayerOptions())
- class LayerOptions¶
Bases:
object
Setting options for loading raster layers.
- skipCrsValidation¶
Controls whether the layer is allowed to have an invalid/unknown CRS.
If
True
, then no validation will be performed on the layer’s CRS and the layer layer’scrs()
may beinvalid()
(i.e. the layer will have no georeferencing available and will be treated as having purely numerical coordinates).If
False
(the default), the layer’s CRS will be validated usingQgsCoordinateReferenceSystem.validate()
, which may cause a blocking, user-facing dialog asking users to manually select the correct CRS for the layer.Added in version 3.10.
- LayerType¶
alias of
RasterLayerType
- MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM = 1¶
Default enhancement algorithm for multiple band raster of type different from Byte
- MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS = 3¶
Default enhancement limits for multiple band raster of type different from Byte
- MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM = 0¶
Default enhancement algorithm for multiple band raster of type Byte
- MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS = 1¶
Default enhancement limits for multiple band raster of type Byte
- SAMPLE_SIZE = 250000.0¶
Default sample size (number of pixels) for estimated statistics/histogram calculation
- SINGLE_BAND_ENHANCEMENT_ALGORITHM = 1¶
Default enhancement algorithm for single band raster
- SINGLE_BAND_MIN_MAX_LIMITS = 1¶
Default enhancement limits for single band raster
- as_numpy(use_masking=True, bands: List[int] | None = None) List[ndarray | MaskedArray] ¶
Returns the layer data as a numpy array.
If use_masking is True then the returned arrays will be numpy masked arrays, masking the raster block’s nodata values.
If bands is provided, only the specified bands will be included in the returned array; otherwise, all bands will be used.
- Raises:
QgsNotSupportedException – if numpy is not available on the system
Added in version 3.40.
- attributeTable(self, bandNumber: int) QgsRasterAttributeTable | None [source]¶
Returns the (possibly NULL) raster attribute table for the given band
bandNumber
.Added in version 3.30.
- Parameters:
bandNumber (int)
- Return type:
Optional[QgsRasterAttributeTable]
- attributeTableCount(self) int [source]¶
Returns the number of attribute tables for the raster by counting the number of bands that have an associated attribute table.
Added in version 3.30.
- Return type:
int
- bandName(self, bandNoInt: int) str [source]¶
Returns the name of a band given its number.
- Parameters:
bandNoInt (int)
- Return type:
str
- brightnessFilter(self) QgsBrightnessContrastFilter | None [source]¶
Returns the raster’s brightness/contrast filter.
See also
See also
- Return type:
Optional[QgsBrightnessContrastFilter]
- canCreateRasterAttributeTable(self) bool [source]¶
Returns
True
if the raster renderer is suitable for creation of a raster attribute table. The supported renderers areQgsPalettedRasterRenderer
andQgsSingleBandPseudoColorRenderer
.Added in version 3.30.
- Return type:
bool
- clone(self) QgsRasterLayer | None [source]¶
Returns a new instance equivalent to this one. A new provider is created for the same data source and renderer is cloned too.
- Return type:
Optional[QgsRasterLayer]
- Returns:
a new layer instance
- constDataProvider(self) QgsRasterDataProvider | None ¶
Returns the source data provider.
This will be
None
if the layer is invalid.- Return type:
Optional[QgsRasterDataProvider]
- dataProvider(self) QgsRasterDataProvider | None [source]¶
Returns the source data provider.
This will be
None
if the layer is invalid.- Return type:
Optional[QgsRasterDataProvider]
- draw(self, theQPainter: QPainter | None, myRasterViewPort: QgsRasterViewPort | None, qgsMapToPixel: QgsMapToPixel | None = None)[source]¶
This is an overloaded version of the
draw()
function that is called by bothdraw()
and thumbnailAsPixmap- Parameters:
theQPainter (Optional[QPainter])
myRasterViewPort (Optional[QgsRasterViewPort])
qgsMapToPixel (Optional[QgsMapToPixel] = None)
- hueSaturationFilter(self) QgsHueSaturationFilter | None [source]¶
Returns the raster’s hue/saturation filter.
See also
See also
- Return type:
Optional[QgsHueSaturationFilter]
- ignoreExtents(self) bool [source]¶
If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the data provider. To be used for example for WMS layers with labels or symbology that happens to be drawn outside the data extent.
Added in version 3.10.
- Return type:
bool
- static isValidRasterFileName(fileNameQString: str | None, retError: str | None) bool [source]¶
This helper checks to see whether the file name appears to be a valid raster file name. If the file name looks like it could be valid, but some sort of error occurs in processing the file, the error is returned in
retError
.- Parameters:
fileNameQString (Optional[str])
retError (Optional[str])
- Return type:
bool
- static isValidRasterFileName(fileNameQString: str | None) bool [source]
- Parameters:
fileNameQString (Optional[str])
- Return type:
bool
- static lastModified(name: str | None) QDateTime [source]¶
Returns time stamp for given file name
- Parameters:
name (Optional[str])
- Return type:
QDateTime
- legendSymbologyItems(self) List[Tuple[str, QColor]] [source]¶
Returns a list with classification items (Text and color).
Deprecated since version 3.40: Use
QgsRasterRenderer.createLegendNodes()
instead.- Return type:
List[Tuple[str, QColor]]
- paletteAsPixmap(self, bandNumber: int = 1) QPixmap [source]¶
Returns a 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned
- Parameters:
bandNumber (int = 1) – the number of the band to use for generating a pixmap of the associated palette
- Return type:
QPixmap
- pipe(self) QgsRasterPipe | None [source]¶
Returns the raster pipe.
- Return type:
Optional[QgsRasterPipe]
- previewAsImage(self, size: QSize, bgColor: QColor | Qt.GlobalColor = Qt.white, format: QImage.Format = QImage.Format_ARGB32_Premultiplied) QImage [source]¶
Draws a preview of the rasterlayer into a QImage
- Parameters:
size (QSize)
bgColor (Union[QColor, Qt.GlobalColor] = Qt.white)
format (QImage.Format = QImage.Format_ARGB32_Premultiplied)
- Return type:
QImage
- rasterType(self) Qgis.RasterLayerType [source]¶
Returns the raster layer type (which is a read only property).
- Return type:
- rasterUnitsPerPixelX(self) float [source]¶
Returns the number of raster units per each raster pixel in X axis.
In a world file, this is normally the first row (without the sign). (E.g. the value reported by the GDAL geotransform[1]).
Note
If the
dataProvider()
does not have native size/resolution then 1 will be returned.QgsRasterDataProvider.capabilities()
can be used to test for theQgis
.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.See also
- Return type:
float
- rasterUnitsPerPixelY(self) float [source]¶
Returns the number of raster units per each raster pixel in Y axis.
In a world file, this is normally the first row (without the sign).
Note
If the
dataProvider()
does not have native size/resolution then 1 will be returned.QgsRasterDataProvider.capabilities()
can be used to test for theQgis
.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.See also
- Return type:
float
- renderer(self) QgsRasterRenderer | None [source]¶
Returns the raster’s renderer.
See also
- Return type:
Optional[QgsRasterRenderer]
- resampleFilter(self) QgsRasterResampleFilter | None [source]¶
Returns the raster’s resample filter.
See also
See also
- Return type:
Optional[QgsRasterResampleFilter]
- resamplingStage(self) Qgis.RasterResamplingStage [source]¶
Returns which stage of the pipe should apply resampling.
See also
Added in version 3.16.
- Return type:
- setContrastEnhancement(self, algorithm: QgsContrastEnhancement.ContrastEnhancementAlgorithm, limits: QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax, extent: QgsRectangle = QgsRectangle(), sampleSize: int = QgsRasterLayer.SAMPLE_SIZE, generateLookupTableFlag: bool = True)[source]¶
Set contrast enhancement algorithm
- Parameters:
algorithm (QgsContrastEnhancement.ContrastEnhancementAlgorithm) – Contrast enhancement algorithm
limits (QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax) – Limits
extent (
QgsRectangle
= QgsRectangle()) – Extent used to calculate limits, if empty, use full layer extentsampleSize (int = QgsRasterLayer.SAMPLE_SIZE) – Size of data sample to calculate limits, if 0, use full resolution
generateLookupTableFlag (bool = True) – Generate lookup table.
- setDataProvider(self, provider: str | None)[source]¶
Set the data provider.
Deprecated since version 3.40: Use the version with ProviderOptions instead.
- Parameters:
provider (Optional[str])
- setDataProvider(self, provider: str | None, options: QgsDataProvider.ProviderOptions, flags: Qgis.DataProviderReadFlags | Qgis.DataProviderReadFlag = Qgis.DataProviderReadFlags())[source]
Set the data provider.
- Parameters:
provider (Optional[str]) – provider key string, must match a valid
QgsRasterDataProvider
key. E.g. “gdal”, “wms”, etc.options (QgsDataProvider.ProviderOptions) – provider options
flags (Union[Qgis.DataProviderReadFlags, Qgis.DataProviderReadFlag] = Qgis.DataProviderReadFlags()) – provider flags since QGIS 3.16
Added in version 3.2.
- setRenderer(self, renderer: QgsRasterRenderer | None)[source]¶
Sets the raster’s
renderer
. Takes ownership of the renderer object.See also
- Parameters:
renderer (Optional[QgsRasterRenderer])
- setResamplingStage(self, stage: Qgis.RasterResamplingStage)[source]¶
Select which stage of the pipe should apply resampling.
See also
Added in version 3.16.
- Parameters:
stage (Qgis.RasterResamplingStage)
- setSubsetString(self, subset: str | None) bool [source]¶
Sets the string (typically sql) used to define a subset of the layer
- Parameters:
subset (Optional[str]) – The subset string. This may be the where clause of a sql statement or other definition string specific to the underlying dataprovider and data store.
- Return type:
bool
- Returns:
True
, when setting the subset string was successful,False
otherwise
Added in version 3.12.
- subsetString(self) str [source]¶
Returns the string (typically sql) used to define a subset of the layer.
- Return type:
str
- Returns:
The subset string or null QString if not implemented by the provider
Added in version 3.12.
- signal subsetStringChanged[source]¶
Emitted when the layer’s subset string has changed.
Added in version 3.12.
- writeSld(self, node: QDomNode, doc: QDomDocument, errorMessage: str | None, props: Dict[str, Any] = {}) bool [source]¶
Writes the symbology of the layer into the document provided in SLD 1.0.0 format
- Parameters:
node (QDomNode) – the node that will have the style element added to it.
doc (QDomDocument) – the document that will have the QDomNode added.
errorMessage (Optional[str]) – reference to string that will be updated with any error messages
props (Dict[str, Any] = {}) – a open ended set of properties that can drive/inform the SLD encoding
- Return type:
bool
- Returns:
True
in case of success
Added in version 3.6.