Skip to content

fix(cv2): draw ellipses like OpenCV without OpenCV - #2740

Merged
Borda merged 6 commits into
roboflow:developfrom
px12811:fix/ellipse-opencv-parity
Oct 16, 2026
Merged

Borda merged 6 commits into
roboflow:developfrom
px12811:fix/ellipse-opencv-parity

Conversation

@px12811

@px12811 px12811 commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Description

The NumPy ellipse fallback did not match OpenCV. It sampled the ellipse with its
own angle grid, used Pillow's inward-growing strokes for thick outlines, and filled
arcs with Pillow's polygon rule. cv2.ellipse is reached by sv.EllipseAnnotator,
sv.RoundBoxAnnotator and the key-point ellipse annotators, so a plain
pip install supervision drew different pixels from the OpenCV backend.

This ports OpenCV's Ellipse2Poly / EllipseEx path:

  • OpenCV's 451-entry SinTable, stored as a compact float32 constant. It cannot be
    regenerated exactly from numpy.sin: 242 of the 451 entries differ in the last bit.
  • ellipse2Poly fixed-point sampling: step snapping, angle and arc normalization,
    and the 1/65536 rounding plus deduplication done by EllipseEx.
  • ThickLine for fixed-point ellipse points, where OpenCV skips the integer pre-clip
    because the line's own shift is 16, reusing the FillConvexPoly and disc-cap
    helpers from fix(cv2): draw thick lines and polylines like OpenCV without OpenCV #2727.
  • FillEdgeCollection for filled partial arcs, including the clipped-edge x
    correction that CollectPolyEdges applies.

thickness <= 1 follows the same OpenCV PolyLine -> Line path, so thin ellipses
are fixed too. No public API changes. circle is deliberately untouched; it is being
handled separately.

Refs #2674.

Minimal reproduction

import numpy as np
import cv2

from supervision._cv2._drawing import _ellipse

actual = np.zeros((80, 80), dtype=np.uint8)
expected = np.zeros_like(actual)
_ellipse(actual, (40, 40), (25, 15), 0, 0, 360, 255, thickness=2)
cv2.ellipse(expected, (40, 40), (25, 15), 0, 0, 360, 255, thickness=2)

print(
    int((actual > 0).sum()),
    int((expected > 0).sum()),
    int(np.count_nonzero((actual > 0) != (expected > 0))),
)
# develop: 308 380 82
# this PR: 380 380 0

Testing

  • pytest tests/cv2/test_drawing.py -q -> 92 passed.
  • pytest tests/cv2 -q --ignore=tests/cv2/test_integration.py -> 522 passed.
  • pytest src tests -q -> 5962 passed, 1 skipped, 10 failed. All ten failures are
    ImportError: metrics extra is required in tests/metrics/utils/test_aggregate.py;
    the metrics extra is not installed in this environment and the failures are
    unrelated to the changed files.
  • Seeded fuzz against OpenCV 5.0.0: 50,000 random ellipses (full, filled, rotated,
    partial arcs, off-canvas centers and degenerate axes) with 0 differing pixels.
  • pre-commit run --files src/supervision/_cv2/_drawing.py tests/cv2/test_drawing.py docs/changelog.md: all hooks pass, including ruff, docformatter, mypy and codespell.
  • The embedded sine table is checked bit-for-bit against the table in OpenCV's
    modules/imgproc/src/drawing.cpp in the test environment.

New tests cover full and filled ellipses, rotation, partial and past-full-turn arcs,
off-canvas geometry, zero axes, half-degree angle inputs and a seeded random sweep.

  • Added/updated tests, and the focused and cv2 suites pass locally
  • Added a changelog entry under Unreleased
  • Updated docs (no public API change; the fallback is private)

AI assistance: Codex helped port OpenCV's fixed-point routines and draft the tests.
I reviewed the implementation and ran the verification above.

@px12811
px12811 requested a review from SkalskiP as a code owner October 16, 2026 09:37
@px12811
px12811 force-pushed the fix/ellipse-opencv-parity branch from 5b3660c to d14c717 Compare October 16, 2026 09:38
@px12811
px12811 force-pushed the fix/ellipse-opencv-parity branch from d14c717 to 1f30072 Compare October 16, 2026 09:40
@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.65772% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 94%. Comparing base (3d06d6e) to head (2a050cc).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop   #2740    +/-   ##
========================================
  Coverage       94%     94%            
========================================
  Files           83      83            
  Lines        13491   13612   +121     
========================================
+ Hits         12675   12796   +121     
  Misses         816     816            
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda Borda added the bug Something isn't working label Oct 16, 2026
@Borda
Borda requested a balanced review from Copilot October 16, 2026 14:35

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

Filled fractional-angle arcs can select the wrong rasterization path and break OpenCV pixel parity.

1 open finding
What changed in this PR

Aligns Supervision’s NumPy ellipse fallback with OpenCV’s rasterization without changing the public API.

