Skip to content

Drawing on images

from interactive_pipe import draw — pure functions drawing detections, keypoints, regions and labels on a copy of an image, keeping its dtype and range. See Figures, heatmaps & overlays for the conventions (coordinates, colours, speed).

Draw marks on images: points, boxes, lines, polygons, text and masks.

Small and dependency-free (numpy + Pillow, both required by interactive_pipe; OpenCV is not needed). Meant to be called inside a filter::

from interactive_pipe import draw

@interactive(threshold=(0.5, [0.0, 1.0]))
def detect(img, threshold=0.5):
    boxes = find_boxes(img, threshold)          # (N, 4) x0, y0, x1, y1
    return draw.boxes(img, boxes, labels=[f"{s:.2f}" for s in scores])

Conventions shared by every function:

  • Pure: the input image is never modified (pipeline inputs are read-only views); a new array is returned.
  • dtype and range kept: float images (values in [0, 1]), uint8 (0-255) and uint16 (0-65535) come back with the same dtype and range. Only the marked pixels change.
  • Channels: RGB and RGBA images keep their channels (an RGBA image gets an opaque alpha where it is marked); grayscale (H, W) / (H, W, 1) images are promoted to (H, W, 3) RGB, since marks are coloured.
  • Coordinates: pixels, (x, y) order (x = column, y = row, origin at the top-left corner), sub-pixel values accepted. Marks partly or entirely outside the image are clipped, never an error; items with NaN coordinates are skipped.
  • Colours: a name ("red", "tab:blue"), a hex string ("#ff8800"), an (r, g, b) tuple of floats in [0, 1] (or of ints in 0-255 when a value is above 1). color=None gives each item its own colour from DEFAULT_COLORS (matplotlib's tab10 cycle); a list of colours is used per item (cycled when shorter).

DEFAULT_COLORS module-attribute

DEFAULT_COLORS: List[Tuple[float, float, float]] = [(0.122, 0.467, 0.706), (1.0, 0.498, 0.055), (0.173, 0.627, 0.173), (0.839, 0.153, 0.157), (0.58, 0.404, 0.741), (0.549, 0.337, 0.294), (0.89, 0.467, 0.761), (0.498, 0.498, 0.498), (0.737, 0.741, 0.133), (0.09, 0.745, 0.812)]

points

points(img: ndarray, xy: Any, color: ColorArg = None, radius: float = 3.0, labels: Optional[Sequence[Any]] = None, filled: bool = True, width: float = 1.0, text_size: Optional[float] = None) -> np.ndarray

Draw points (discs, or circles with filled=False) at xy.

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
xy Any

one (x, y) pair or an (N, 2) array of them, in pixels.

required
color ColorArg

one colour, a list (one per point) or None for the colour cycle.

None
radius float

disc radius in pixels (a radius below 1 marks a single pixel).

3.0
labels Optional[Sequence[Any]]

optional text per point, drawn on the right of the point.

None
filled bool

discs (True) or circle outlines of width pixels (False).

True
text_size Optional[float]

label height in pixels (default from the image size).

None

Returns:

Type Description
ndarray

A new image with the points drawn.

Source code in src/interactive_pipe/draw.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def points(
    img: np.ndarray,
    xy: Any,
    color: ColorArg = None,
    radius: float = 3.0,
    labels: Optional[Sequence[Any]] = None,
    filled: bool = True,
    width: float = 1.0,
    text_size: Optional[float] = None,
) -> np.ndarray:
    """Draw points (discs, or circles with ``filled=False``) at ``xy``.

    Args:
        img: image (not modified).
        xy: one ``(x, y)`` pair or an ``(N, 2)`` array of them, in pixels.
        color: one colour, a list (one per point) or None for the colour cycle.
        radius: disc radius in pixels (a radius below 1 marks a single pixel).
        labels: optional text per point, drawn on the right of the point.
        filled: discs (True) or circle outlines of ``width`` pixels (False).
        text_size: label height in pixels (default from the image size).

    Returns:
        A new image with the points drawn.
    """
    canvas = _Canvas(img)
    pts = _as_points(xy)
    colors = _colors(color, len(pts))
    texts = _labels(labels, len(pts))
    line_width = _check_width(width)
    label_size = canvas.text_size(text_size)
    for (x, y), rgb, label in zip(pts, colors, texts):
        if not _finite(x, y):
            continue
        fill = canvas.rgba(rgb)
        if radius < 1.0:
            canvas.draw.point((x, y), fill=fill)
        elif filled:
            canvas.draw.ellipse([x - radius, y - radius, x + radius, y + radius], fill=fill)
        else:
            canvas.draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=fill, width=line_width)
        if label:
            canvas.label(label, (x + max(radius, 1.0) + 3, y), rgb, label_size, anchor="lm")
    return canvas.result()

