Skip to content

Clipping

clip_raster(raster, geodataframe)

Clips a raster with polygon geometries.

Parameters:

Name Type Description Default
raster DatasetReader

The raster to be clipped.

required
geodataframe GeoDataFrame

A geodataframe containing the geometries to do the clipping with. Should contain only polygon features.

required

Returns:

Type Description
ndarray

The clipped raster data.

dict

The updated metadata.

Raises:

Type Description
NonMatchingCrsException

The raster and geodataframe are not in the same CRS.

GeometryTypeException

The input geometries contain non-polygon features.

Source code in eis_toolkit/raster_processing/clipping.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@beartype
def clip_raster(raster: rasterio.io.DatasetReader, geodataframe: geopandas.GeoDataFrame) -> Tuple[np.ndarray, dict]:
    """Clips a raster with polygon geometries.

    Args:
        raster: The raster to be clipped.
        geodataframe: A geodataframe containing the geometries to do the clipping with.
            Should contain only polygon features.

    Returns:
        The clipped raster data.
        The updated metadata.

    Raises:
        NonMatchingCrsException: The raster and geodataframe are not in the same CRS.
        GeometryTypeException: The input geometries contain non-polygon features.
    """
    geometries = geodataframe["geometry"]

    if not check_matching_crs(
        objects=[raster, geometries],
    ):
        raise NonMatchingCrsException("The raster and geodataframe are not in the same CRS.")

    if not check_geometry_types(
        geometries=geometries,
        allowed_types=["Polygon", "MultiPolygon"],
    ):
        raise GeometryTypeException("The input geometries contain non-polygon features.")

    out_image, out_meta = _clip_raster(
        raster=raster,
        geometries=geometries,
    )

    return out_image, out_meta