Skip to content

fix(cv2): read transparent and 1-bit PNGs unchanged the way OpenCV does - #2588

Merged
Borda merged 4 commits into
roboflow:developfrom
kevin9327:fix/fallback-imread-gray-alpha-png
Sep 17, 2026
Merged

Borda merged 4 commits into
roboflow:developfrom
kevin9327:fix/fallback-imread-gray-alpha-png

Conversation

@kevin9327

Copy link
Copy Markdown
Contributor

Description

Without OpenCV installed, sv.IconAnnotator fails on a grayscale PNG icon with an alpha channel:

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

icon = np.zeros((16, 16, 2), dtype=np.uint8)
icon[4:12, 4:12] = (200, 255)                     # gray value, alpha
Image.fromarray(icon).save("icon.png")            # a grayscale PNG with alpha

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")
# with OpenCV:    draws the icon
# without OpenCV: ValueError: could not broadcast input array from shape (16,16,2) into shape (16,16,3)

sv.draw_image(scene, "icon.png", ...) fails the same way with ValueError: Image must have 3 or 4 channels.

Both functions read the file with cv2.imread(path, cv2.IMREAD_UNCHANGED) so the alpha channel survives. For that flag, the fallback backend in supervision/_cv2/_image.py returned np.asarray of the Pillow image, which is Pillow's layout rather than OpenCV's. OpenCV never returns a 2-channel or boolean image. I compared the two readers on PNGs in each mode Pillow opens them with (1, L, LA, P, RGB, RGBA, I;16, with and without a transparent color). They differ in three cases:

PNG cv2.imread(..., IMREAD_UNCHANGED) fallback on develop
grayscale with alpha (LA) (H, W, 4) uint8 BGRA (H, W, 2) uint8
RGB with a transparent color (tRNS) (H, W, 4) uint8 BGRA (H, W, 3) uint8, no alpha
1-bit (1) (H, W) uint8, 0/255 (H, W) bool

Palettes already had a special case that expands them to RGB or RGBA, as OpenCV does. This PR moves that case into a small helper, _opencv_unchanged_mode, which also handles the three modes above. The helper returns the Pillow mode to convert to, and the existing BGR/BGRA reordering does the rest. For all five modes the result is byte-identical to cv2.imread.

Motivation and Context

OpenCV is optional since the fallback backend was added, so these reads now run for anyone who installs supervision without opencv-python. Grayscale PNGs with alpha are common for single-color icons and logos: PNG optimizers such as optipng and oxipng store an RGBA image as gray+alpha whenever every pixel is gray. The same icon works with OpenCV installed and fails without it. An RGB icon with a transparent color doesn't raise, but it is pasted with its transparent pixels drawn black.

Changes Made

  • src/supervision/_cv2/_image.py: new _opencv_unchanged_mode(image) returns "RGBA" for palettes with transparency, grayscale with alpha, and RGB with a transparent color; "RGB" for other palettes; "L" for 1-bit; otherwise None. _read_pil_source converts to that mode for IMREAD_UNCHANGED. Other modes are read as before.
  • tests/cv2/test_image.py: test_fallback_imread_unchanged_matches_opencv_channels_and_depth checks shape, dtype and pixels against cv2.imread for gray+alpha, RGB with a transparent color, 1-bit, palette, and palette with a transparent color. The two palette cases already passed and cover the moved lines.
  • tests/annotators/test_core.py: TestIconAnnotator.test_draws_grayscale_icon_with_alpha draws a gray+alpha icon and checks that only its opaque square is drawn. It runs in the OpenCV-free CI jobs, where the parity test above is skipped.
  • docs/changelog.md: entry under Unreleased.

Out of scope: IMREAD_COLOR reads already matched OpenCV for all these files. 16-bit color PNGs still read as 8-bit in the fallback, because Pillow can't hold 16-bit RGB. Grayscale PNGs without alpha are still 2-D with both backends.

Testing

New tests on develop, with OpenCV installed:

