Skip to content

fix(cv2): write JPEG and WebP at OpenCV's default quality without OpenCV - #2592

Merged
Borda merged 9 commits into
roboflow:developfrom
kevin9327:fix/fallback-image-writers-opencv-quality
Sep 18, 2026
Merged

Borda merged 9 commits into
roboflow:developfrom
kevin9327:fix/fallback-image-writers-opencv-quality

Conversation

@kevin9327

Copy link
Copy Markdown
Contributor

Description

Without OpenCV installed, sv.ImageSink saves .jpg frames at JPEG quality 75 and .webp frames as lossy WebP. With OpenCV installed, the same call writes quality 95 and lossless WebP:

import numpy as np
import supervision as sv

frame = ...  # any BGR frame
with sv.ImageSink("out", overwrite=True, image_name_pattern="frame_{:05d}.webp") as sink:
    sink.save_image(frame)
# with OpenCV:    out/frame_00000.webp decodes to exactly `frame`
# without OpenCV: out/frame_00000.webp is lossy (PSNR 27.7 dB on a 320x240 test frame)

cv2.imwrite and cv2.imencode use OpenCV's encoder defaults when no params are given: IMWRITE_JPEG_QUALITY 95, and lossless WebP. The fallbacks in supervision/_cv2/_image.py drop params and call Image.save with no options, so Pillow's defaults apply: JPEG quality 75, and lossy WebP at quality 80. Here is the same 320×240 frame through each writer:

extension cv2.imwrite fallback on develop
.jpg / .jpeg / .jpe 43,592 bytes (quality 95) 13,217 bytes (quality 75)
.webp 190,984 bytes, lossless 17,110 bytes, PSNR 27.7 dB
.png lossless lossless

This PR adds _opencv_default_save_options(image_format), which returns {"quality": 95} for JPEG and {"lossless": True} for WebP. _imwrite and _imencode pass these options to Image.save. _imwrite looks the format up from the file extension with Image.registered_extensions(), the same table Image.save uses. With quality 95, Pillow's JPEG bytes for that frame are identical to OpenCV's.

Motivation and Context

These writers run for anyone without opencv-python. The fallback is used when OpenCV isn't installed:

  • sv.ImageSink.save_image, for frames saved with a .jpg or .webp name pattern;
  • sv.DetectionDataset.as_yolo, as_pascal_voc and as_coco (through save_dataset_images) and sv.ClassificationDataset.as_folder_structure, for images held in memory, which keep their original file names.

In each case, the stored images depended on whether OpenCV was installed. JPEGs had stronger compression artifacts, and WebP images, which OpenCV writes losslessly, lost their exact pixels.

Changes Made

  • src/supervision/_cv2/_image.py: new _opencv_default_save_options, used by _imwrite (format from the file extension) and _imencode (format from ext, as before).
  • tests/cv2/test_image.py: test_fallback_encoders_match_opencv_default_jpeg_quality compares the JPEG quantization tables, which the quality setting determines, against cv2.imencode. It uses tables rather than bytes so that libjpeg builds on different platforms can't break it. test_fallback_encoders_write_webp_losslessly_like_opencv decodes the WebP and expects both the original pixels and cv2.imencode's round trip. Both tests run for _imwrite and _imencode.
  • tests/utils/test_sinks.py: TestImageSink.test_saves_webp_images_losslessly saves a frame with a .webp pattern and reads it back with Pillow. It runs in the OpenCV-free CI jobs, where tests/cv2 is skipped.
  • docs/changelog.md: entry under Unreleased.

Out of scope: explicit params are still ignored by the fallback, as before. Supervision itself never passes them. Formats whose defaults already match stay unchanged, including PNG, BMP and TIFF.

Testing

New tests on develop, with OpenCV installed:

E       assert {0: [8, 6, 5,... 50, 50, ...]} == {0: [2, 1, 1,... 10, 10, ...]}
E       Mismatched elements: 7600 / 9216 (82.5%)
FAILED tests/cv2/test_image.py::test_fallback_encoders_match_opencv_default_jpeg_quality[imwrite]
FAILED tests/cv2/test_image.py::test_fallback_encoders_match_opencv_default_jpeg_quality[imencode]
FAILED tests/cv2/test_image.py::test_fallback_encoders_write_webp_losslessly_like_opencv[imwrite]
FAILED tests/cv2/test_image.py::test_fallback_encoders_write_webp_losslessly_like_opencv[imencode]
4 failed, 56 passed

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

E       Mismatched elements: 7600 / 9216 (82.5%)
E       Max absolute difference among violations: 99
FAILED tests/utils/test_sinks.py::TestImageSink::test_saves_webp_images_losslessly
1 failed, 5 passed, 2 skipped

With this change:

$ pytest tests/cv2/test_image.py tests/utils/test_sinks.py::TestImageSink
60 passed
$ pytest tests/cv2 tests/utils tests/dataset          # without OpenCV
648 passed, 19 skipped
$ pytest            # src doctests + tests, OpenCV installed
4094 passed, 1 skipped      (develop: 4089 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 only mapped the two lossy formats whose defaults differ and that OpenCV's standard wheels write. I left alone AVIF (the opencv-python wheel I tested can't write it) and JPEG 2000 (OpenCV's default output is itself lossy there, while Pillow's is lossless).

🤖 Generated with Claude Code

Given no parameters, cv2.imwrite and cv2.imencode write JPEG at quality
95 and WebP losslessly. The OpenCV-free fallback used Pillow's defaults,
JPEG at quality 75 and lossy WebP, so ImageSink and in-memory dataset
exports stored frames differently depending on whether OpenCV was
installed.

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

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2592   +/-   ##
=======================================
  Coverage       91%     91%           
=======================================
  Files           78      78           
  Lines        11388   11398   +10     
=======================================
+ Hits         10387   10397   +10     
  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 fallback still fails for OpenCV’s .jpe JPEG alias despite the PR claiming support for it.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Aligns Pillow-based image encoding with OpenCV’s default JPEG and WebP behavior.

Changes:

  • Applies JPEG quality 95 and lossless WebP options.
  • Adds fallback and ImageSink regression tests.
  • Documents the behavior change.
File summaries
File Description
src/supervision/_cv2/_image.py Configures Pillow encoder defaults.
tests/cv2/test_image.py Compares fallback output with OpenCV.
tests/utils/test_sinks.py Verifies lossless WebP output.
docs/changelog.md Records the fix.
Review details
  • Files reviewed: 4/4 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 src/supervision/_cv2/_image.py Resolved
Borda and others added 3 commits September 18, 2026 13:31
…gnored params

[resolve group] PR roboflow#2592 — items 5 10

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…le, upper-case-ext cases

[resolve group] PR roboflow#2592 — items 6 11 12 13 14

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…uide divergence

[resolve group] PR roboflow#2592 — items 7 8 15

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Comment thread tests/cv2/test_image.py Resolved
Comment thread tests/cv2/test_image.py Resolved
@Borda
Borda merged commit 5fe4979 into roboflow:develop Sep 18, 2026
36 checks passed
Borda added a commit that referenced this pull request Sep 22, 2026
…nCV (#2592)

Given no parameters, cv2.imwrite and cv2.imencode write JPEG at quality
95 and WebP losslessly. The OpenCV-free fallback used Pillow's defaults,
JPEG at quality 75 and lossy WebP, so ImageSink and in-memory dataset
exports stored frames differently depending on whether OpenCV was
installed.

---------

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>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[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