xrspatial.zonal.regions#

xrspatial.zonal.regions(raster: DataArray, neighborhood: int = 4, name: str = 'regions') 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)

  • neighborhood (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 numpy as np
>>> import xarray as xr
>>> from xrspatial.zonal import regions

>>> # Create a raster with distinct value regions
>>> arr = np.array([[1, 1, 0, 2, 2],
...                 [1, 1, 0, 2, 2],
...                 [0, 0, 0, 0, 0],
...                 [3, 3, 0, 3, 3],
...                 [3, 3, 0, 3, 3]], dtype=np.float64)
>>> raster = xr.DataArray(arr, dims=['y', 'x'])
>>> print(raster.values)
[[1. 1. 0. 2. 2.]
 [1. 1. 0. 2. 2.]
 [0. 0. 0. 0. 0.]
 [3. 3. 0. 3. 3.]
 [3. 3. 0. 3. 3.]]

>>> # With 4-connectivity, each group of connected same-value
>>> # pixels becomes a unique region
>>> result = regions(raster, neighborhood=4)
>>> print(result.values)
[[1. 1. 2. 3. 3.]
 [1. 1. 2. 3. 3.]
 [2. 2. 2. 2. 2.]
 [5. 5. 2. 6. 6.]
 [5. 5. 2. 6. 6.]]

>>> # Note: The two bottom-corner 3-regions are separate because
>>> # they are not connected (the zero-valued cross separates them)
>>> print(f"Number of unique regions: {len(np.unique(result.values))}")
Number of unique regions: 5

>>> # With 8-connectivity, diagonal neighbors also connect regions
>>> diagonal = np.array([[1, 0, 1],
...                      [0, 1, 0],
...                      [1, 0, 1]], dtype=np.float64)
>>> raster_diag = xr.DataArray(diagonal, dims=['y', 'x'])
>>> result_8 = regions(raster_diag, neighborhood=8)
>>> print(result_8.values)
[[1. 2. 1.]
 [2. 1. 2.]
 [1. 2. 1.]]

>>> # All 1s are connected diagonally into one region,
>>> # all 0s form another region
>>> print(f"Number of unique regions: {len(np.unique(result_8.values))}")
Number of unique regions: 2