Skip to content

fix(utils): convert every Pillow mode to 8-bit BGR or grayscale in pillow_to_cv2 - #2614

Merged
Borda merged 5 commits into
roboflow:developfrom
raghav-rathi:fix/pillow-to-cv2-modes
Sep 22, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
raghav-rathi:fix/pillow-to-cv2-modes

Conversation

@raghav-rathi

Copy link
Copy Markdown
Contributor

Description

pillow_to_cv2 passed raw mode bytes through: a 1-bit image came back as 0/1, a 16-bit or 32-bit integer image wrapped modulo 256, LA/PA crashed cvtColor with a two-channel array, and CMYK ink values were drawn as RGB. Every annotator, crop_image, resize_image, letterbox_image, plot_image and friends go through this helper when handed a PIL.Image.

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

sv.pillow_to_cv2(Image.new("1", (2, 1), color=1)).tolist()
# develop: [[1, 1]]              this PR: [[255, 255]]
sv.pillow_to_cv2(Image.fromarray(np.array([[55000]], dtype=np.uint16))).tolist()
# develop: [[216]]               this PR: [[214]]   (= cv2.imread of the same 16-bit PNG)
sv.pillow_to_cv2(Image.new("RGB", (1, 1), (10, 20, 30)).convert("CMYK")).tolist()
# develop: [[[225, 55, 245]]]    this PR: [[[30, 20, 10]]]
sv.BoxAnnotator().annotate(Image.new("LA", (20, 20), color=(0, 255)), sv.Detections(xyxy=np.array([[2, 2, 17, 17]], dtype=np.float32), class_id=np.array([0])))
# develop: cv2.error             this PR: annotated LA image

Every mode is now reduced to what cv2.imread returns for the same picture: 1-bit becomes 0/255; alpha is dropped (RGBA -> BGR, LA -> grayscale); 16-bit keeps its high byte, as libpng's png_set_strip_16 does when OpenCV reads a 16-bit PNG as 8-bit (32-bit integers are clipped to the 16-bit range first); F is clipped like Pillow's own convert("L"); CMYK, YCbCr, HSV and RGBX are converted to color through Pillow. RGB, RGBA, L and P are byte-identical to before.

Motivation and Context

Closes #2613. Same OpenCV-parity stream as #2591, #2592, #2601, #2602 and #2603, for in-memory Pillow images rather than files.

Changes Made

  • utils/conversion.py: pillow_to_cv2 routes single-channel modes (L, 1, LA, La, F) to 8-bit grayscale, deep integer modes (I, I;16*) to their high byte, and everything else through convert("RGB") to BGR. Docstring and doctest.
  • tests/utils/test_conversion.py: per-mode expectations (1-bit, LA, 16-bit, 32-bit, float, CMYK, HSV, RGBX, PA), YCbCr within Pillow's round-trip tolerance, a real-OpenCV parity test (pytest.importorskip("cv2")) comparing against cv2.imread of the same picture written to disk, and BoxAnnotator on an LA scene.
  • docs/changelog.md: entry under Unreleased.

Out of scope: the annotator wrapper pastes the 8-bit result back into the caller's image, so annotating an I;16 image in place still yields a dark 16-bit image. That is the paste-back, not the conversion.

Testing

  • New tests on develop: the 1-bit, 16-bit, 32-bit, CMYK and LA cases fail with the values above; the LA annotator case fails with cv2.error. With this change they pass.

  • Without OpenCV (NumPy fallback): tests/utils tests/annotators tests/key_points 735 passed, 1 skipped; full suite 3749 passed, 24 skipped (develop: 3737 / 23).

  • With OpenCV 5.0: tests/utils/test_conversion.py 27 passed, including the on-disk parity test.

  • Doctests pass; ruff, docformatter, codespell clean; mypy reports the same errors as develop.

  • 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

Additional Notes

