fix(cv2): pad getTextSize height/baseline from actual stroke_width
_get_text_size approximated thickness-to-stroke padding with thickness // 2 formulas that diverge from the thickness - 1 stroke_width _put_text actually renders with. Past thickness 2 the padding grows too slowly, so heavy-stroke descender pixels can fall outside the reported box, breaking the documented enclosure guarantee. Both functions now derive stroke_width from one shared helper. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
This commit is contained in:
@@ -23,6 +23,7 @@ date_modified: 2026-07-16
|
||||
- The cv2-free fallback's `addWeighted` now raises `ValueError` for a non-default `dtype` instead of silently ignoring it.
|
||||
- The cv2-free fallback's `approxPolyDP` now uses an O(N) farthest-point heuristic for closed contours instead of an O(N^2) full distance matrix, avoiding memory blowups on large contours.
|
||||
- The cv2-free fallback now renders text with Pillow and the bundled DejaVu Sans face instead of reproducing OpenCV's Hershey stroke fonts. This drops the packaged 143 KB glyph table and its loader in favor of an existing dependency. Text drawn without cv2 now uses a proportional TrueType face, so glyph shapes and `getTextSize` metrics differ from OpenCV within the documented visual-divergence tier; the OpenCV path is unchanged. All Hershey font faces remain accepted for API compatibility but map to the same face (the italic modifier selects the oblique variant).
|
||||
- The cv2-free fallback's `getTextSize` now derives its height and baseline padding directly from the same `stroke_width` `putText` renders with, instead of a separate approximation. For `thickness > 2` the old formula under-padded the box, so a heavy stroke's descender pixels could fall outside the reported rectangle.
|
||||
- Fixed [#2427](https://github.com/roboflow/supervision/issues/2427): size-bucketed `sv.Precision` and `sv.F1Score` no longer count out-of-bucket detections as false positives. `sv.Recall` now matches only targets in the requested bucket, and all three metrics prioritize in-bucket targets during matching, matching COCO evaluation and `sv.MeanAveragePrecision`. A pixel-perfect detector now scores 1.0 in every bucket.
|
||||
- `sv.hex_to_rgba` now rejects multiple leading `#` characters instead of silently normalizing them, matching `sv.is_valid_hex` and the documented single optional prefix.
|
||||
- `sv.box_iou_batch` now upcasts box corners to `float64` before computing areas and intersections, returning `float32`. This fixes integer-dtype overflow (e.g. `int32` coordinates around `50_000` could previously wrap to a negative area and produce an incorrect `0.0` IoU) and gives full `float64` precision to callers that pass `float64`/`int64` coordinates directly. It does not recover precision already lost when coordinates are stored as `float32` before this function is called (e.g. `Detections.xyxy`, which is `float32` throughout the library) — such callers must upcast their own arrays to `float64`/`int64` before calling `box_iou_batch` to benefit from this fix. Results for small-coordinate inputs are unchanged.
|
||||
|
||||
@@ -46,20 +46,29 @@ def _load_font(font_face: int, font_scale: float) -> Any:
|
||||
return ImageFont.truetype(_font_path(bool(font_face & _FONT_ITALIC)), size)
|
||||
|
||||
|
||||
def _stroke_width(thickness: int) -> int:
|
||||
"""Map an OpenCV stroke thickness to the Pillow stroke_width it renders with."""
|
||||
return max(0, thickness - 1)
|
||||
|
||||
|
||||
def _get_text_size(
|
||||
text: str, fontFace: int, fontScale: float, thickness: int
|
||||
) -> tuple[tuple[int, int], int]:
|
||||
"""Return an OpenCV-shaped ``((width, height), baseline)`` for the face.
|
||||
|
||||
Height is the font ascent and baseline the descent, both string-independent
|
||||
like OpenCV's contract, so consumers get stable row heights. Thickness pads
|
||||
the box the way OpenCV widens strokes.
|
||||
like OpenCV's contract, so consumers get stable row heights. Padding uses
|
||||
the same stroke_width _put_text renders with: Pillow's stroke dilates the
|
||||
glyph outline by stroke_width pixels on every side, so width grows by
|
||||
twice that (left and right) while height and baseline each grow by one
|
||||
stroke_width (top and bottom).
|
||||
"""
|
||||
font = _load_font(fontFace, fontScale)
|
||||
ascent, descent = font.getmetrics()
|
||||
width = round(font.getlength(text)) + max(0, thickness)
|
||||
height = ascent + (thickness + 1) // 2
|
||||
baseline = descent + thickness // 2
|
||||
stroke_width = _stroke_width(thickness)
|
||||
width = round(font.getlength(text)) + 2 * stroke_width
|
||||
height = ascent + stroke_width
|
||||
baseline = descent + stroke_width
|
||||
return (width, height), baseline
|
||||
|
||||
|
||||
@@ -87,7 +96,7 @@ def _put_text(
|
||||
return img
|
||||
|
||||
font = _load_font(fontFace, fontScale)
|
||||
stroke_width = max(0, thickness - 1)
|
||||
stroke_width = _stroke_width(thickness)
|
||||
x, y = round(org[0]), round(org[1])
|
||||
|
||||
def draw_text(draw: Any) -> None:
|
||||
|
||||
@@ -142,6 +142,28 @@ class TestPutText:
|
||||
assert rows.min() >= org[1] - height
|
||||
assert rows.max() <= org[1] + baseline
|
||||
|
||||
def test_reported_baseline_encloses_thick_stroke_descent(self) -> None:
|
||||
"""Keep the baseline padding matching the stroke_width putText renders.
|
||||
|
||||
A thickness of 7 (stroke_width 6) is past the point where the old
|
||||
``thickness // 2`` baseline formula under-padded relative to the
|
||||
``thickness - 1`` stroke_width _put_text actually uses, letting
|
||||
descender pixels fall outside the reported box.
|
||||
"""
|
||||
image = np.zeros((160, 320, 3), dtype=np.uint8)
|
||||
org = (20, 100)
|
||||
(_, height), baseline = _get_text_size(
|
||||
"person 0.87", _FONT_HERSHEY_SIMPLEX, 1.0, 7
|
||||
)
|
||||
|
||||
_put_text(
|
||||
image, "person 0.87", org, _FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 7
|
||||
)
|
||||
|
||||
rows, _ = np.nonzero(np.any(image, axis=2))
|
||||
assert rows.min() >= org[1] - height
|
||||
assert rows.max() <= org[1] + baseline
|
||||
|
||||
def test_rejects_bottom_left_origin(self) -> None:
|
||||
"""Reject the unsupported inverted-axis origin mode."""
|
||||
image = np.zeros((32, 64, 3), dtype=np.uint8)
|
||||
|
||||
Reference in New Issue
Block a user