NumPy interfacing

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")
numpy interfacing

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)")
numpy interfacing

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.

<xarray.DataArray (y: 618, x: 539)> Size: 333kB
array([[False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ...,
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], shape=(618, 539))
Coordinates:
  * y            (y) float64 5kB 4.852e+06 4.852e+06 ... 4.834e+06 4.834e+06
  * x            (x) float64 4kB 6.272e+05 6.272e+05 ... 6.433e+05 6.433e+05
    band         int64 8B 1
    spatial_ref  int64 8B 0
Attributes:
    AREA_OR_POINT:             Area
    scale_factor:              1.0
    add_offset:                0.0
    overview_factors:          []
    overview_selected_level:   -1
    overview_selected_factor:  1
    block_shape:               (3, 539)


We plot the mask.

numpy interfacing

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

Gallery generated by Sphinx-Gallery