While checking parity I found that the OpenCV-free imread fallback (_read_pil_source, #2602) and IconAnnotator (#2591) scale 16-bit with rint(v / 256), whereas OpenCV keeps the high byte; the two differ by one whenever the low byte is >= 128 (5000 -> 20 vs 19). This PR follows OpenCV for pillow_to_cv2. Happy to align the fallback in a follow-up if you want them identical.

@CLAassistant

CLAassistant commented Sep 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Borda Borda changed the title fix(utils): convert every Pillow mode to 8-bit BGR or grayscale in pillow_to_cv2 fix(utils): convert every Pillow mode to 8-bit BGR or grayscale in pillow_to_cv2 Sep 21, 2026
@Borda
Borda requested a balanced review from Copilot September 21, 2026 20:37
@Borda Borda added the bug Something isn't working label Sep 21, 2026
@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91%. Comparing base (2877b33) to head (8c6461b).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2614   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11590   11601   +11     
=======================================
+ Hits         10598   10613   +15     
+ Misses         992     988    -4     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

Copilot review overview

🟡 Changes recommended

Some valid integer modes and downstream grayscale helper paths remain unsupported.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 High severity · 1 Medium severity · 1 Low severity

Open (3)
What changed in this PR

Updates pillow_to_cv2 to consistently produce 8-bit OpenCV-compatible arrays from Pillow images.

Changes:

  • Normalizes grayscale, deep-integer, alpha, and color modes.
  • Adds conversion and annotator coverage.
  • Documents the behavior change.
File Description
tests/​utils/​test_conversion.py Adds per-mode and OpenCV parity tests.
src/​supervision/​utils/​conversion.py Implements mode-aware Pillow conversion.
docs/​changelog.md Documents the conversion fix.

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

Comment thread src/supervision/utils/conversion.py Resolved
Comment thread src/supervision/utils/conversion.py Resolved
Comment thread docs/changelog.md Resolved
raghav-rathi added a commit to raghav-rathi/supervision that referenced this pull request Sep 22, 2026
Review follow-up for roboflow#2614. pillow_to_cv2 hands back a single-channel
array for L, LA, 1 and deep grayscale modes, but tint_image could not
broadcast its BGR overlay into it and grayscale_image fed it to
COLOR_BGR2GRAY, so those modes still failed in the two helpers (as L
already did). Expand a 2-D scene to BGR first; letterbox_image already
documented grayscale input.

pillow_to_cv2 now picks the high-byte path from the array dtype (any
integer wider than 8 bits, signed or not) instead of a mode list, and
returns a writable copy for single-channel modes so annotators can draw
into it. The changelog entry links the PR.
raghav-rathi and others added 3 commits September 22, 2026 04:22
…llow_to_cv2

pillow_to_cv2 passed raw mode bytes through: a 1-bit image came back as
0/1, a 16-bit or 32-bit integer image wrapped modulo 256, a grayscale
image with alpha (LA, PA) crashed cvtColor with two channels, and CMYK
ink values were drawn as RGB. Every annotator, crop_image, resize_image,
letterbox_image, plot_image and friends go through this helper when
handed a Pillow image.

Reduce every mode to what cv2.imread returns for the same picture: 1-bit
becomes 0/255, alpha is dropped, deep integer images keep their high
byte (as libpng's png_set_strip_16 does), and CMYK, YCbCr, HSV and
padded RGB are converted to color through Pillow. RGB, RGBA, L and P
convert exactly as before.
Review follow-up for roboflow#2614. pillow_to_cv2 hands back a single-channel
array for L, LA, 1 and deep grayscale modes, but tint_image could not
broadcast its BGR overlay into it and grayscale_image fed it to
COLOR_BGR2GRAY, so those modes still failed in the two helpers (as L
already did). Expand a 2-D scene to BGR first; letterbox_image already
documented grayscale input.

pillow_to_cv2 now picks the high-byte path from the array dtype (any
integer wider than 8 bits, signed or not) instead of a mode list, and
returns a writable copy for single-channel modes so annotators can draw
into it. The changelog entry links the PR.
@Borda

Borda commented Sep 22, 2026

Copy link
Copy Markdown
Member

@raghav-rathi pls avoid force push once the PR review process has started, otherwise we have to restart it and it takes much longer 🦝

@Borda
Borda merged commit 2c6acd0 into roboflow:develop Sep 22, 2026
36 checks passed
Borda added a commit that referenced this pull request Sep 29, 2026
…illow_to_cv2` (#2614)

pillow_to_cv2 passed raw mode bytes through: a 1-bit image came back as
0/1, a 16-bit or 32-bit integer image wrapped modulo 256, a grayscale
image with alpha (LA, PA) crashed cvtColor with two channels, and CMYK
ink values were drawn as RGB. Every annotator, crop_image, resize_image,
letterbox_image, plot_image and friends go through this helper when
handed a Pillow image.

Reduce every mode to what cv2.imread returns for the same picture: 1-bit
becomes 0/255, alpha is dropped, deep integer images keep their high
byte (as libpng's png_set_strip_16 does), and CMYK, YCbCr, HSV and
padded RGB are converted to color through Pillow. RGB, RGBA, L and P
convert exactly as before.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <[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.

pillow_to_cv2 passes raw mode bytes through for 1-bit, 16-bit, LA and CMYK Pillow images

4 participants