Skip to content

Windowing

extract_window(raster, center_coords, height, width)

Extract window from raster.

Center coordinate must be inside the raster but window can extent outside the raster in which case padding with raster nodata value is used. Args: raster: Source raster. center_coords: Center coordinates for window in form (x, y). The coordinates should be in the raster's CRS. height: Window height in pixels. width: Window width in pixels.

Returns:

Type Description
ndarray

The extracted raster window.

dict

The updated metadata.

Raises:

Type Description
InvalidParameterValueException

Window size is too small.

CoordinatesOutOfBoundException

Window center coordinates are out of raster bounds.

Source code in eis_toolkit/raster_processing/windowing.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@beartype
def extract_window(
    raster: rasterio.io.DatasetReader,
    center_coords: Tuple[Number, Number],
    height: int,
    width: int,
) -> Tuple[np.ndarray, dict]:
    """Extract window from raster.

       Center coordinate must be inside the raster but window can extent outside the raster in which case padding with
       raster nodata value is used.
    Args:
        raster: Source raster.
        center_coords: Center coordinates for window in form (x, y). The coordinates should be in the raster's CRS.
        height: Window height in pixels.
        width: Window width in pixels.

    Returns:
        The extracted raster window.
        The updated metadata.

    Raises:
        InvalidParameterValueException: Window size is too small.
        CoordinatesOutOfBoundException: Window center coordinates are out of raster bounds.
    """

    if height < 1 or width < 1:
        raise InvalidParameterValueException(f"Window size is too small: {height}, {width}.")

    center_x = center_coords[0]
    center_y = center_coords[1]

    if (
        center_x < raster.bounds.left
        or center_x > raster.bounds.right
        or center_y < raster.bounds.bottom
        or center_y > raster.bounds.top
    ):
        raise CoordinatesOutOfBoundsException("Window center coordinates are out of raster bounds.")

    out_image, out_meta = _extract_window(raster, center_coords, height, width)

    return out_image, out_meta