Skip to content

fix(annotators): draw masks and halos on grayscale scenes - #2755

Merged
Borda merged 5 commits into
roboflow:developfrom
MohammadHijjawi97:fix/annotators-grayscale-mask-halo
Oct 19, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
MohammadHijjawi97:fix/annotators-grayscale-mask-halo

Conversation

@MohammadHijjawi97

Copy link
Copy Markdown
Contributor

Description

MaskAnnotator and HaloAnnotator raise ValueError on grayscale scenes: (H, W) arrays, (H, W, 1) arrays, and Pillow "L" images (which pillow_to_cv2 turns into (H, W) arrays). BoxAnnotator, PolygonAnnotator and ColorAnnotator already work on the same scenes.

import numpy as np
import supervision as sv

mask = np.zeros((1, 10, 10), dtype=bool)
mask[0, 2:8, 2:8] = True
detections = sv.Detections(
    xyxy=np.array([[2, 2, 7, 7]], dtype=np.float32), mask=mask, class_id=np.array([0])
)
scene = np.zeros((10, 10), dtype=np.uint8)
sv.MaskAnnotator().annotate(scene, detections)
sv.HaloAnnotator().annotate(scene, detections)

Before (develop):

MaskAnnotator (H, W) array: ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 36 output values where the mask is true
MaskAnnotator (H, W, 1) array: ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (36,1)
MaskAnnotator PIL 'L' image: ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 36 output values where the mask is true
HaloAnnotator (H, W) array: ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 36 output values where the mask is true
HaloAnnotator (H, W, 1) array: ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (36,1)
HaloAnnotator PIL 'L' image: ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 36 output values where the mask is true

After (color sv.Color(r=10, g=20, b=200)):

MaskAnnotator (H, W) array: shape (10, 10), center 200, edge 0
MaskAnnotator (H, W, 1) array: shape (10, 10, 1), center [200], edge [0]
MaskAnnotator PIL 'L' image: shape (10, 10), center 200, edge 0
HaloAnnotator (H, W) array: shape (10, 10), center 0, edge 53
HaloAnnotator (H, W, 1) array: shape (10, 10, 1), center [0], edge [53]
HaloAnnotator PIL 'L' image: shape (10, 10), center 0, edge 53
PolygonAnnotator (H, W) outline value: 200

Motivation and Context

_paint_masks_by_area writes color.as_bgr(), a three-value color, into every canvas pixel under a mask. A single-channel canvas cannot take three values. The other annotators draw through OpenCV (cv2.rectangle, cv2.fillPoly), and OpenCV writes the color's first (blue) value on a one-channel image. Grayscale scenes are already supported elsewhere: pillow_to_cv2 returns (H, W) arrays for single-channel Pillow modes, and #2725 fixed the same layouts in BlurAnnotator and PixelateAnnotator.

Changes Made

  • _paint_masks_by_area now paints a grayscale canvas with the first channel of the color, so a mask gets the same gray value as the box or polygon outline for that detection.
  • MaskAnnotator: restore the singleton channel axis that OpenCV's addWeighted drops before writing the blend back.
  • HaloAnnotator: restore the channel axis after blur, clear the mask area with a scalar, and take the halo alpha straight from the single channel instead of COLOR_BGR2GRAY.
  • Docstrings of both annotate methods describe the grayscale layouts.
  • BGR scenes take exactly the same code path as before. BGRA scenes are out of scope.

Testing

  • New TestSingleChannelMaskAnnotators (12 cases): mask and halo on (H, W) and (H, W, 1) scenes, with dense masks and CompactMask, must equal channel 0 of the same annotation on the BGR copy of the scene. A gray mask must take color.b, like PolygonAnnotator and ColorAnnotator. A Pillow "L" image must come back as an "L" image.

  • On develop: 6 failed, 2 passed (the polygon and color reference cases). With this change: 12 passed, with OpenCV 5.0 and with the NumPy fallback.

  • pytest full suite with OpenCV: 6069 passed, 1 skipped. Without OpenCV: 5741 passed, 123 skipped.

  • pre-commit run on the changed files: ruff, ruff-format, docformatter, codespell and the other hooks pass. mypy reports no new errors.

  • 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)

Additional Notes

