xrspatial.polygon_clip.clip_polygon#
- xrspatial.polygon_clip.clip_polygon(raster: DataArray, geometry, nodata: float = nan, crop: bool = True, all_touched: bool = False, rasterize_kw: dict | None = None, name: str | None = None) DataArray[source]#
Clip a raster to an arbitrary polygon geometry.
Pixels outside the polygon are set to nodata. When crop is True (the default), the output is also trimmed to the polygon’s bounding box so the result is smaller than the input.
- Parameters:
raster (xr.DataArray) – Input raster to clip. Must be at least 2-D with named
yandxdimensions (last two dimensions).geometry (shapely geometry, list of geometries, GeoDataFrame, or coordinate array) –
The clipping polygon(s). Accepts:
A single
shapely.geometry.PolygonorMultiPolygon.An iterable of shapely polygon geometries (merged via
unary_union).A
GeoDataFrameorGeoSeries(merged viaunary_union).A list of
(x, y)coordinate pairs defining a single polygon ring.
nodata (float, default np.nan) – Value to assign to pixels outside the polygon.
crop (bool, default True) – If True, also trim the output to the bounding box of the polygon. This reduces memory usage for small clip regions within large rasters.
all_touched (bool, default False) – If True, all pixels touched by the polygon boundary are included. If False (default), only pixels whose centre falls inside the polygon are included.
rasterize_kw (dict, optional) – Extra keyword arguments forwarded to
rasterize()when creating the polygon mask.name (str, optional) – Name for the output DataArray. Defaults to the input name.
- Returns:
Clipped raster with the same attributes as raster. The dtype is the input dtype promoted against nodata (e.g. an integer raster clipped with the default
np.nanis returned as float), so the result is identical across the numpy, cupy, dask, and dask+cupy backends.- Return type:
xr.DataArray
Examples
>>> from shapely.geometry import Polygon >>> import xrspatial >>> poly = Polygon([(1, 1), (1, 3), (3, 3), (3, 1)]) >>> clipped = xrspatial.clip_polygon(raster, poly)