xrspatial.focal.focal_stats#
- xrspatial.focal.focal_stats(agg, kernel, stats_funcs=None, name='focal_stats', boundary='nan')[source]#
Calculates statistics of the values within a specified focal neighborhood for each pixel in an input raster. The statistics types are Mean, Maximum, Minimum, Range, Standard deviation, Variation, Sum, and Variety.
- Parameters:
agg (xarray.DataArray) – 2D array of input values to be analysed. Can be a NumPy backed, CuPy backed, Dask with NumPy backed, or Dask with CuPy backed DataArray.
kernel (numpy.array) – 2D binary array where values of 1 indicate the kernel. The kernel is a membership mask, not a weight array; only 0 and 1 are allowed and any other value raises a ValueError. For a weighted convolution use
xrspatial.convolution.convolve_2dinstead.stats_funcs (list of string) – List of statistics types to be calculated. Default set to [‘mean’, ‘max’, ‘min’, ‘range’, ‘std’, ‘var’, ‘sum’, ‘variety’].
'variety'counts the number of distinct non-NaN values in the neighbourhood (useful for categorical rasters).name (str, default='focal_stats') – Output xr.DataArray.name property.
boundary (str, default='nan') – How to handle edges where the kernel extends beyond the raster.
'nan'– fill missing neighbours with NaN (default).'nearest'– repeat edge values.'reflect'– mirror at boundary.'wrap'– periodic / toroidal.
- Returns:
stats_agg – 3D array with dimensions of (stat, y, x) and with values indicating the focal stats.
- Return type:
xarray.DataArray of same type as agg
Examples
>>> import numpy as np >>> import xarray as xr >>> from xrspatial.convolution import circle_kernel >>> kernel = circle_kernel(1, 1, 1) >>> kernel array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]]) >>> data = np.array([ [0, 0, 0, 0, 0, 0], [1, 1, 2, 2, 1, 1], [2, 2, 1, 1, 2, 2], [3, 3, 0, 0, 3, 3], ]) >>> from xrspatial.focal import focal_stats >>> focal_stats(xr.DataArray(data), kernel, stats_funcs=['min', 'sum']) <xarray.DataArray 'focal_stats' (stats: 2, dim_0: 4, dim_1: 6)> array([[[0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.], [1., 1., 0., 0., 1., 1.], [2., 0., 0., 0., 0., 2.]], [[1., 1., 2., 2., 1., 1.], [4., 6., 6., 6., 6., 4.], [8., 9., 6., 6., 9., 8.], [8., 8., 4., 4., 8., 8.]]]) Coordinates: * stats (stats) object 'min' 'sum' Dimensions without coordinates: dim_0, dim_1