Skip to content

fix(draw): scale 16-bit images down in draw_image - #2603

Merged
Borda merged 5 commits into
roboflow:developfrom
kevin9327:fix/draw-image-16-bit-png
Sep 21, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
kevin9327:fix/draw-image-16-bit-png

Conversation

@kevin9327

Copy link
Copy Markdown
Contributor

Description

With OpenCV installed, sv.draw_image draws a 16-bit PNG with every nonzero channel saturated to 255:

import numpy as np
import supervision as sv
from supervision import _cv2 as cv2

logo = np.zeros((8, 8, 3), dtype=np.uint8)
logo[:] = (0, 0, 200)                                   # BGR red
cv2.imwrite("logo16.png", logo.astype(np.uint16) * 257)  # the same red, saved at 16 bits

scene = np.full((20, 20, 3), 50, dtype=np.uint8)
scene = sv.draw_image(scene, "logo16.png", opacity=1.0, rect=sv.Rect(x=5, y=5, width=8, height=8))
print(scene[8, 8])
# develop:     [  0   0 255]
# this branch: [  0   0 201]

draw_image reads an image path with cv2.IMREAD_UNCHANGED to keep the alpha channel. That flag also keeps a 16-bit PNG at 16 bits, but the rest of the function assumes 8 bits: cv2.convertScaleAbs saturates both the alpha and the blended pixels to 0..255, so any 16-bit value from 256 up draws as 255. A dark gray logo is drawn white, and so is any color whose three channels are all nonzero.

sv.IconAnnotator reads its icons the same way, and #2591 added the fix there: _load_icon_from_path scales a 16-bit icon down with np.clip(np.rint(icon / 256), 0, 255). This PR applies the same scaling in draw_image when it reads an image from a path.

Motivation and Context

Image editors export 16-bit PNGs when a document is in 16 bits per channel, and a logo or watermark file passed to draw_image can be one of them. Without OpenCV, the fallback reader already returns a 16-bit color PNG at 8 bits, because Pillow can't hold 16-bit RGB, so the same call drew correctly there and only the OpenCV path was affected.

Changes Made

  • src/supervision/draw/utils.py: after cv2.imread, scale a uint16 image down to uint8 in the same way as _load_icon_from_path. The image argument docs say so.
  • tests/draw/test_utils.py: test_draw_image_16_bit_file_draws_its_colors, for BGR and BGRA, returns a 16-bit image from a patched cv2.imread (as TestIconAnnotator.test_draws_16_bit_color_icon does) and expects the 8-bit colors in the scene. The patch keeps the test independent of which backend is installed, since the fallback can't write 16-bit color PNGs.
  • docs/changelog.md: entry under Unreleased.

Out of scope: arrays passed directly are drawn as before. The parameter is typed NDArray[np.uint8], and the caller controls what they pass. Grayscale files are still rejected, as the docstring states.

Testing

New tests on develop:

E       Mismatched elements: 300 / 1200 (25%)
E        [5, 5, 0]: 255 (ACTUAL), 100 (DESIRED)
E        [5, 5, 1]: 255 (ACTUAL), 50 (DESIRED)
E        [5, 5, 2]: 255 (ACTUAL), 200 (DESIRED)
FAILED tests/draw/test_utils.py::test_draw_image_16_bit_file_draws_its_colors[3]
FAILED tests/draw/test_utils.py::test_draw_image_16_bit_file_draws_its_colors[4]
2 failed

It fails the same way without OpenCV, where the fallback's convertScaleAbs saturates just as OpenCV's does.

With this change:

$ pytest tests/draw/test_utils.py -k 16_bit
2 passed
$ pytest tests/draw tests/annotators          # without OpenCV
383 passed      (develop: 381 passed)
$ pytest            # src doctests + tests, OpenCV installed
4107 passed, 1 skipped      (develop: 4105 passed, 1 skipped)
$ ruff check && ruff format --check && docformatter --check   # changed files
All checks passed!
2 files already formatted

mypy on the changed source and test files reports the same errors on develop and on this branch. I also ran the snippet above on real 16-bit BGR and BGRA PNGs with OpenCV installed: [0 0 255] before, [0 0 201] after. Without OpenCV, both give [0 0 200].

  • 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

The rounding matches the icon loader, so 200 * 257 becomes 201 rather than the fallback's 200, which keeps the high byte. I kept the icon loader's rounding rather than add a second convention. The logic is two lines, so I repeated it instead of moving it into a shared helper between annotators/core.py and draw/utils.py. I'm happy to extract one if you'd prefer.

🤖 Generated with Claude Code

draw_image reads image paths with IMREAD_UNCHANGED, which keeps a 16-bit
PNG at 16 bits with OpenCV installed. The blend into the 8-bit scene then
saturated every nonzero channel to 255. Scale 16-bit images to 8 bits on
load, as the IconAnnotator icon loader already does.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kevin9327
kevin9327 requested a review from SkalskiP as a code owner September 18, 2026 10:16
@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 18, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2603   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11484   11486    +2     
=======================================
+ Hits         10491   10493    +2     
  Misses         993     993           
🚀 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 18, 2026 10:49
@Borda Borda added the bug Something isn't working label Sep 18, 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 BGRA test does not verify scaling of semi-transparent 16-bit alpha values.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes color saturation when draw_image loads 16-bit images.

Changes:

  • Converts path-loaded uint16 images to uint8.
  • Adds BGR/BGRA tests and changelog documentation.
  • Assessment: Code 5/5, Tests 4/5, Docs 5/5.
File summaries
File Description
src/supervision/draw/utils.py Scales loaded 16-bit images.
tests/draw/test_utils.py Tests 16-bit BGR/BGRA drawing.
docs/changelog.md Documents the 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/draw/test_utils.py Resolved
Changes:
- Add a non-multiple uint16 draw-image regression that asserts rounding 51400 to 201 while retaining semi-transparent BGRA coverage.
- Correct the draw-image changelog to describe clipping only for channel values above the 8-bit range.

Impact:
- Prevents a truncating uint16 conversion from passing the regression test.
- Keeps release notes accurate for low-valued 16-bit channels.

Verification:
- uv run pytest tests/draw/test_utils.py -k 16_bit — 2 passed.
- uv run pytest tests/draw — 109 passed.
- uv run ruff check and uv run ruff format --check on changed files — passed.
- git diff --check — passed.

Residual limits:
- Full suite has environment failures from the missing metrics extra and one OpenCV harness test; mypy is not installed.
- Independent review provenance remains unavailable.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit 1a0c035 into roboflow:develop Sep 21, 2026
36 checks passed
Borda added a commit that referenced this pull request Sep 22, 2026
draw_image reads image paths with IMREAD_UNCHANGED, which keeps a 16-bit
PNG at 16 bits with OpenCV installed. The blend into the 8-bit scene then
saturated every nonzero channel to 255. Scale 16-bit images to 8 bits on
load, as the IconAnnotator icon loader already does.

---------

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: 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