Skip to content

gdf2inst

gdf2inst

gdf2inst(
    gdf: GeoDataFrame,
    xoff: int = 0,
    yoff: int = 0,
    width: int | None = None,
    height: int | None = None,
    reset_index: bool = False,
    id_col: str | None = None,
    transform: Affine | None = None,
) -> np.ndarray

Rasterize instance geometry onto a discrete integer grid.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Instance geometries in the output grid's coordinate units.

required
xoff int

Unit-grid x origin when transform is omitted.

0
yoff int

Unit-grid y origin when transform is omitted.

0
width int | None

Output columns. Inferred from geometry bounds only on the unit grid.

None
height int | None

Output rows. Inferred from geometry bounds only on the unit grid.

None
reset_index bool

Assign IDs 1 through N instead of retaining existing IDs.

False
id_col str | None

Column providing instance IDs; defaults to the frame index and is ignored when reset_index is true.

None
transform Affine | None

Rasterio affine mapping (column, row) pixel corners to geometry coordinates. Requires explicit width/height and zero xoff/yoff. Geometry and transform must use the same units; no CRS conversion occurs.

None

Returns:

Type Description
ndarray

Int32 instance labels with shape (height, width), background zero, and

ndarray

Rasterio's existing pixel-center/edge burning rules. IDs are not interpolated.

Raises:

Type Description
ValueError

If an explicit grid lacks dimensions or also supplies offsets.

TypeError

If empty geometry has no unit-grid output dimensions.

Examples:

>>> from histolytics.data import hgsc_cancer_nuclei
>>> from histolytics.utils.raster import gdf2inst
>>> from skimage.measure import label
>>> from skimage.color import label2rgb
>>> import matplotlib.pyplot as plt
>>>
>>> nuc = hgsc_cancer_nuclei()
>>> # Convert the GeoDataFrame to an instance segmentation raster
>>> nuc_raster = gdf2inst(nuc, xoff=0, yoff=0, width=1500, height=1500)
>>> # Visualize the instance segmentation raster and the GeoDataFrame
>>> fig, ax = plt.subplots(1, 2, figsize=(8, 4))
>>> ax[0].imshow(label2rgb(label(nuc_raster), bg_label=0))
>>> ax[0].set_axis_off()
>>> nuc.plot(column="class_name", ax=ax[1])
>>> ax[1].set_axis_off()
>>> fig.tight_layout()

out

Source code in src/histolytics/utils/raster.py
def gdf2inst(
    gdf: gpd.GeoDataFrame,
    xoff: int = 0,
    yoff: int = 0,
    width: int | None = None,
    height: int | None = None,
    reset_index: bool = False,
    id_col: str | None = None,
    transform: Affine | None = None,
) -> np.ndarray:
    """Rasterize instance geometry onto a discrete integer grid.

    Args:
        gdf: Instance geometries in the output grid's coordinate units.
        xoff: Unit-grid x origin when ``transform`` is omitted.
        yoff: Unit-grid y origin when ``transform`` is omitted.
        width: Output columns. Inferred from geometry bounds only on the unit grid.
        height: Output rows. Inferred from geometry bounds only on the unit grid.
        reset_index: Assign IDs 1 through N instead of retaining existing IDs.
        id_col: Column providing instance IDs; defaults to the frame index and is
            ignored when ``reset_index`` is true.
        transform: Rasterio affine mapping (column, row) pixel corners to geometry
            coordinates. Requires explicit width/height and zero xoff/yoff.
            Geometry and transform must use the same units; no CRS conversion occurs.

    Returns:
        Int32 instance labels with shape (height, width), background zero, and
        Rasterio's existing pixel-center/edge burning rules. IDs are not interpolated.

    Raises:
        ValueError: If an explicit grid lacks dimensions or also supplies offsets.
        TypeError: If empty geometry has no unit-grid output dimensions.

    Examples:
        >>> from histolytics.data import hgsc_cancer_nuclei
        >>> from histolytics.utils.raster import gdf2inst
        >>> from skimage.measure import label
        >>> from skimage.color import label2rgb
        >>> import matplotlib.pyplot as plt
        >>>
        >>> nuc = hgsc_cancer_nuclei()
        >>> # Convert the GeoDataFrame to an instance segmentation raster
        >>> nuc_raster = gdf2inst(nuc, xoff=0, yoff=0, width=1500, height=1500)
        >>> # Visualize the instance segmentation raster and the GeoDataFrame
        >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4))
        >>> ax[0].imshow(label2rgb(label(nuc_raster), bg_label=0))
        >>> ax[0].set_axis_off()
        >>> nuc.plot(column="class_name", ax=ax[1])
        >>> ax[1].set_axis_off()
        >>> fig.tight_layout()
    ![out](../../img/gdf2inst.png)
    """
    if transform is not None:
        if width is None or height is None:
            raise ValueError("An explicit transform requires width and height.")
        if xoff != 0 or yoff != 0:
            raise ValueError(
                "An explicit transform contains its own offsets; use xoff=yoff=0."
            )

    if gdf.empty:
        try:
            return np.zeros((int(height), int(width)), dtype=np.int32)
        except TypeError:
            raise TypeError(
                "Input gdf is empty, trying to return an empty mask but height and width"
                " are not provided. Cannot infer the output shape."
            )

    if transform is None:
        xmin, ymin, xmax, ymax = gdf.total_bounds
        xoff = xoff - xmin
        yoff = yoff - ymin

        if width is None:
            width = int(xmax - xmin)
        if height is None:
            height = int(ymax - ymin)

        geoms = gdf.geometry.translate(xoff=-xmin - xoff, yoff=-ymin - yoff)
        transform = Affine.identity()
    else:
        geoms = gdf.geometry

    if reset_index:
        labels = range(1, len(gdf) + 1)
    else:
        if id_col is not None:
            labels = gdf[id_col].values
        else:
            labels = gdf.index.values

    image_shape = (int(height), int(width))
    shapes = list(zip(geoms, labels))
    out_mask = rasterize(
        shapes,
        out_shape=image_shape,
        fill=0,
        dtype=np.int32,
        transform=transform,
    )

    return out_mask