Skip to content

gdf2sem

gdf2sem

gdf2sem(
    gdf: GeoDataFrame,
    xoff: int = 0,
    yoff: int = 0,
    class_dict: dict[str, int] | None = None,
    width: int | None = None,
    height: int | None = None,
    transform: Affine | None = None,
) -> np.ndarray

Rasterize semantic geometry onto a discrete integer grid.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Geometries with a class_name column, 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
class_dict dict[str, int] | None

Class-name to integer mapping. Without one, retain the existing pandas categorical-code mapping plus one.

None
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
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 class labels with shape (height, width), background zero, and

ndarray

Rasterio's existing pixel-center/edge burning rules. Classes 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 gdf2sem
>>> import matplotlib.pyplot as plt
>>> from skimage.measure import label
>>> from skimage.color import label2rgb
>>>
>>> nuc = hgsc_cancer_nuclei()
>>> # Convert the GeoDataFrame to an instance segmentation raster
>>> nuc_raster = gdf2sem(nuc, xoff=0, yoff=0, width=1500, height=1500)
>>> # Visualize the semantic segmentation raster and the GeoDataFrame
>>> fig, ax = plt.subplots(1, 2, figsize=(8, 4))
>>> ax[0].imshow(label2rgb(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 gdf2sem(
    gdf: gpd.GeoDataFrame,
    xoff: int = 0,
    yoff: int = 0,
    class_dict: dict[str, int] | None = None,
    width: int | None = None,
    height: int | None = None,
    transform: Affine | None = None,
) -> np.ndarray:
    """Rasterize semantic geometry onto a discrete integer grid.

    Args:
        gdf: Geometries with a class_name column, 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.
        class_dict: Class-name to integer mapping. Without one, retain the existing
            pandas categorical-code mapping plus one.
        width: Output columns. Inferred from geometry bounds only on the unit grid.
        height: Output rows. Inferred from geometry bounds only on the unit grid.
        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 class labels with shape (height, width), background zero, and
        Rasterio's existing pixel-center/edge burning rules. Classes 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 gdf2sem
        >>> import matplotlib.pyplot as plt
        >>> from skimage.measure import label
        >>> from skimage.color import label2rgb
        >>>
        >>> nuc = hgsc_cancer_nuclei()
        >>> # Convert the GeoDataFrame to an instance segmentation raster
        >>> nuc_raster = gdf2sem(nuc, xoff=0, yoff=0, width=1500, height=1500)
        >>> # Visualize the semantic segmentation raster and the GeoDataFrame
        >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4))
        >>> ax[0].imshow(label2rgb(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/gdf2sem.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)

        # Translate geometries to the correct position
        geoms = gdf.geometry.translate(xoff=-xmin - xoff, yoff=-ymin - yoff)
        transform = Affine.identity()
    else:
        geoms = gdf.geometry

    # Map class names to integer labels
    if class_dict is None:
        labels = gdf["class_name"].astype("category").cat.codes + 1
    else:
        labels = gdf["class_name"].map(class_dict).astype(np.int32)

    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