boxes

boxes(img: ndarray, boxes: Any, labels: Optional[Sequence[Any]] = None, color: ColorArg = None, width: float = 2.0, fmt: str = 'xyxy', text_size: Optional[float] = None) -> np.ndarray

Draw rectangles.

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
boxes Any

one box or an (N, 4) array. fmt="xyxy" (default): (x0, y0, x1, y1), opposite corners in pixels; fmt="xywh": (x0, y0, width, height).

required
labels Optional[Sequence[Any]]

optional text per box, drawn on a filled tag above the box (inside it when the box touches the top of the image).

None
color ColorArg

one colour, a list (one per box) or None for the colour cycle.

None
width float

line width in pixels.

2.0
fmt str

"xyxy" or "xywh".

'xyxy'
text_size Optional[float]

label height in pixels (default from the image size).

None

Returns:

Type Description
ndarray

A new image with the boxes drawn.

Source code in src/interactive_pipe/draw.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def boxes(
    img: np.ndarray,
    boxes: Any,
    labels: Optional[Sequence[Any]] = None,
    color: ColorArg = None,
    width: float = 2.0,
    fmt: str = "xyxy",
    text_size: Optional[float] = None,
) -> np.ndarray:
    """Draw rectangles.

    Args:
        img: image (not modified).
        boxes: one box or an ``(N, 4)`` array. ``fmt="xyxy"`` (default):
            ``(x0, y0, x1, y1)``, opposite corners in pixels; ``fmt="xywh"``:
            ``(x0, y0, width, height)``.
        labels: optional text per box, drawn on a filled tag above the box
            (inside it when the box touches the top of the image).
        color: one colour, a list (one per box) or None for the colour cycle.
        width: line width in pixels.
        fmt: ``"xyxy"`` or ``"xywh"``.
        text_size: label height in pixels (default from the image size).

    Returns:
        A new image with the boxes drawn.
    """
    if fmt not in ("xyxy", "xywh"):
        raise ValueError(f"fmt must be 'xyxy' or 'xywh', got {fmt!r}")
    canvas = _Canvas(img)
    array = np.asarray(boxes, dtype=np.float64)
    if array.size == 0:
        array = np.zeros((0, 4))
    if array.ndim == 1:
        array = array[None, :]
    if array.ndim != 2 or array.shape[1] != 4:
        raise ValueError(f"boxes must be a 4-value box or an (N, 4) array, got shape {array.shape}")
    array = array.copy()
    if fmt == "xywh":
        array[:, 2:] += array[:, :2]
    array = np.clip(array, -_COORD_LIMIT, _COORD_LIMIT)
    colors = _colors(color, len(array))
    texts = _labels(labels, len(array))
    line_width = _check_width(width)
    label_size = canvas.text_size(text_size)
    for (x0, y0, x1, y1), rgb, label in zip(array, colors, texts):
        if not _finite(x0, y0, x1, y1):
            continue
        x0, x1 = min(x0, x1), max(x0, x1)
        y0, y1 = min(y0, y1), max(y0, y1)
        canvas.draw.rectangle([x0, y0, x1, y1], outline=canvas.rgba(rgb), width=line_width)
        if label:
            if y0 - label_size - 2 >= 0:
                canvas.label(label, (max(x0, 0.0), y0 - 1), rgb, label_size, anchor="lb")
            else:  # no room above: inside the top-left corner (kept in the image)
                inside = (max(x0, 0.0) + line_width, max(y0, 0.0) + line_width + 1)
                canvas.label(label, inside, rgb, label_size, anchor="lt")
    return canvas.result()

lines

lines(img: ndarray, lines: Any, color: ColorArg = None, width: float = 2.0, closed: bool = False) -> np.ndarray

Draw polylines or segments.

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
lines Any

one polyline (M, 2) ((x, y) vertices), a (K, M, 2) array — (K, 2, 2) is K segments — or a list of polylines of different lengths.

required
color ColorArg

one colour, a list (one per polyline) or None for the colour cycle.

None
width float

line width in pixels.

2.0
closed bool

join the last vertex back to the first.

False

Returns:

Type Description
ndarray

A new image with the lines drawn.

