Skip to content

fix: keep mask holes from becoming extra instances in dataset export - #2703

Merged
Borda merged 4 commits into
roboflow:developfrom
avanish-garg:fix/dataset-export-mask-holes
Oct 11, 2026
Merged

Borda merged 4 commits into
roboflow:developfrom
avanish-garg:fix/dataset-export-mask-holes

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

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_polygons keeps hole contours as ordinary polygons and the
writers emit one object per polygon).

Minimal repro (full script in the issue): a 100x150 ring mask of area 2100 exported with as_yolo and
reloaded with from_yolo.

  • Before: 2 label lines, reload gives 2 instances with areas [2500, 480].
  • After: 1 label line, reload gives 1 instance of area 2100, mask identical to the original.

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_coco already handles holes through RLE.

Closes #2702

Changes Made

  • approximate_mask_with_polygons gets an opt-in bridge_holes: bool = False. When True, each hole contour is
    joined 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_voc and as_labelme pass bridge_holes=True. LabelMe previously called
    mask_to_polygons directly and now goes through the helper (identical output for masks without holes).
  • Left alone on purpose: mask_to_polygons (also used by MaskAnnotator), the COCO path, and the default of
    the 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 --check and mypy (pre-commit defaults) on the changed files: clean.
  • Not run: tests/cv2/test_integration.py (needs sklearn, not in my environment), pre-commit's mdformat.

New tests fail on develop and pass with this change (13 fail on develop: 8 with
TypeError: unexpected keyword argument 'bridge_holes', YOLO/VOC/LabelMe round trips with assert 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.

  • Added/updated tests, and the full suite passes locally
  • Updated docs (docstrings / mkdocs entry) for new or changed public API
  • Added a changelog entry in docs/changelog.md under Unreleased (skip for lint/type/format-only or pure doc changes)

(Tick the first box only after you run the full suite yourself.)

Additional Notes

  • Dropping holes instead of bridging them would give one instance but area 2500 (+19% vs 2100); the seam
    keeps the area.
  • Seams add a few duplicate vertices to the exported polygon, and the nearest-vertex seam can cross background
    on very concave shapes (on random masks the fill differed from the original by 0.2% on average, 2% worst case).
  • A hole whose outer contour is dropped by the area filters is dropped with it; a hole below
    min_image_area_percentage is still filled in.
  • scipy.spatial is imported at module level (scipy is already a dependency).
  • Not verified: Ultralytics reading the seam polygons; masks with thousands of holes (performance).

@avanish-garg
avanish-garg requested a review from SkalskiP as a code owner October 8, 2026 20:08
@CLAassistant

CLAassistant commented Oct 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

`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
avanish-garg force-pushed the fix/dataset-export-mask-holes branch from 1491f8e to 5bfa38f Compare October 8, 2026 20:21
@Borda
Borda requested a balanced review from Copilot October 8, 2026 22:29
@Borda Borda added the bug Something isn't working label Oct 8, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment thread src/supervision/dataset/utils.py Resolved
Comment thread src/supervision/dataset/utils.py Resolved
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.
Borda and others added 2 commits October 11, 2026 11:05
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

codecov Bot commented Oct 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.15966% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93%. Comparing base (714ad23) to head (cb86371).

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: DetectionDataset.as_yolo / as_pascal_voc / as_labelme write a mask with a hole as two instances

4 participants