From 5a59dcdec6fddaf57d88981bd3175f0e439dcadb Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Wed, 22 Apr 2026 08:12:00 +0200 Subject: [PATCH] refactor(masks): switch CompactMask RLE to F-order (#2228) * refactor(masks): switch CompactMask RLE to F-order * docs(masks): update _rle_area docstring example to F-order RLE * test(masks): verify _rle_encode produces COCO-compatible F-order RLE --------- Co-authored-by: Claude Code Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- examples/compact_mask/README.md | 4 +- src/supervision/detection/compact_mask.py | 53 +++++++++++++++-------- tests/detection/test_compact_mask.py | 40 ++++++++++++++++- 3 files changed, 75 insertions(+), 22 deletions(-) diff --git a/examples/compact_mask/README.md b/examples/compact_mask/README.md index a24b240d..a9dca913 100644 --- a/examples/compact_mask/README.md +++ b/examples/compact_mask/README.md @@ -102,7 +102,7 @@ At N=1 000 with 1 % overlap, bbox pre-filter reduces 499 500 candidate pairs to Both formats compress extremely well; the deciding factors for Crop-RLE are: 1. **~3x smaller** for masks that are themselves sparse within their bounding box. -2. **COCO RLE interop path** — row-major crop RLE can be re-encoded to column-major full-image RLE for `pycocotools` if needed. +2. **COCO RLE interop path** — crop RLE uses column-major (F-order) pixel scan, matching `pycocotools`; to interoperate, you still need to construct a full-image COCO RLE from the crop-scoped encoding (for example by padding/merging runs onto the full-image canvas, or by materialising the crop in the full image and re-encoding). 3. `.area` computed directly from run lengths — no materialisation, no allocation. The main trade-off: crop-only decode is O(A) rather than O(1). For the common solid-fill segmentation mask this is negligible (\<0.1 ms per mask). @@ -578,7 +578,7 @@ All non-skipped scenarios pass: pixel-perfect annotation, exact area, lossless ` ## Limitations - `CompactMask` is **not** a full `np.ndarray`. Call `.to_dense()` before passing to code that requires arbitrary ndarray methods (`astype`, `reshape`, `ravel`, `any`, `all`, …). -- RLE format is **row-major (C-order), crop-scoped** — incompatible with pycocotools / COCO API RLEs (column-major, full-image-scoped). Use `.to_dense()` first if you need pycocotools interop. +- RLE format is **column-major (F-order), crop-scoped** — pixel-scan order matches COCO / pycocotools, but crop scope differs from full-image scope. Use `.to_dense()` to materialize a full-image dense mask, then encode that mask to COCO RLE before passing it to pycocotools. - `from_dense()` requires the input `(N, H, W)` array to fit in memory. For truly OOM-scale data, build `CompactMask` per-detection directly from model output crops rather than from a pre-allocated dense stack. --- diff --git a/src/supervision/detection/compact_mask.py b/src/supervision/detection/compact_mask.py index 32135212..d1a43c7a 100644 --- a/src/supervision/detection/compact_mask.py +++ b/src/supervision/detection/compact_mask.py @@ -19,11 +19,13 @@ import numpy.typing as npt def _rle_encode(mask_2d: npt.NDArray[Any]) -> npt.NDArray[np.int32]: - """Run-length encode a 2D boolean mask in row-major order. + """Run-length encode a 2D boolean mask in column-major (Fortran) order. - The encoding starts with the count of leading ``False`` values (may be 0 - if the mask begins with ``True``). Subsequent values alternate between - ``True`` and ``False`` run counts. + Pixels are scanned column-by-column (top-to-bottom within each column, + left-to-right across columns), matching the COCO / pycocotools RLE + convention. The encoding starts with the count of leading ``False`` + values (may be 0 if the mask begins with ``True``). Subsequent values + alternate between ``True`` and ``False`` run counts. Args: mask_2d: 2D boolean array of shape ``(H, W)``. @@ -37,11 +39,11 @@ def _rle_encode(mask_2d: npt.NDArray[Any]) -> npt.NDArray[np.int32]: >>> from supervision.detection.compact_mask import _rle_encode >>> mask = np.array([[False, True, True], [True, False, False]]) >>> _rle_encode(mask).tolist() - [1, 3, 2] + [1, 2, 1, 1, 1] ``` """ - flat = mask_2d.ravel() # C-order (row-major) + flat = mask_2d.ravel(order="F") # F-order (column-major, COCO-compatible) if len(flat) == 0: return np.array([0], dtype=np.int32) @@ -76,7 +78,7 @@ def _rle_decode( ```pycon >>> import numpy as np >>> from supervision.detection.compact_mask import _rle_decode - >>> rle = np.array([1, 3, 2], dtype=np.int32) + >>> rle = np.array([1, 2, 1, 1, 1], dtype=np.int32) >>> _rle_decode(rle, 2, 3) array([[False, True, True], [ True, False, False]]) @@ -91,7 +93,9 @@ def _rle_decode( # Pad with False if the RLE is shorter than expected (e.g. all-False # tails are often omitted during encoding). flat = np.pad(flat, (0, num_pixels - len(flat))) - return cast(npt.NDArray[np.bool_], flat[:num_pixels].reshape(height, width)) + return cast( + npt.NDArray[np.bool_], flat[:num_pixels].reshape(height, width, order="F") + ) def _rle_area(rle: npt.NDArray[np.int32]) -> int: @@ -107,7 +111,7 @@ def _rle_area(rle: npt.NDArray[np.int32]) -> int: ```pycon >>> import numpy as np >>> from supervision.detection.compact_mask import _rle_area - >>> rle = np.array([1, 3, 2], dtype=np.int32) # 1 F, 3 T, 2 F + >>> rle = np.array([1, 2, 1, 1, 1], dtype=np.int32) >>> _rle_area(rle) 3 @@ -138,17 +142,28 @@ class CompactMask: ``cm.to_dense().astype(np.uint8)``. :meth:`to_dense` is the single explicit materialisation boundary. - .. note:: **RLE encoding incompatibility with pycocotools / COCO API** + .. note:: **RLE encoding — COCO / pycocotools pixel-scan order** - :class:`CompactMask` uses **row-major (C-order)** run-lengths scoped - to each mask's bounding-box crop. The COCO API (pycocotools) uses - **column-major (Fortran-order)** run-lengths scoped to the **full - image**. The two formats are not interchangeable: you cannot pass a - :class:`CompactMask` RLE directly to ``maskUtils.iou()`` or - ``maskUtils.decode()``, and you cannot load a COCO RLE dict into a - :class:`CompactMask` without re-encoding. Use - :meth:`to_dense` to obtain a standard boolean array, then pass it to - pycocotools if needed. + :class:`CompactMask` uses **column-major (Fortran-order, F-order)** + run-lengths scoped to each mask's bounding-box crop, matching the + pixel-scan order used by the COCO API (pycocotools). The crop scope + still differs from the full-image scope used by pycocotools, so a + :class:`CompactMask` RLE cannot be passed directly to + ``maskUtils.iou()`` or ``maskUtils.decode()`` without re-scoping to + the full canvas. Use :meth:`to_dense` to obtain a standard boolean + array for pycocotools interop. + + This scan order is part of CompactMask's internal RLE representation. + Switching from row-major (C-order) to column-major (F-order) is a + backward-incompatible format change for any persisted or serialized + :class:`CompactMask` state, including pickled objects and any + external storage of ``._rles``. Older stored RLE arrays will decode + incorrectly under the new convention. + + Migration note: load or decode legacy masks with the older version, + materialize them to dense boolean arrays, and then re-encode them + with the current version (for example via :meth:`to_dense` followed + by :meth:`from_dense`) before persisting them again. Args: rles: List of N int32 run-length arrays. diff --git a/tests/detection/test_compact_mask.py b/tests/detection/test_compact_mask.py index cb4e9673..ee15ad00 100644 --- a/tests/detection/test_compact_mask.py +++ b/tests/detection/test_compact_mask.py @@ -13,7 +13,7 @@ from supervision.detection.compact_mask import ( _rle_decode, _rle_encode, ) -from supervision.detection.utils.converters import mask_to_xyxy +from supervision.detection.utils.converters import mask_to_rle, mask_to_xyxy from supervision.detection.utils.masks import ( calculate_masks_centroids, contains_holes, @@ -86,6 +86,44 @@ class TestRleHelpers: rle = _rle_encode(mask_2d) assert _rle_area(rle) == int(np.sum(mask_2d)) + @pytest.mark.parametrize( + ("mask_2d", "expected_rle"), + [ + # 2x3; F-order flat: [F,T,T,F,T,F] -> 1F,2T,1F,1T,1F + ( + np.array([[False, True, True], [True, False, False]]), + [1, 2, 1, 1, 1], + ), + # 3x3 all-False -> single run of 9 + (np.zeros((3, 3), dtype=bool), [9]), + # 3x1 all-True; F-order scan starts True -> leading zero prepended + (np.ones((3, 1), dtype=bool), [0, 3]), + # 2x2; F-order flat: [F,T,F,T] -> alternating single-pixel runs + ( + np.array([[False, False], [True, True]]), + [1, 1, 1, 1], + ), + ], + ) + def test_encode_matches_coco_f_order( + self, mask_2d: np.ndarray, expected_rle: list[int] + ) -> None: + """_rle_encode produces COCO-compatible F-order RLE for known masks.""" + assert _rle_encode(mask_2d).tolist() == expected_rle + + @pytest.mark.parametrize( + "mask_2d", + [ + np.array([[False, True, True], [True, False, False]]), + np.zeros((4, 4), dtype=bool), + np.array([[False, False], [True, True]]), + np.ones((3, 1), dtype=bool), + ], + ) + def test_encode_agrees_with_mask_to_rle(self, mask_2d: np.ndarray) -> None: + """_rle_encode output matches mask_to_rle (the public COCO-format encoder).""" + assert _rle_encode(mask_2d).tolist() == mask_to_rle(mask_2d) + class TestFromDenseToDense: """Tests for CompactMask.from_dense and to_dense.