Skip to content

fix(cv2): draw thick lines and polylines like OpenCV without OpenCV - #2727

Merged
Borda merged 5 commits into
roboflow:developfrom
kevin9327:fix/thick-line-fallback
Oct 15, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
kevin9327:fix/thick-line-fallback

Conversation

@kevin9327

@kevin9327 kevin9327 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

Without opencv-python, _cv2.line, _cv2.polylines and the outline form of _cv2.drawContours (thickness >= 0) at thickness >= 2 paint different pixels from OpenCV. They used Pillow's ImageDraw.line(width=...), which has square ends and its own edge rounding. OpenCV draws each segment as a fixed-point quadrilateral and puts a filled disc on its ends. This is the part of #2674 that #2675 left open, after the rectangle fix.

On 2,000 random lines on a 200×200 canvas with thickness 2–12, 2000/2000 differed from cv2.line on develop. The median gap was 24.2% of OpenCV's painted pixels and the largest 66.4%. With this PR: 0/2000.

Consumers on this path include OrientedBoxAnnotator, BoxCornerAnnotator, TraceAnnotator, TriangleAnnotator's outline, RoundBoxAnnotator, LineZoneAnnotator, the keypoint EdgeAnnotator, sv.draw_line and sv.draw_polygon (and so PolygonZoneAnnotator), whenever their thickness is 2 or more.

Motivation and Context

Since OpenCV is optional, the fallback is what a plain pip install supervision draws with. #2433 and #2439 say the fallback should match OpenCV. A comment on #2674 freed _line and _polylines, and I said there that I'm taking them.

Refs #2674

Changes Made

src/supervision/_cv2/_drawing.py. All of this is private, and the public API does not change.

  • _thick_line_mask: a port of OpenCV's ThickLine for 8-connected lines. It does the following:
    • Pre-clips an off-canvas segment to the canvas grown by thickness, as OpenCV does.
    • Builds the XY_SHIFT=16 fixed-point quadrilateral with cvRound (round half to even) offsets.
    • Puts round caps of radius (thickness + 1) // 2 on the requested ends. It reuses _paint_disc from fix(cv2): center thick rectangle borders on the edge #2675.
  • _fill_convex_fixed_point: a port of FillConvexPoly. It uses OpenCV's two walking edges, the rounded per-row slope, and C truncating division.
  • _fixed_point_line_pixels: a port of Line2, the fixed-point outline, with clipLine on the scaled canvas. It is vectorized per edge.
  • _clip_line: a port of clipLine, using the same double-precision product truncated toward zero.
  • _polylines and _draw_contours with thickness > 1 follow OpenCV's PolyLine and drawContours cap rules. Each segment gets an end cap, and an open polyline also gets a start cap. An open one-point polyline draws nothing, as in OpenCV.
  • _paint_around paints only the window around the points. Thin shapes on large frames then do not pay for a full-frame boolean index.
  • thickness <= 1 keeps the existing Pillow path, which already matched OpenCV.
  • Out of scope: _circle and _ellipse with thickness >= 2, and lineType=LINE_AA, which the fallback ignores as before.

tests/cv2/test_drawing.py

  • test_fallback_line_draws_and_matches_opencv_extent now asserts pixel equality instead of a bounding box with atol=1. That atol=1 is the reason this was not caught before.
  • New TestFallbackThickLine class with these tests:
    • Line cases: even and odd thickness, horizontal, vertical, a single point, clipped, and fully off-canvas with the cap reaching in.
    • polylines: open and closed at thickness 2, 3 and 7, plus one-point and repeated-point inputs.
    • An offset drawContours outline.
    • A seeded 200-line random test.
    • A test that does not need cv2.

Testing

  • New tests on develop: 20 failed, 11 passed. With this PR: 31 passed.
  • Full suite with opencv-python-headless 5.0.0: 5571 passed, 1 skipped. That includes test_ordinary_suite_passes_when_cv2_is_blocked.
  • pre-commit run on the changed files: clean (ruff, ruff-format, docformatter, mypy).
  • Fuzz against cv2.line / cv2.polylines / cv2.drawContours with 20,000 random cases each. Canvases were 5–120 px, points from -40 to 160 (so many are partly or fully off-canvas), thickness 2–24, and 1–7 points, open or closed. Result: 0 differing pixels for all three.

