Skip to content

fix(annotators): draw grayscale PNG icons in IconAnnotator - #2591

Merged
Borda merged 6 commits into
roboflow:developfrom
kevin9327:fix/icon-annotator-grayscale-icon
Sep 18, 2026
Merged

Borda merged 6 commits into
roboflow:developfrom
kevin9327:fix/icon-annotator-grayscale-icon

Conversation

@kevin9327

Copy link
Copy Markdown
Contributor

Description

sv.IconAnnotator fails on a grayscale PNG icon without alpha, with or without OpenCV installed:

import numpy as np
from PIL import Image
import supervision as sv

Image.fromarray(np.full((16, 16), 200, dtype=np.uint8)).save("icon.png")   # grayscale PNG

detections = sv.Detections(xyxy=np.array([[8.0, 16.0, 40.0, 40.0]]))
scene = np.zeros((48, 48, 3), dtype=np.uint8)
sv.IconAnnotator(icon_resolution_wh=(16, 16)).annotate(scene, detections, icon_path="icon.png")
# IndexError: tuple index out of range
#   src/supervision/utils/image.py:453, in _overlay_image: `if overlay.shape[2] == 4:`

_load_icon_from_path reads the icon with cv2.imread(path, cv2.IMREAD_UNCHANGED) so an RGBA icon keeps its alpha channel. For a grayscale PNG, that flag also keeps the image as a 2-D (H, W) array. _overlay_image only handles (H, W, 3) and (H, W, 4) overlays, and it indexes overlay.shape[2] before anything else.

This PR expands a 2-D icon to BGR with cv2.cvtColor(..., cv2.COLOR_GRAY2BGR) right after loading. That is the array cv2.imread would return for the file without IMREAD_UNCHANGED. The icon is then letterboxed and cached as before.

Motivation and Context

icon_path is documented as a path to a PNG image, and grayscale is a standard PNG color type. Single-color icons and logos are often saved that way. PNG optimizers such as optipng and oxipng also store an RGB image as grayscale whenever all of its pixels are gray, so an icon that worked can start failing after it has been optimized.

Changes Made

  • src/supervision/annotators/core.py: _load_icon_from_path converts a 2-D icon to BGR, and its docstring explains why.
  • tests/annotators/test_core.py: TestIconAnnotator.test_draws_grayscale_icon draws a 16×16 gray PNG icon and checks that exactly its square is painted with its gray value.
  • docs/changelog.md: entry under Unreleased.

Out of scope: sv.draw_image rejects 2-D images on purpose with ValueError: Image must have 3 or 4 channels., so it is unchanged. Color icons, with or without alpha, follow the same code path as before.

Testing

New test on develop, with OpenCV installed and without it (sys.modules["cv2"] = None, as in the OpenCV-free CI jobs):

E       IndexError: tuple index out of range
src\supervision\utils\image.py:453: IndexError
FAILED tests/annotators/test_core.py::TestIconAnnotator::test_draws_grayscale_icon
1 failed, 2 passed

With this change:

$ pytest tests/annotators/test_core.py::TestIconAnnotator     # with and without OpenCV
3 passed
$ pytest            # src doctests + tests
4090 passed, 1 skipped      (develop: 4089 passed, 1 skipped)
$ ruff check && ruff format --check && docformatter --check   # changed files
All checks passed!
2 files already formatted

mypy src/supervision/annotators/core.py reports the same errors on develop and on this branch. Two of them move down 8 lines.

  • 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

I made the conversion in the icon loader, not in _overlay_image, so the loader's output always has the shape the overlay expects. The icon cache also stores the converted array, so the conversion runs once per path and resolution.

Related: #2588 fixes the OpenCV-free reader for grayscale PNGs that do have alpha. The two changes are independent.

🤖 Generated with Claude Code

Icons are read with IMREAD_UNCHANGED to keep alpha, which returns a
grayscale PNG without alpha as a 2-D array. The overlay only handles
BGR and BGRA, so annotate failed with IndexError. Expand grayscale
icons to BGR when loading them.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kevin9327
kevin9327 requested a review from SkalskiP as a code owner September 17, 2026 11:21
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91%. Comparing base (6c0fb71) to head (e3a2257).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2591   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11382   11388    +6     
=======================================
+ Hits         10381   10387    +6     
  Misses        1001    1001           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda
Borda requested a balanced review from Copilot September 17, 2026 12:54
@Borda Borda added the bug Something isn't working label Sep 17, 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 new test method lacks the required return type annotation.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes IconAnnotator so grayscale PNG icons are converted to BGR before resizing and overlaying.

Changes:

  • Converts two-dimensional grayscale icons to BGR.
  • Adds a pixel-accurate regression test.
  • Documents the fix in the changelog.

Assessment: Code quality 4/5; testing 4/5; documentation 5/5.

File summaries
File Description
src/supervision/annotators/core.py Normalizes grayscale icons to BGR.
tests/annotators/test_core.py Tests grayscale icon rendering.
docs/changelog.md Records the bug fix.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread tests/annotators/test_core.py Resolved
Borda and others added 3 commits September 17, 2026 19:01
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
…-grayscale-icon

# Conflicts:
#	docs/changelog.md
Challenge log: 3 as-suggested, 1 self-resolved, 0 rejected

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Comment thread docs/changelog.md Resolved
@Borda
Borda merged commit eb58b7b into roboflow:develop Sep 18, 2026
36 checks passed
Borda added a commit that referenced this pull request Sep 22, 2026
Icons are read with IMREAD_UNCHANGED to keep alpha, which returns a
grayscale PNG without alpha as a 2-D array. The overlay only handles
BGR and BGRA, so annotate failed with IndexError. Expand grayscale
icons to BGR when loading them.

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Jirka Borovec <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
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