Changes:

  • Ports fixed-point ellipse sampling, strokes, and fills.
  • Adds pixel-equality tests for representative and randomized ellipses.
  • Documents the correction; circle drawing remains unchanged.
File Description
tests/​cv2/​test_drawing.py Adds OpenCV parity tests.
src/​supervision/​_cv2/​_drawing.py Implements OpenCV-style ellipse rasterization.
docs/​changelog.md Records the fallback correction.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/supervision/_cv2/_drawing.py Resolved
Changes:
- Integrate the fetched 0.31.0 release metadata and current documentation updates from develop into the ellipse parity branch.
- Preserve the PR ellipse note under Unreleased while retaining the target release notes and documentation examples.

Impact:
- Bring the PR branch up to the verified develop target while preserving the post-release boundary for the ellipse change.
- Keep the full target documentation and version updates in the local PR branch history.

Verification:
- Canonical gates: lint, format, types, tests, and review all passed.
- Full tests: 5694 passed, 123 skipped; 93% coverage.
- All-files pre-commit passed; no unmerged paths remain and staged diff checks passed.

Residual limits:
- Prior review limitations remain: independent specialist coverage was not validated, and local OpenCV reference execution was unavailable.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Add negative-axis tests for both axes and assert failure leaves the image unchanged.
- Add a partial filled-arc test for center inclusion and sector boundaries.

Impact:
- Protects ellipse fallback argument validation and pie-slice fill behavior from regression.

Verification:
- Targeted drawing tests: 33 passed, 65 skipped, 1 warning.
- Canonical gates: lint, format, types, and review passed; full suite 5,697 passed, 123 skipped, 39 warnings.
- git diff --check passed.

Residual limits:
- OpenCV-dependent parity tests skipped locally because OpenCV is unavailable; the historical Codecov comment does not identify its fourth uncovered line.

---
Co-authored-by: Codex <[email protected]>
Borda and others added 2 commits October 16, 2026 23:48
Changes:
- Expand seven ellipse and fixed-point rasterizer docstrings with coordinate units, rounding rules, scanline filling, clipping, cap scheduling, parameters, and return contracts.
- Add 33 doctest prompts covering arc sampling, degenerate geometry, sector filling, stroke caps, path closure, in-place painting, and fractional-angle fill selection.

Impact:
- Make the low-level ellipse fallback understandable through executable examples while preserving executable code unchanged.

Verification:
- Drawing module doctests and drawing tests: 44 passed, 65 skipped.
- Full pytest suite with coverage: 5704 passed, 123 skipped, 39 warnings; 94% total coverage.
- Repository-wide pre-commit hooks and git diff --check passed.
- AST comparison confirmed only docstrings changed.
- A temporary-copy mutation restoring the old unrounded fill-path condition failed the new rounding doctest as expected.

Residual limits:
- OpenCV is not installed, so reference parity checks were skipped; fallback doctests passed.
- The full suite emitted fallback, deprecation, plotting, and scenario-specific warnings.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit 138ef8e into roboflow:develop Oct 16, 2026
36 checks passed
jorge-asenjo added a commit to jorge-asenjo/supervision that referenced this pull request Oct 17, 2026
Merge develop at ffd0ac0, which released 0.31.0 and merged roboflow#2741, roboflow#2740
and roboflow#2743. Only docs/changelog.md conflicted: the CompactMask.area entry
now opens the new Unreleased section and the rest matches develop.

roboflow#2741 now filters MaskAnnotator ROI crops with CompactMask.area > 0, so
that path uses the vectorized area; its tests pass unchanged.

Verification: full suite 5,735 passed, 123 skipped, 94% coverage (NumPy
fallback); compact mask, mask utility and annotator tests 601 passed with
both the fallback and OpenCV 5.0.0; pre-commit passed on the PR files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Borda added a commit to Lingikaushikreddy/supervision that referenced this pull request Oct 17, 2026
Changes:
- Merge the fetched develop target into the Pascal VOC rounding branch, including the Unreleased notes for PRs roboflow#2740, roboflow#2741, and roboflow#2743.
- Integrate OpenCV-compatible ellipse rasterization and its regression coverage.
- Integrate mask ROI handling that excludes all-False masks and its tests.
- Integrate overflow-safe mean-average-precision box extents and dtype regression tests.

Impact:
- Keeps the PR branch current so the roboflow#2748 changelog note can be added beside the target's Unreleased entries.
- Brings the target's drawing, mask annotation, and metric fixes into the local PR branch.

Verification:
- The three-tree merge completed automatically without conflicts.
- The staged merge diff check passed; all eight staged paths were reviewed.

Residual limits:
- None known.

---

Co-authored-by: Codex <[email protected]>
Borda added a commit that referenced this pull request Oct 20, 2026
* fix: draw ellipses like OpenCV without OpenCV
* fix: round ellipse arc angles before choosing the fill path
* test: cover ellipse fallback edge paths
* docs: explain ellipse rasterization and add doctests

---------

Co-authored-by: jirka <[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