Skip to content

ratiopath.masks.tile_mask

tile_mask(tiles, tile_extent, size, outline_width=4)

Draws the outlines of tiles into a single-channel mask.

Useful as an overlay that shows which tiles of a slide were used, e.g. after tissue-based filtering. Coordinates and extents are in pixels of the level the mask is drawn at.

Parameters:

Name Type Description Default
tiles DataFrame

A DataFrame with columns x and y, the top-left corner of each tile.

required
tile_extent tuple[int, int]

Width and height of a tile.

required
size tuple[int, int]

Width and height of the mask.

required
outline_width int

Width of the tile outline in pixels.

4

Returns:

Type Description
Image

A mode L image with tile outlines set to 255 and everything else 0.

Examples:

import pandas as pd

from ratiopath.masks import tile_mask

tiles = pd.DataFrame({"x": [0, 512], "y": [0, 0]})
mask = tile_mask(tiles, tile_extent=(512, 512), size=(2048, 1024))
mask.save("tiles.png")
Source code in ratiopath/masks/tile_mask.py
12
13
14
15
16
17
18
19
20
21
22
23
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
def tile_mask(
    tiles: pd.DataFrame,
    tile_extent: tuple[int, int],
    size: tuple[int, int],
    outline_width: int = 4,
) -> Image.Image:
    """Draws the outlines of tiles into a single-channel mask.

    Useful as an overlay that shows which tiles of a slide were used, e.g. after
    tissue-based filtering. Coordinates and extents are in pixels of the level the
    mask is drawn at.

    Args:
        tiles: A DataFrame with columns `x` and `y`, the top-left corner of each tile.
        tile_extent: Width and height of a tile.
        size: Width and height of the mask.
        outline_width: Width of the tile outline in pixels.

    Returns:
        A mode `L` image with tile outlines set to 255 and everything else 0.

    Examples:
        ```python
        import pandas as pd

        from ratiopath.masks import tile_mask

        tiles = pd.DataFrame({"x": [0, 512], "y": [0, 0]})
        mask = tile_mask(tiles, tile_extent=(512, 512), size=(2048, 1024))
        mask.save("tiles.png")
        ```
    """
    mask = Image.new("L", size)
    canvas = ImageDraw.Draw(mask)

    for x, y in tiles[["x", "y"]].itertuples(index=False, name=None):
        canvas.rectangle(
            [x, y, x + tile_extent[0], y + tile_extent[1]],
            outline=255,
            width=outline_width,
        )

    return mask