Files
supervision/tests/metrics/utils/test_object_size.py
T
058d8fd990 perf(detection): count mask pixels with count_nonzero (#2361)
Mask pixel-area counting used `np.sum` — `np.array([np.sum(m) for m in
masks])` in `Detections.area` and `np.sum(mask, axis=(1, 2))` in the metrics
`get_mask_size_category`. For boolean masks `np.count_nonzero` (with no axis)
dispatches to NumPy's SIMD popcount over the raw byte buffer, whereas every
axis-reduction form — `np.sum(..., axis=...)` and even `np.count_nonzero(...,
axis=...)` — falls back to a slower generic reduction. So counting per mask
with `np.count_nonzero` is several times faster than the "obvious" vectorized
sum, while producing bit-identical integer counts.

Route both sites through `np.fromiter((np.count_nonzero(m) for m in masks),
dtype=np.int64, count=len(masks))`. `dtype=np.int64` preserves the documented
`Detections.area` mask-branch dtype on every platform (a bare
`np.array([...])` of Python ints would be int32 on Windows).

Measured ~5x on 640x640 masks (e.g. `Detections.area`, N=300: ~24ms -> ~4ms),
faster across densities. `get_mask_size_category` feeds the size-bucketed
F1/Precision/Recall/mAP/mAR metrics, where it is invoked repeatedly per
dataset. Counts are integer-exact (verified over 400 randomized trials plus
empty / all-true / all-false / 1x1 edge cases).

Adds parity tests for `Detections.area` (dense mask) and
`get_mask_size_category` against an `np.sum` reference.

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2026-07-01 23:22:46 +02:00

63 lines
2.2 KiB
Python

"""Tests for supervision.metrics.utils.object_size — mask pixel-count path."""
from __future__ import annotations
import numpy as np
import pytest
from supervision.metrics.utils.object_size import (
SIZE_THRESHOLDS,
ObjectSizeCategory,
get_mask_size_category,
)
def _reference_mask_size_category(mask: np.ndarray) -> np.ndarray:
"""Reference categorization using a plain ``np.sum`` area."""
areas = np.sum(mask, axis=(1, 2))
result = np.full(areas.shape, ObjectSizeCategory.ANY.value)
sm, lg = SIZE_THRESHOLDS
result[areas < sm] = ObjectSizeCategory.SMALL.value
result[(areas >= sm) & (areas < lg)] = ObjectSizeCategory.MEDIUM.value
result[areas >= lg] = ObjectSizeCategory.LARGE.value
return result
class TestGetMaskSizeCategory:
"""Verify the count_nonzero-based mask area categorization."""
@pytest.mark.parametrize(
("n", "h", "w", "seed"),
[
pytest.param(0, 8, 8, 1, id="empty"),
pytest.param(1, 40, 40, 2, id="single"),
pytest.param(6, 64, 64, 3, id="batch"),
pytest.param(4, 200, 200, 4, id="across-thresholds"),
],
)
def test_matches_sum_based_reference(
self, n: int, h: int, w: int, seed: int
) -> None:
"""Categories match a plain ``np.sum(axis=(1, 2))`` reference."""
rng = np.random.default_rng(seed)
mask = rng.random((n, h, w)) < rng.random()
np.testing.assert_array_equal(
get_mask_size_category(mask), _reference_mask_size_category(mask)
)
def test_threshold_boundaries(self) -> None:
"""Pixel counts on each SMALL/MEDIUM/LARGE boundary land in the right bin."""
sm, lg = SIZE_THRESHOLDS
mask = np.zeros((3, 100, 100), dtype=bool)
mask[0].flat[: sm - 1] = True # below SMALL threshold -> SMALL
mask[1].flat[:sm] = True # exactly SMALL threshold -> MEDIUM
mask[2].flat[:lg] = True # exactly LARGE threshold -> LARGE
np.testing.assert_array_equal(
get_mask_size_category(mask),
[
ObjectSizeCategory.SMALL.value,
ObjectSizeCategory.MEDIUM.value,
ObjectSizeCategory.LARGE.value,
],
)