xrspatial.zonal.regions

xrspatial.zonal.regions(raster: xarray.core.dataarray.DataArray, neighborhood: int = 4, name: str = 'regions') xarray.core.dataarray.DataArray[source]

Create unique regions of raster based on pixel value connectivity. Connectivity can be based on either 4 or 8-pixel neighborhoods. Output raster contain a unique int for each connected region.

Parameters
  • raster (xr.DataArray) –

  • connections (int, default=4) – 4 or 8 pixel-based connectivity.

  • name (str, default='regions') – output xr.DataArray.name property.

Returns

regions_agg

Return type

xarray.DataArray

References

Examples

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

from xrspatial import generate_terrain
from xrspatial.zonal import regions

# Generate Example Terrain
W = 500
H = 300

template_terrain = xr.DataArray(np.zeros((H, W)))
x_range=(-20e6, 20e6)
y_range=(-20e6, 20e6)

terrain_agg = generate_terrain(
    template_terrain, x_range=x_range, y_range=y_range
)

# Edit Attributes
terrain_agg = terrain_agg.assign_attrs(
    {
        'Description': 'Example Terrain',
        'units': 'km',
        'Max Elevation': '4000',
    }
)

terrain_agg = terrain_agg.rename({'x': 'lon', 'y': 'lat'})
terrain_agg = terrain_agg.rename('Elevation')

# Create Regions
regions_agg = regions(terrain_agg)

# Edit Attributes
regions_agg = regions_agg.assign_attrs({'Description': 'Example Regions',
                                        'units': ''})
regions_agg = regions_agg.rename('Region Value')

# Plot Terrain (Values)
terrain_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Terrain (Values)")
plt.ylabel("latitude")
plt.xlabel("longitude")

# Plot Regions
regions_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Regions")
plt.ylabel("latitude")
plt.xlabel("longitude")
../../_images/xrspatial-zonal-regions-1_00.png

(png, hires.png, pdf)

../../_images/xrspatial-zonal-regions-1_01.png

(png, hires.png, pdf)

>>> print(terrain_agg[200:203, 200:202])
<xarray.DataArray 'Elevation' (lat: 3, lon: 2)>
array([[1264.02296597, 1261.947921  ],
       [1285.37105519, 1282.48079719],
       [1306.02339636, 1303.4069579 ]])
Coordinates:
* lon      (lon) float64 -3.96e+06 -3.88e+06
* lat      (lat) float64 6.733e+06 6.867e+06 7e+06
Attributes:
    res:            (80000.0, 133333.3333333333)
    Description:    Example Terrain
    units:          km
    Max Elevation:  4000

>>> print(regions_agg[200:203, 200:202])
<xarray.DataArray 'Region Value' (lat: 3, lon: 2)>
array([[39557., 39558.],
       [39943., 39944.],
       [40327., 40328.]])
Coordinates:
* lon      (lon) float64 -3.96e+06 -3.88e+06
* lat      (lat) float64 6.733e+06 6.867e+06 7e+06
Attributes:
    res:            (80000.0, 133333.3333333333)
    Description:    Example Regions
    units:
    Max Elevation:  4000