QGIS raster layer to NumPy array and back

RasterWizard: get the data of a QGIS raster layer as a NumPy array, and the processing result back into QGIS as a new raster layer

The latest version of my QGIS plugin SciPy filters features RasterWizard, a helper class for Python users to quickly get the data of a raster layer as a NumPy array, and the processing result back into QGIS as a new raster layer. This allows for processing with NumPy, SciPy, scikit-image, scikit-learn or other python libraries — and visualizing the results immediately in QGIS. It’s great for prototype development and experimenting with algorithms.

Just open the Python console in QGIS and run something like:

from scipy_filters.helpers import RasterWizard
from scipy import ndimage

wizard = RasterWizard() # Uses active layer if layer is not given
a = wizard.toarray()    # Returns numpy array with all bands

# Any calculation, for example a sobel filter with SciPy
# In the example, the result is a NumPy array with dtype float32
b = ndimage.sobel(a, output="float32") 

# Write the result to a geotiff and load it back into QGIS
wizard.tolayer(b, name="Sobel", filename="/path/to/sobel.tif")

The NumPy array will have the dimensions [bands], x, y. This means you can select a band with e.g. a[0]. Using the option bands_last=True you’ll get x, y, [bands] instead, as expected by scikit-image.

The resulting NumPy array can be loaded back into QGIS as a new raster layer, as long as the number of pixels is the same as the input layer and the geotransform is not changed (no reprojection, no subsetting in NumPy). The number of bands and the datatype can be different.

Getting more info about the raster:

# You can also get pixel values at [x, y]
wizard[0,10] 

# or information like shape, CRS, etc.
wizard.shape   # like numpy_array.shape
wizard.crs_wkt # CRS as WKT string
wizard.crs     # CRS as QgsCoordinateReferenceSystem

The plugin can be installed using “Manage and Install Plugins” in QGIS. For more information, see the API documentation for RasterWizard.