Skip to content

fix(cv2): center thick rectangle borders on the edge - #2675

Merged
Borda merged 9 commits into
roboflow:developfrom
atikulmunna:fix/cv2-rectangle-thick-stroke
Oct 7, 2026
Merged

Borda merged 9 commits into
roboflow:developfrom
atikulmunna:fix/cv2-rectangle-thick-stroke

Conversation

@atikulmunna

Copy link
Copy Markdown
Contributor

Description

The NumPy fallback drew a stroked rectangle entirely inside the rectangle, while OpenCV centers the stroke on the edges. Any box with thickness >= 2 came out thinner and 1 pixel smaller per side without opencv-python installed.

BoxAnnotator's default thickness is 2 and OpenCV is no longer a dependency, so this was the default path for a plain pip install supervision:

backend painted px painted bbox
opencv 596 x 19-81, y 19-61
fallback 392 x 20-80, y 20-60

Repro, run once with opencv-python and once without:

import numpy as np
import supervision as sv
from supervision._cv2 import BACKEND_NAME

detections = sv.Detections(
    xyxy=np.array([[20.0, 20.0, 80.0, 60.0]]),
    class_id=np.array([0]),
    confidence=np.array([0.9]),
)
scene = np.zeros((80, 100, 3), dtype=np.uint8)
painted = sv.BoxAnnotator().annotate(scene, detections).any(axis=2)
ys, xs = np.where(painted)

print(f"backend        : {BACKEND_NAME}")
print(f"painted pixels : {int(painted.sum())}")
print(f"painted bbox   : x {xs.min()}-{xs.max()}, y {ys.min()}-{ys.max()}")

Motivation and Context

Pillow's ImageDraw.rectangle(outline=1, width=...) only grows inward. OpenCV strokes each edge as a band centered on it and rounds the four joints with a filled disc, so the border spreads outside the rectangle as well as inside.

The existing test_fallback_line_draws_and_matches_opencv_extent compares only the raster bounding box with atol=1, and the error at thickness=2 is exactly 1 pixel per side, so it passed.

Part of #2674

Changes Made

  • _rectangle now rasterizes the stroke directly as four edge bands plus a corner disc, clipped to the canvas, instead of delegating to Pillow's outline=/width=.
  • Added _rectangle_mask and _disc helpers in src/supervision/_cv2/_drawing.py. The disc is built once at its own size and OR-ed into each corner window, so cost scales with the stroke, not the canvas.
  • thickness=1 and filled (thickness=-1) rectangles are unchanged, as is the public API.
  • Deliberately out of scope: _line, _circle, _polylines and _ellipse share the inward-stroke cause and are untouched here. See the two scoping questions in [Bug]: NumPy fallback draws thick rectangle borders inward instead of centering them on the edge #2674.

Testing

Band radius is 0 at thickness=1, else (thickness + 1) // 2, derived from OpenCV and checked against it. The patched _rectangle matches cv2.rectangle byte for byte on 1310 randomized and hand-picked cases (degenerate, reversed, negative and out-of-bounds corners, float corners, thickness 1 to 25), on both opencv-python 4.10.0 and 5.0.0.

New tests fail on develop and pass with this change. thickness=1 passes either way:

$ uv run pytest tests/cv2/test_drawing.py -k rectangle_stroke   # fix stashed
FAILED tests/cv2/test_drawing.py::test_fallback_rectangle_stroke_matches_opencv[2]
FAILED tests/cv2/test_drawing.py::test_fallback_rectangle_stroke_matches_opencv[3]
FAILED tests/cv2/test_drawing.py::test_fallback_rectangle_stroke_matches_opencv[4]
FAILED tests/cv2/test_drawing.py::test_fallback_rectangle_stroke_matches_opencv[7]
FAILED tests/cv2/test_drawing.py::test_fallback_rectangle_stroke_clips_to_the_canvas
5 failed, 1 passed, 11 deselected in 0.29s

Full suite, both CI legs, on Windows 11 / Python 3.12:

$ uv sync --frozen --group dev --extra metrics
$ uv run pytest tests/ -q                      # fallback backend
4154 passed, 30 skipped, 30 warnings in 100.64s

$ uv pip install opencv-python                 # cv2 5.0.0, backend "opencv"
$ uv run pytest tests/ -q
4375 passed, 1 skipped, 29 warnings in 170.23s
$ uv run pre-commit run --files src/supervision/_cv2/_drawing.py tests/cv2/test_drawing.py
check doctest fences.....................................................Passed
ruff check...............................................................Passed
ruff format..............................................................Passed
docformatter.............................................................Passed
mypy.....................................................................Passed
codespell................................................................Passed
  • 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