E       AssertionError: assert ((2, 2, 2), dtype('uint8')) == ((2, 2, 4), dtype('uint8'))
E       AssertionError: assert ((1, 2, 3), dtype('uint8')) == ((1, 2, 4), dtype('uint8'))
E       AssertionError: assert ((2, 2), dtype('bool')) == ((2, 2), dtype('uint8'))
FAILED tests/cv2/test_image.py::test_fallback_imread_unchanged_matches_opencv_channels_and_depth[gray-alpha]
FAILED tests/cv2/test_image.py::test_fallback_imread_unchanged_matches_opencv_channels_and_depth[rgb-transparent-color]
FAILED tests/cv2/test_image.py::test_fallback_imread_unchanged_matches_opencv_channels_and_depth[one-bit]
3 failed, 2 passed, 50 deselected

On develop, without OpenCV (sys.modules["cv2"] = None, as in the OpenCV-free CI jobs):

E           ValueError: could not broadcast input array from shape (16,16,2) into shape (16,16,3)
FAILED tests/annotators/test_core.py::TestIconAnnotator::test_draws_grayscale_icon_with_alpha
1 failed

With this change:

$ pytest tests/cv2/test_image.py -k unchanged_matches_opencv_channels
5 passed, 50 deselected
$ pytest            # src doctests + tests, OpenCV installed
4095 passed, 1 skipped      (develop: 4089 passed, 1 skipped)
$ pytest tests/annotators tests/cv2 tests/utils tests/draw    # without OpenCV
648 passed, 19 skipped
$ ruff check && ruff format --check && docformatter --check   # changed files
All checks passed!
3 files already formatted

mypy src/supervision/_cv2/_image.py prints the same output on develop and on this branch.

  • 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 matched OpenCV mode by mode instead of converting every unchanged read to RGBA, because OpenCV itself keeps grayscale PNGs without alpha, RGB PNGs without a transparent color, and 16-bit grayscale PNGs as they are. The existing 16-bit test covers that last case.

🤖 Generated with Claude Code

The OpenCV-free backend returned Pillow's pixel layout for
IMREAD_UNCHANGED: grayscale with alpha as 2 channels, RGB with a
transparent color without alpha, and 1-bit images as booleans. OpenCV
returns BGRA and 8-bit arrays for these, so IconAnnotator and draw_image
failed on or ignored the transparency of such icons without OpenCV.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kevin9327
kevin9327 requested a review from SkalskiP as a code owner September 17, 2026 11:04
@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 (29c207e) to head (dfd8836).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2588   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11372   11382   +10     
=======================================
+ Hits         10368   10381   +13     
+ Misses        1004    1001    -3     
🚀 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:53
@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.

🟢 Approval recommended

The focused implementation correctly addresses the reported incompatibilities with comprehensive regression coverage.

Pull request overview

Aligns Pillow-based image loading with OpenCV’s unchanged PNG decoding behavior.

Changes:

  • Normalizes grayscale-alpha, transparent RGB/palette, and 1-bit images.
  • Adds parity and IconAnnotator regression tests.
  • Documents the fix in the changelog.
  • Assessment: code quality 5/5, testing 5/5, documentation 5/5.
File summaries
File Description
src/supervision/_cv2/_image.py Adds OpenCV-compatible Pillow mode conversion.
tests/cv2/test_image.py Tests unchanged-read parity with OpenCV.
tests/annotators/test_core.py Tests grayscale-alpha icon rendering.
docs/changelog.md Records the user-visible fix.
Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 0
  • 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 docs/changelog.md Resolved
@Borda
Borda merged commit 8debaa4 into roboflow:develop Sep 17, 2026
36 checks passed
Souptik96 added a commit to Souptik96/supervision that referenced this pull request Sep 18, 2026
AGENTS.md section 6 requires each changelog entry to link the PR rather
than the source issue. The entry was added before this PR had a number,
so the link is appended now, in the same trailing style as the roboflow#2582 and
roboflow#2588 entries.
Borda pushed a commit that referenced this pull request Sep 22, 2026
…es (#2588)

The OpenCV-free backend returned Pillow's pixel layout for
IMREAD_UNCHANGED: grayscale with alpha as 2 channels, RGB with a
transparent color without alpha, and 1-bit images as booleans. OpenCV
returns BGRA and 8-bit arrays for these, so IconAnnotator and draw_image
failed on or ignored the transparency of such icons without OpenCV.

---------

Co-authored-by: Claude Opus 5 <[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