Repository navigation
fix: keep mask holes from becoming extra instances in dataset export - #2703
Merged
Borda merged 4 commits intoOct 11, 2026
Merged
Conversation
`as_yolo`, `as_pascal_voc` and `as_labelme` wrote every contour of a mask as its own polygon, so each hole became a phantom same-class instance and the outer polygon lost the hole. A 50x50 square with a 20x20 hole (2100 px) reloaded as two instances of 2500 and 480 px. `approximate_mask_with_polygons` gains an opt-in `bridge_holes` flag that joins each hole to its outer contour with a zero-width seam. The three exporters enable it; the default, `sv.mask_to_polygons` and COCO export are unchanged, and masks without holes produce identical polygons.
avanish-garg
force-pushed
the
fix/dataset-export-mask-holes
branch
from
October 8, 2026 20:21
1491f8e to
5bfa38f
Compare
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
The seam can cross background on concave masks, causing export corruption, and its repeated spatial-index construction scales poorly with many holes.
2 open findings
What changed in this PR
Fixes dataset exports so mask holes remain part of one instance.
Changes:
- Adds optional hole-bridging polygon conversion.
- Enables bridging for YOLO, Pascal VOC, and LabelMe.
- Adds round-trip tests and changelog documentation.
Review scores: Code quality 3/5; testing 4/5; documentation 4/5. Risk: 3/5 medium.
| File | Description |
|---|---|
src/supervision/dataset/utils.py |
Implements hole bridging. |
src/supervision/dataset/formats/yolo.py |
Enables bridging for YOLO. |
src/supervision/dataset/formats/pascal_voc.py |
Enables bridging for Pascal VOC. |
src/supervision/dataset/formats/labelme.py |
Enables bridging for LabelMe. |
tests/dataset/test_utils.py |
Tests polygon bridging behavior. |
tests/dataset/formats/test_yolo.py |
Tests YOLO round trips. |
tests/dataset/formats/test_pascal_voc.py |
Tests Pascal VOC round trips. |
tests/dataset/formats/test_labelme.py |
Tests LabelMe exports and round trips. |
tests/detection/utils/test_converters.py |
Preserves existing contour behavior. |
docs/changelog.md |
Documents the export fix. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
The seam joining a hole to its outer contour was the nearest vertex pair, which for a concave component can lie across background. Filling the exported polygon then painted pixels along the seam even with approximation_percentage=0. Each seam is now the shortest straight line between two contour vertices whose pixels are all foreground in the original mask; the nearest pair is only the fallback when no candidate qualifies. Holes may hang from the outer contour or from a hole attached before them, as before. Candidates come from one spatial index over the attached vertices, which is rebuilt only after 512 new vertices instead of once per hole, and all holes are spliced in a single pass.
Changes: - Integrate fetched develop at 714ad23 with PR roboflow#2703 on its remediation branch. - Resolve docs/changelog.md by preserving the target Unreleased entries and the PR mask-hole export entry. Impact: - The PR branch includes the fetched target implementation, tests, configuration, and documentation while retaining its mask-hole export change. - No remote refs are changed; PR source fixes remain for the remediation phase. Verification: - The remediation branch receipt check passed at the collected PR head. - The conflict-free merge index passed git diff --cached --check and the configured mdformat hook. - The merge index differs from the fetched target only across the ten PR-specific paths. Residual limits: - The two reported source findings and remaining remediation gates are still open after this integration commit. --- Co-authored-by: Codex <[email protected]>
Changes: - Validate every crossed pixel cell along candidate seams and reject an unsafe nearest fallback with a clear ValueError. - Add regressions for an unsafe exhausted-search fallback and a background cell crossed between sample points; document the failure behavior in the PR changelog. Impact: - Dataset mask exports no longer silently alter pixels when no foreground-contained seam is found. - The raster traversal checks interval interiors and boundary crossings so narrow background cells cannot slip between samples. Verification: - Targeted dataset utility tests: 81 passed. - Full suite: 5,428 passed, 79 skipped; coverage 93%. - Pinned Ruff lint/format, docformatter, and mypy hooks passed; independent review found no confirmed correctness or safety defect. Residual limits: - OpenCV backend was unavailable; tests used the NumPy fallback. - If bounded seam search finds no safe seam, the documented ValueError propagates through the affected dataset exporters. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <[email protected]>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #2703 +/- ##
========================================
Coverage 93% 93%
========================================
Files 83 83
Lines 12992 13109 +117
========================================
+ Hits 12137 12253 +116
- Misses 855 856 +1 🚀 New features to boost your workflow:
|
Borda
approved these changes
Oct 11, 2026
3 tasks done
2 of 3 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Description
A mask with a hole was exported to YOLO, Pascal VOC and LabelMe as two instances of the same class, one for
the outer contour and one for the hole (
mask_to_polygonskeeps hole contours as ordinary polygons and thewriters emit one object per polygon).
Minimal repro (full script in the issue): a 100x150 ring mask of area 2100 exported with
as_yoloandreloaded with
from_yolo.Motivation and Context
SAM-style masks often have holes, and the extra same-class instance inside the hole ends up in the training
labels.
as_cocoalready handles holes through RLE.Closes #2702
Changes Made
approximate_mask_with_polygonsgets an opt-inbridge_holes: bool = False. When True, each hole contour isjoined to its enclosing outer contour along a seam (nearest outer vertex), so the mask becomes one polygon
that fills back to the same pixels. Holes are told apart from outer contours by contour orientation, which
works with both the OpenCV and the NumPy fallback backends.
as_yolo,as_pascal_vocandas_labelmepassbridge_holes=True. LabelMe previously calledmask_to_polygonsdirectly and now goes through the helper (identical output for masks without holes).mask_to_polygons(also used byMaskAnnotator), the COCO path, and the default ofthe new parameter, so external callers and COCO output are unchanged. Masks without holes take the old code
path.
Testing
Ran (not the whole suite, not
pre-commit --all-files):pytest tests/dataset tests/detection tests/cv2 tests/annotators: 3477 passed, 1 skipped; with cv2 blocked(NumPy fallback),
tests/dataset tests/detection tests/annotators: 3041 passed, 1 skipped.pytest --doctest-modules src/supervision/dataset src/supervision/detection/utils: 79 passed (both backends).ruff check,ruff format --check,docformatter --checkandmypy(pre-commit defaults) on the changed files: clean.tests/cv2/test_integration.py(needssklearn, not in my environment), pre-commit's mdformat.New tests fail on
developand pass with this change (13 fail on develop: 8 withTypeError: unexpected keyword argument 'bridge_holes', YOLO/VOC/LabelMe round trips withassert 2 == 1,and the LabelMe round trip; 2 guard tests pass on both). Ring round trip for YOLO, VOC and LabelMe gives 1
instance, area 2100, identical mask, on OpenCV and on the NumPy fallback.
docs/changelog.mdunderUnreleased(skip for lint/type/format-only or pure doc changes)(Tick the first box only after you run the full suite yourself.)
Additional Notes
keeps the area.
on very concave shapes (on random masks the fill differed from the original by 0.2% on average, 2% worst case).
min_image_area_percentageis still filled in.scipy.spatialis imported at module level (scipy is already a dependency).