Not tested: macOS and Linux, and opencv-python-headless. The change is pure NumPy and Pillow with no platform-specific code, and the OpenCV reference was checked on two major versions.

I could not find a thickness at which OpenCV's own corner geometry is reproducible by simply expanding Pillow's bounds, which is why the corner disc is explicit. OpenCV's filled circle turns out to be exactly the integer disc x^2 + y^2 <= r^2, verified for radius 0 to 14, so _disc is exact rather than an approximation. That same fact would make _circle cheap to fix if you want it.

Pillow's `ImageDraw.rectangle(outline=1, width=...)` grows the border
inward only, so the NumPy fallback drew every `thickness >= 2` rectangle
thinner and smaller than OpenCV does. OpenCV strokes each edge as a band
centered on it and rounds the four joints with a filled disc, which is
exactly the integer disc.

Rasterize the stroke directly instead: four edge bands plus a corner
disc, clipped to the canvas. `thickness=1` and filled rectangles are
unchanged.

Part of roboflow#2674
@atikulmunna
atikulmunna requested a review from SkalskiP as a code owner October 5, 2026 09:36
@Borda
Borda requested a balanced review from Copilot October 5, 2026 22:15
@Borda Borda added the bug Something isn't working label Oct 5, 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.

Copilot review overview

🟡 Changes recommended

The changelog must link this PR instead of issue #2674.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
What changed in this PR

Fixes NumPy fallback rectangle strokes to match OpenCV’s centered borders.

Changes:

  • Adds edge-band and corner-disc rasterization.
  • Adds parity and clipping tests.
  • Documents the fix in the changelog.

Assessment: Code quality 5/5 · Testing 5/5 · Documentation 4/5

File Description
src/​supervision/​_cv2/​_drawing.py Implements centered rectangle strokes.
tests/​cv2/​test_drawing.py Tests OpenCV parity and clipping.
docs/​changelog.md Records the user-visible fix.

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

Comment thread docs/changelog.md Resolved
@codecov

codecov Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93%. Comparing base (3bc0301) to head (8d9983c).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2675   +/-   ##
=======================================
  Coverage       93%     93%           
=======================================
  Files           78      78           
  Lines        11930   11962   +32     
=======================================
+ Hits         11049   11081   +32     
  Misses         881     881           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…e-thick-stroke

# Conflicts:
#	docs/changelog.md
@atikulmunna

Copy link
Copy Markdown
Contributor Author

Addressed the review note in 5c79df2: the changelog entry links this PR instead of #2674, per AGENTS.md:104.

That commit also merges develop, which had added five entries at the top of Unreleased since this branch was cut and had left the PR unmergeable. Re-ran the full suite on the merged tree: 4533 passed with opencv-python, 4323 passed without it, and pre-commit is clean on the three changed files.

…e-thick-stroke

# Conflicts:
#	docs/changelog.md
Borda and others added 5 commits October 7, 2026 15:42
…thick-stroke

# Conflicts:
#	docs/changelog.md
Reword the module and _point docstrings to Pillow/NumPy and pixel coordinates.

[resolve group] PR roboflow#2675 — items 11

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Evaluate each corner disc only over its clipped window, coerce rectangle thickness with operator.index, and raise ValueError above 32767. Document the centered border in the _rectangle docstring.

[resolve group] PR roboflow#2675 — items 5 6 13

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Add a cv2-free golden test for the centered border, NumPy integer thickness, huge and invalid thickness, and 18 parametrized OpenCV parity cases.

[resolve group] PR roboflow#2675 — items 7 8

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Name the box, state the zero-height exception, and document the thickness limits.

[resolve group] PR roboflow#2675 — items 10

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
@Borda
Borda merged commit 24d7924 into roboflow:develop Oct 7, 2026
35 of 36 checks passed
@Borda Borda mentioned this pull request Oct 8, 2026
Borda added a commit that referenced this pull request Oct 8, 2026
Pillow's `ImageDraw.rectangle(outline=1, width=...)` grows the border
inward only, so the NumPy fallback drew every `thickness >= 2` rectangle
thinner and smaller than OpenCV does. OpenCV strokes each edge as a band
centered on it and rounds the four joints with a filled disc, which is
exactly the integer disc.

Rasterize the stroke directly instead: four edge bands plus a corner
disc, clipped to the canvas. `thickness=1` and filled rectangles are
unchanged.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[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