Skip to content

fix(cv2): read CMYK images unchanged as color without OpenCV - #2602

Merged
Borda merged 3 commits into
roboflow:developfrom
kevin9327:fix/fallback-imread-cmyk-unchanged
Sep 21, 2026
Merged

Borda merged 3 commits into
roboflow:developfrom
kevin9327:fix/fallback-imread-cmyk-unchanged

Conversation

@kevin9327

@kevin9327 kevin9327 commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

Without OpenCV installed, sv.IconAnnotator and sv.draw_image draw a CMYK JPEG or TIFF in the wrong colors, and only where it has black ink. With OpenCV installed, the same calls draw it correctly:

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

Image.new("RGB", (8, 8), (200, 0, 0)).convert("CMYK").save("logo.jpg")  # a red CMYK JPEG
scene = np.full((20, 20, 3), 50, dtype=np.uint8)
scene = sv.draw_image(scene, "logo.jpg", opacity=1.0, rect=sv.Rect(x=5, y=5, width=8, height=8))
print(scene[8, 8])
# with OpenCV:    [  1   1 201]  (the logo's red)
# without OpenCV: [50 50 50]     (nothing drawn)

Both read the image with cv2.IMREAD_UNCHANGED to keep an alpha channel. For CMYK, OpenCV converts to color even with that flag: a CMYK JPEG comes back as BGR, and a CMYK TIFF as BGRA with an opaque alpha channel (libtiff's RGBA reader). The fallback's _opencv_unchanged_mode in supervision/_cv2/_image.py has no case for Pillow's CMYK mode, so it returned the four ink channels unchanged, and _read_pil_source then reordered them as if they were RGBA. The black channel became alpha, and cyan, magenta and yellow were drawn as red, green and blue. A red logo has no black ink, so it came back fully transparent.

This PR maps CMYK to RGB for a JPEG and to RGBA (opaque) for a TIFF. It's the same kind of case as the grayscale-with-alpha, transparent-color and 1-bit modes that #2588 aligned.

Motivation and Context

This fallback runs for anyone without opencv-python. CMYK is the usual color space for images prepared for print, such as logos exported from a print workflow, and IMREAD_UNCHANGED is how IconAnnotator and draw_image load their images. With OpenCV installed these images already work.

Changes Made

  • src/supervision/_cv2/_image.py: _opencv_unchanged_mode returns RGB for a CMYK JPEG and RGBA for a CMYK TIFF. Docstring updated.
  • tests/cv2/test_image.py: test_fallback_imread_unchanged_converts_cmyk_like_opencv writes random CMYK pixels, black channel included, as .jpg and .tif, and compares _imread(..., IMREAD_UNCHANGED) with cv2.imread: the shape and dtype must match exactly, and the values must be within 2. Pillow's and libjpeg's CMYK-to-RGB rounding differ by up to 2, which is also true of the existing IMREAD_COLOR path.
  • tests/annotators/test_core.py: TestIconAnnotator.test_draws_cmyk_jpeg_icon draws a CMYK JPEG icon and expects its color. It runs in the OpenCV-free CI jobs, where tests/cv2 is skipped.
  • docs/changelog.md: entry under Unreleased.

IMREAD_COLOR reads are unchanged. They already went through convert("RGB") and match OpenCV.

Testing

New tests on develop, with OpenCV installed:

E       AssertionError: assert ((8, 8, 4), dtype('uint8')) == ((8, 8, 3), dtype('uint8'))
FAILED tests/cv2/test_image.py::test_fallback_imread_unchanged_converts_cmyk_like_opencv[.jpg]
E       Mismatched elements: 252 / 256 (98.4%)
E        [0, 0, 3]: 217 (ACTUAL), 255 (DESIRED)
FAILED tests/cv2/test_image.py::test_fallback_imread_unchanged_converts_cmyk_like_opencv[.tif]
2 failed, 1 passed

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

E       Mismatched elements: 768 / 6912 (11.1%)
E        [8, 16, 0]: 0 (ACTUAL), 90 (DESIRED)
FAILED tests/annotators/test_core.py::TestIconAnnotator::test_draws_cmyk_jpeg_icon
1 failed, 2 skipped

With this change:

$ pytest tests/cv2/test_image.py tests/annotators/test_core.py -k cmyk
3 passed
$ pytest tests/cv2 tests/annotators tests/draw          # without OpenCV
444 passed, 19 skipped      (develop: 443 passed, 19 skipped)
$ pytest            # src doctests + tests, OpenCV installed
4108 passed, 1 skipped      (develop: 4105 passed, 1 skipped)
$ ruff check && ruff format --check && docformatter --check   # changed files
All checks passed!
3 files already formatted

mypy on the changed source and test files reports the same errors 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 compared _imread with cv2.imread (opencv-python 5.0.0) for both flags on JPEG, TIFF (uncompressed and LZW), BMP, GIF, PPM, WebP and JPEG 2000 files in the common Pillow modes. The only other differences I found are rare TIFF variants (CIELab, gray with alpha, RGBA with unassociated alpha, which OpenCV premultiplies, and four samples without an alpha tag), a 16-bit PGM, which Pillow reads as 32-bit integers, and a 16-bit color PNG, which Pillow reads at 8 bits. I left those out of scope.

🤖 Generated with Claude Code

With IMREAD_UNCHANGED, OpenCV converts CMYK JPEGs to BGR and CMYK TIFFs
to opaque BGRA. The Pillow fallback returned the raw ink channels in
BGRA order, so IconAnnotator and draw_image used black ink as alpha.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kevin9327
kevin9327 requested a review from SkalskiP as a code owner September 18, 2026 10:10
@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 (78898db) to head (431e476).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2602   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11482   11484    +2     
=======================================
+ Hits         10489   10491    +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:15
@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.

🟢 Approval recommended

The focused implementation matches OpenCV behavior and includes appropriate unit, integration, and documentation updates.

Pull request overview

Aligns Pillow fallback decoding of CMYK JPEG/TIFF images with OpenCV.

Changes:

  • Converts CMYK JPEG to BGR and TIFF to opaque BGRA.
  • Adds decoder parity and IconAnnotator regression tests.
  • Documents the fix in the changelog.

Assessment: Code quality 5/5 · Testing 5/5 · Documentation 5/5 · Risk 1/5

File summaries
File Description
src/supervision/_cv2/_image.py Adds CMYK mode conversion.
tests/cv2/test_image.py Tests OpenCV decoding parity.
tests/annotators/test_core.py Tests CMYK icon rendering.
docs/changelog.md Records the bug 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.

@Borda
Borda merged commit d79110b into roboflow:develop Sep 21, 2026
36 checks passed
Borda added a commit that referenced this pull request Sep 22, 2026
With IMREAD_UNCHANGED, OpenCV converts CMYK JPEGs to BGR and CMYK TIFFs
to opaque BGRA. The Pillow fallback returned the raw ink channels in
BGRA order, so IconAnnotator and draw_image used black ink as alpha.

---------

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

3 participants