Timing (1920×1080×3 image, best of 3×20, ms per call):

case develop this PR
line corner to corner, t=2 7.61 5.80
line corner to corner, t=8 7.95 6.00
polylines 4-point zone, t=4 6.96 2.81
polylines 200-point contour, t=2 7.04 14.57
  • Added/updated tests, and the full suite passes locally
  • Updated docs (docstrings / mkdocs entry) for new or changed public API (no public API change)
  • Added a changelog entry in docs/changelog.md under Unreleased

Additional Notes

  • The port runs one Python-level fill per segment, so a 200-vertex closed outline is about 2× slower than Pillow (14.6 ms vs 7.0 ms on a 1080p frame). Lines and zone-sized polylines got faster because of the windowed paint. I can try vectorizing the scanline fill across segments if the dense-contour case matters.
  • The pre-clip of off-canvas thick lines exists in current OpenCV (4.x and 5.0), and I fuzzed against 5.0.0.

@kevin9327
kevin9327 requested a review from SkalskiP as a code owner October 14, 2026 00:21
@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 Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (e2c958f) to head (bd4a139).
⚠️ Report is 4 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop   #2727    +/-   ##
========================================
  Coverage       94%     94%            
========================================
  Files           83      83            
  Lines        13100   13316   +216     
========================================
+ Hits         12293   12506   +213     
- Misses         807     810     +3     
🚀 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 14, 2026
@Borda
Borda requested a balanced review from Copilot October 14, 2026 07:39

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

Oversized thickness values can stall rasterization, and existing rectangle regression tests were removed.

2 open findings
What changed in this PR

🟠 Request Changes — Adds OpenCV-compatible thick-line rasterization to the NumPy fallback.

Changes:

  • Implements fixed-point thick lines, caps, clipping, and polygon filling.
  • Applies rasterization to lines, polylines, and contour outlines.
  • Adds comparison tests and a changelog entry.

Quality: Code 4/5 · Tests 3/5 · Documentation 5/5 · Risk 3/5

File Description
src/​supervision/​_cv2/​_drawing.py Implements thick-line rasterization.
tests/​cv2/​test_drawing.py Adds pixel-equality tests but removes rectangle regressions.
docs/​changelog.md Documents corrected fallback behavior.

🧠 Review effort: Balanced


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

Comment thread src/supervision/_cv2/_drawing.py Resolved
Comment thread tests/cv2/test_drawing.py Resolved
Reject a line, polyline or contour thickness above OpenCV's MAX_THICKNESS
(32767) before rasterizing, sharing one validator with the rectangle path,
so an oversized value can no longer stall _fill_convex_fixed_point.

Restore the rectangle regression tests (OpenCV raster matrix, centered
border, NumPy-integer thickness, huge thickness) and add rejection tests
for the stroke paths.
pre-commit-ci Bot and others added 2 commits October 15, 2026 09:19
Changes:
- Add four regression cases for absent or empty thick polylines and zero-sized clipping bounds.
- Qualify the changelog pixel-parity claim to LINE_8 and document the existing LINE_AA limitation.

Impact:
- Protect the three previously uncovered drawing guard returns.
- Describe which fallback drawing calls match OpenCV without promising antialiasing support.

Verification:
- Full suite: 5582 passed, 97 skipped.
- OpenCV 5.0.0.93 drawing oracle: 69 passed, zero skipped.
- Repository-wide pre-commit and all five canonical gates passed.
- Independent source review completed 6500 reference comparisons.

Residual limits:
- Oracle evidence covers one OpenCV version and macOS arm64; finite probes are not exhaustive.
- Parent verified the documentation correction and added tests after the independent source review.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit 99c48fc into roboflow:develop Oct 15, 2026
36 checks passed
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