Note
Go to the end to download the full example code.
NumPy interfacing#
This example demonstrates NumPy interfacing with rasters on xarray.DataArray objects with the rst accessor. See NumPy functions and reductions for more details.
We open a raster.
import geoutils as gu
filename_rast = gu.examples.get_path("exploradores_aster_dem")
rast = gu.open_raster(filename_rast)
rast.rst.plot(cmap="terrain")

The NumPy interface allows to use almost any NumPy function directly on the raster.
import numpy as np
# Get the x and y gradient as 1D arrays
gradient_y, gradient_x = np.gradient(rast.values)
# Estimate the orientation in degrees casting to 2D
aspect_values = np.arctan2(-gradient_x, gradient_y)
aspect = rast.copy(data=(aspect_values * 180 / np.pi) + np.pi)
aspect.rst.plot(cmap="twilight", cbar_title="Aspect (degrees)")

Important
For rigorous slope and aspect calculation (matching that of GDAL), check-out our sister package xDEM.
We use NumPy logical operations to isolate the terrain oriented South and above three thousand meters. The rasters will be logically cast to a
boolean xarray.DataArray.
mask = np.logical_and(np.logical_and(aspect > -45, aspect < 45), rast > 3000)
mask
We plot the mask.

Total running time of the script: (0 minutes 1.565 seconds)