On a grayscale scene a color has no single obvious gray. I used the first (blue) channel because that is what every OpenCV-drawn annotator already writes, so masks, boxes and polygons on the same frame agree. Converting colors to luminance would need the same change in all of those annotators, which is beyond this fix. CropAnnotator, BackgroundOverlayAnnotator, HeatMapAnnotator and RichLabelAnnotator also fail on grayscale scenes; I left them for separate PRs.

`MaskAnnotator` and `HaloAnnotator` raised `ValueError` on grayscale
scenes, shaped `(H, W)` or `(H, W, 1)` or given as a Pillow "L" image,
because `_paint_masks_by_area` assigned a three-value BGR color to
single-channel pixels. Other annotators draw on the same scenes through
OpenCV, which writes the first (blue) channel of the color.

Paint grayscale canvases with that first channel, restore the singleton
channel axis that OpenCV drops in `addWeighted` and `blur`, and compute
the halo alpha from the single channel instead of `COLOR_BGR2GRAY`.
BGR scenes are unchanged.
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (9399814) to head (3867062).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2755   +/-   ##
=======================================
  Coverage       94%     94%           
=======================================
  Files           83      83           
  Lines        13638   13644    +6     
=======================================
+ Hits         12833   12839    +6     
  Misses         805     805           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda Borda added the bug Something isn't working label Oct 19, 2026
@Borda
Borda requested a balanced review from Copilot October 19, 2026 11:55

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.

🟢 Approval recommended

The localized channel-handling changes preserve BGR behavior and include focused grayscale regression coverage.

No open issues 🎉

What changed in this PR

🟢 Approve — extends Supervision’s grayscale annotation support to masks and halos. No actionable issues were identified.

Changes:

  • Paint grayscale masks using the color’s blue channel, matching existing OpenCV drawing behavior.
  • Preserve singleton channel dimensions during blending and halo generation.
  • Add regression tests, docstrings, and a changelog entry.

Coverage: behavior, shape compatibility, tests, and documentation. Tests were not independently run.

Quality: code 5/5, testing 4/5, documentation 5/5; risk 1/5. Changes are localized and have focused regression coverage.

File Description
tests/​annotators/​test_core.py Adds grayscale layout, compact-mask, color-value, and Pillow regressions.
src/​supervision/​annotators/​core.py Handles single-channel mask painting, blending, and halos.
docs/​changelog.md Documents grayscale support and color behavior.

Review effort: Balanced

Borda and others added 3 commits October 19, 2026 16:17
Changes:
- Merge target roboflow#2750 and roboflow#2752 metrics behavior and regression coverage into the PR branch.
- Retain the PR roboflow#2755 grayscale annotator changelog entry alongside target metrics release notes.

Impact:
- Keeps the PR branch current with develop while preserving both PR and target behavior.
- Retains release notes for grayscale annotator and metrics changes in one Unreleased section.

Verification:
- `git merge-tree` identified one changelog conflict; the resolution keeps all three independent entries.
- Reviewed the five-path merge index; no unmerged paths remain and `git diff --cached --check` passes.

Residual limits:
- The conflict was documentation-only; merged target code remains subject to this remediation run's quality gates.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Add a HaloAnnotator grayscale regression with non-neutral colors that differ only in the blue component.

Impact:
- Protects the documented first BGR component behavior from future grayscale channel-selection regressions.

Verification:
- Canonical gates passed: ruff lint and format, mypy, and coverage tests (5,763 passed, 123 skipped, 39 warnings).
- The wrong red-channel mutation failed the new assertion; exact source restoration was verified and the focused test passed.
- git diff --check passed.

Residual limits:
- The admitted review's specialist assessments were parent substitutes; independent multi-role coverage remains unavailable.
- Tests used the pure NumPy fallback because OpenCV is not installed.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit a8b1ef4 into roboflow:develop Oct 19, 2026
36 checks passed
Borda added a commit that referenced this pull request Oct 20, 2026
`MaskAnnotator` and `HaloAnnotator` raised `ValueError` on grayscale
scenes, shaped `(H, W)` or `(H, W, 1)` or given as a Pillow "L" image,
because `_paint_masks_by_area` assigned a three-value BGR color to
single-channel pixels. Other annotators draw on the same scenes through
OpenCV, which writes the first (blue) channel of the color.

Paint grayscale canvases with that first channel, restore the singleton
channel axis that OpenCV drops in `addWeighted` and `blur`, and compute
the halo alpha from the single channel instead of `COLOR_BGR2GRAY`.
BGR scenes are unchanged.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: Codex <[email protected]>
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.

3 participants