Source code in src/interactive_pipe/draw.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def lines(
    img: np.ndarray,
    lines: Any,
    color: ColorArg = None,
    width: float = 2.0,
    closed: bool = False,
) -> np.ndarray:
    """Draw polylines or segments.

    Args:
        img: image (not modified).
        lines: one polyline ``(M, 2)`` (``(x, y)`` vertices), a ``(K, M, 2)``
            array — ``(K, 2, 2)`` is K segments — or a list of polylines of
            different lengths.
        color: one colour, a list (one per polyline) or None for the colour cycle.
        width: line width in pixels.
        closed: join the last vertex back to the first.

    Returns:
        A new image with the lines drawn.
    """
    canvas = _Canvas(img)
    polylines = _as_polylines(lines, "lines")
    colors = _colors(color, len(polylines))
    line_width = _check_width(width)
    for polyline, rgb in zip(polylines, colors):
        vertices = [(float(x), float(y)) for x, y in polyline if _finite(x, y)]
        if len(vertices) < 2:
            continue
        if closed and len(vertices) > 2:
            vertices.append(vertices[0])
        canvas.draw.line(vertices, fill=canvas.rgba(rgb), width=line_width, joint="curve" if line_width > 2 else None)
    return canvas.result()

polygon

polygon(img: ndarray, polygons: Any, color: ColorArg = None, width: float = 2.0, fill_alpha: float = 0.0) -> np.ndarray

Draw closed polygons, optionally filled with a translucent colour.

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
polygons Any

one polygon (M, 2) ((x, y) vertices, M >= 3), a (K, M, 2) array or a list of polygons.

required
color ColorArg

one colour, a list (one per polygon) or None for the colour cycle.

None
width float

outline width in pixels (0: no outline, only the fill).

2.0
fill_alpha float

opacity of the fill, 0 (outline only, default) to 1.

0.0

Returns:

Type Description
ndarray

A new image with the polygons drawn.

Source code in src/interactive_pipe/draw.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def polygon(
    img: np.ndarray,
    polygons: Any,
    color: ColorArg = None,
    width: float = 2.0,
    fill_alpha: float = 0.0,
) -> np.ndarray:
    """Draw closed polygons, optionally filled with a translucent colour.

    Args:
        img: image (not modified).
        polygons: one polygon ``(M, 2)`` (``(x, y)`` vertices, M >= 3), a
            ``(K, M, 2)`` array or a list of polygons.
        color: one colour, a list (one per polygon) or None for the colour cycle.
        width: outline width in pixels (0: no outline, only the fill).
        fill_alpha: opacity of the fill, 0 (outline only, default) to 1.

    Returns:
        A new image with the polygons drawn.
    """
    if not 0.0 <= fill_alpha <= 1.0:
        raise ValueError(f"fill_alpha must be in [0, 1], got {fill_alpha}")
    if width < 0:
        raise ValueError(f"width must be >= 0, got {width}")
    canvas = _Canvas(img)
    shapes = _as_polylines(polygons, "polygons")
    colors = _colors(color, len(shapes))
    for shape, rgb in zip(shapes, colors):
        vertices = [(float(x), float(y)) for x, y in shape if _finite(x, y)]
        if len(vertices) < 3:
            continue
        if fill_alpha > 0:
            canvas.draw.polygon(vertices, fill=canvas.rgba(rgb, fill_alpha))
        if width > 0:
            outline = vertices + [vertices[0]]
            canvas.draw.line(outline, fill=canvas.rgba(rgb), width=_check_width(width), joint="curve")
    return canvas.result()

text

text(img: ndarray, text: Union[str, Sequence[str]], xy: Any, color: ColorArg = 'white', size: Optional[float] = None, anchor: str = 'top-left', outline: Optional[Color] = 'black', background: Optional[Color] = None, background_alpha: float = 0.6) -> np.ndarray

Write text, readable on any image.

By default the text is white with a thin black outline, readable on dark and bright areas alike; background=<colour> puts it on a translucent box instead (outline=None to drop the outline).

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
text Union[str, Sequence[str]]

one string, or a list of strings (one per position in xy).

required
xy Any

(x, y) of the anchor point, or an (N, 2) array.

required
color ColorArg

text colour (one, a list, or None for the colour cycle).

'white'
size Optional[float]

text height in pixels (default from the image size, >= 12).

None
anchor str

which point of the text sits at xy: "top-left" (default), "top", "top-right", "left", "center", "right", "bottom-left", "bottom", "bottom-right", or a Pillow anchor such as "ls" (left, baseline).

'top-left'
outline Optional[Color]

colour of the outline around the letters, None for none.

'black'
background Optional[Color]

colour of a box behind the text, None for none.

None
background_alpha float

opacity of that box.

0.6

Returns:

Type Description
ndarray

A new image with the text written. Multi-line strings are supported.

Source code in src/interactive_pipe/draw.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def text(
    img: np.ndarray,
    text: Union[str, Sequence[str]],
    xy: Any,
    color: ColorArg = "white",
    size: Optional[float] = None,
    anchor: str = "top-left",
    outline: Optional[Color] = "black",
    background: Optional[Color] = None,
    background_alpha: float = 0.6,
) -> np.ndarray:
    """Write text, readable on any image.

    By default the text is white with a thin black outline, readable on dark
    and bright areas alike; ``background=<colour>`` puts it on a translucent
    box instead (``outline=None`` to drop the outline).

    Args:
        img: image (not modified).
        text: one string, or a list of strings (one per position in ``xy``).
        xy: ``(x, y)`` of the anchor point, or an ``(N, 2)`` array.
        color: text colour (one, a list, or None for the colour cycle).
        size: text height in pixels (default from the image size, >= 12).
        anchor: which point of the text sits at ``xy``: ``"top-left"``
            (default), ``"top"``, ``"top-right"``, ``"left"``, ``"center"``,
            ``"right"``, ``"bottom-left"``, ``"bottom"``, ``"bottom-right"``,
            or a Pillow anchor such as ``"ls"`` (left, baseline).
        outline: colour of the outline around the letters, None for none.
        background: colour of a box behind the text, None for none.
        background_alpha: opacity of that box.

    Returns:
        A new image with the text written. Multi-line strings are supported.
    """
    pil_anchor = ANCHORS.get(anchor, anchor)
    if not isinstance(pil_anchor, str) or len(pil_anchor) != 2:
        raise ValueError(f"Unknown anchor {anchor!r}: use one of {sorted(ANCHORS)} or a Pillow anchor")
    canvas = _Canvas(img)
    texts = [text] if isinstance(text, str) else [str(item) for item in text]
    positions = _as_points(xy)
    if len(positions) != len(texts):
        raise ValueError(f"Got {len(texts)} texts for {len(positions)} positions")
    colors = _colors(color, len(texts))
    font = canvas.font(size)
    font_size = font.size if hasattr(font, "size") else 12
    stroke = max(1, int(round(font_size / 10.0))) if outline is not None and background is None else 0
    stroke_fill = canvas.rgba(to_rgb(outline)) if stroke and outline is not None else None
    for content, (x, y), rgb in zip(texts, positions, colors):
        if not _finite(x, y):
            continue
        item_anchor = pil_anchor
        if "\n" in content:  # multiline text: vertical anchors a (top) / m / d (bottom)
            item_anchor = pil_anchor[0] + {"t": "a", "b": "d", "s": "d"}.get(pil_anchor[1], pil_anchor[1])
        kwargs = {"font": font, "anchor": item_anchor}
        if background is not None:
            left, top, right, bottom = canvas.draw.textbbox((x, y), content, **kwargs)
            pad = max(2, font_size // 5)
            canvas.draw.rectangle(
                [left - pad, top - pad, right + pad, bottom + pad],
                fill=canvas.rgba(to_rgb(background), background_alpha),
            )
        canvas.draw.text((x, y), content, fill=canvas.rgba(rgb), stroke_width=stroke, stroke_fill=stroke_fill, **kwargs)
    return canvas.result()

mask

mask(img: ndarray, mask: ndarray, color: ColorArg = None, alpha: float = 0.5) -> np.ndarray

Blend a mask over the image.

Parameters:

Name Type Description Default
img ndarray

image (not modified).

required
mask ndarray

(H, W) array, same height and width as the image:

  • boolean: True pixels get color (default: first colour of the cycle);
  • integer labels: 0 (and negatives) is background, each label k > 0 gets its own colour — color=None cycles through DEFAULT_COLORS (label k -> colour (k - 1) % 10), a list of colours is indexed the same way, one colour paints every label;
  • float in [0, 1]: a soft mask, the per-pixel opacity is alpha * mask.
required
color ColorArg

see above.

None
alpha float

opacity of the mask colour, 0 to 1.

0.5

Returns:

Type Description
ndarray

A new image with the mask blended in.

Source code in src/interactive_pipe/draw.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
def mask(
    img: np.ndarray,
    mask: np.ndarray,
    color: ColorArg = None,
    alpha: float = 0.5,
) -> np.ndarray:
    """Blend a mask over the image.

    Args:
        img: image (not modified).
        mask: ``(H, W)`` array, same height and width as the image:

            - boolean: True pixels get ``color`` (default: first colour of
              the cycle);
            - integer labels: 0 (and negatives) is background, each label
              ``k > 0`` gets its own colour — ``color=None`` cycles through
              ``DEFAULT_COLORS`` (label ``k`` -> colour ``(k - 1) % 10``),
              a list of colours is indexed the same way, one colour paints
              every label;
            - float in ``[0, 1]``: a soft mask, the per-pixel opacity is
              ``alpha * mask``.
        color: see above.
        alpha: opacity of the mask colour, 0 to 1.

    Returns:
        A new image with the mask blended in.
    """
    if not 0.0 <= alpha <= 1.0:
        raise ValueError(f"alpha must be in [0, 1], got {alpha}")
    image = _check_image(img)
    array = np.asarray(mask)
    if array.ndim == 3 and array.shape[-1] == 1:
        array = array[..., 0]
    if array.shape != image.shape[:2]:
        raise ValueError(f"mask shape {array.shape} does not match the image size {image.shape[:2]}")
    scale = _value_scale(image)
    out = _as_rgb_copy(image)
    compute = _compute_dtype(out)
    if array.dtype == np.bool_ or np.issubdtype(array.dtype, np.integer):
        if array.dtype == np.bool_:
            selected = array
            labels = None
        else:
            selected = array > 0
            labels = array.reshape(-1)[np.flatnonzero(selected)]
        flat = np.flatnonzero(selected)
        if flat.size == 0:
            return out
        if labels is None or (color is not None and _is_single_color(color)):
            rgb = np.asarray(_colors(color, 1)[0], dtype=compute)[None, :]
        else:
            colors = DEFAULT_COLORS if color is None else [to_rgb(c) for c in color]  # type: ignore[union-attr]
            if not colors:
                raise ValueError("Empty colour list for a mask with labels: give at least one colour, or color=None")
            palette = np.asarray(colors, dtype=compute)
            rgb = palette[(labels.astype(np.int64) - 1) % len(palette)]
        weight = np.full(flat.size, alpha, dtype=compute)
    elif np.issubdtype(array.dtype, np.floating):
        soft = np.nan_to_num(np.clip(array, 0.0, 1.0)).astype(compute)
        flat = np.flatnonzero(soft)
        if flat.size == 0:
            return out
        if color is not None and not _is_single_color(color):
            raise ValueError("A float (soft) mask takes a single colour")
        rgb = np.asarray(_colors(color, 1)[0], dtype=compute)[None, :]
        weight = (alpha * soft.reshape(-1)[flat]).astype(compute)
    else:
        raise TypeError(f"mask must be boolean, integer labels or float, got dtype {array.dtype}")
    if rgb.shape[0] == 1:
        rgb = np.broadcast_to(rgb, (flat.size, 3))
    _blend(out, flat, rgb, weight, scale)
    return out

to_rgb

to_rgb(color: Color) -> Tuple[float, float, float]

(r, g, b) floats in [0, 1] from a colour name, a hex string or a tuple (floats in [0, 1], or ints in 0-255 when a value is > 1).

Source code in src/interactive_pipe/draw.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
def to_rgb(color: Color) -> Tuple[float, float, float]:
    """``(r, g, b)`` floats in ``[0, 1]`` from a colour name, a hex string or
    a tuple (floats in ``[0, 1]``, or ints in ``0-255`` when a value is > 1)."""
    if isinstance(color, str):
        from matplotlib.colors import to_rgb as mpl_to_rgb

        try:
            return tuple(float(c) for c in mpl_to_rgb(color))  # type: ignore[return-value]
        except ValueError:
            raise ValueError(
                f"Unknown colour {color!r}: use a name ('red'), a hex string or an (r, g, b) tuple"
            ) from None
    try:
        values = [float(c) for c in color]  # type: ignore[union-attr]
    except TypeError:
        raise TypeError(f"Colour must be a name, a hex string or an (r, g, b) tuple, got {color!r}") from None
    if len(values) not in (3, 4):
        raise ValueError(f"Colour tuple must have 3 (or 4) values, got {color!r}")
    values = values[:3]
    if max(values) > 1.0:
        values = [v / 255.0 for v in values]
    if min(values) < 0.0 or max(values) > 1.0:
        raise ValueError(f"Colour values must be in [0, 1] (or 0-255), got {color!r}")
    return (values[0], values[1], values[2])