Commit Graph

62 Commits

Author SHA1 Message Date
Piotr Skalski caf060521d
refactor: enrich `KeyPoints` with visibility mask, split confidence fields, and redesign uncertainty annotator (#2286)
- Added `KeyPoints.visible` mask support for per-keypoint visibility
- Split confidence into `keypoint_confidence` and `detection_confidence`
- Kept legacy `KeyPoints.confidence` as deprecated forwarding alias
- Updated `KeyPoints` slicing/filtering to preserve visibility and confidence fields
- Fixed `KeyPoints.__getitem__` row-index normalization for NumPy scalar, 0-D array, and boolean indexing
- Fixed `detection_confidence` indexing to use normalized row indices
- Updated `VertexAnnotator` to skip invisible keypoints
- Updated `EdgeAnnotator` to skip invisible keypoints and edges
- Added per-class skeleton support to `EdgeAnnotator`
- Added multi-skeleton support to `VertexLabelAnnotator`
- Added label validation for `VertexLabelAnnotator`
- Added color-list length validation for keypoint annotators
- Added `VertexEllipseAreaAnnotator`
- Added `VertexEllipseOutlineAnnotator`
- Added `VertexEllipseHaloAnnotator`
- Kept/exported `VertexEllipseAnnotator` alongside the new ellipse variants
- Standardized keypoint annotator docstrings and executable examples
- Added/updated `validate_detection_confidence` and `validate_visible`
- Removed/cleaned old keypoint validator shims
- Added regression tests for visibility, confidence fields, multi-skeleton behavior, and indexing edge cases
- Updated helpers and RF-DETR/keypoint tests for the new confidence/visibility model
- Added API design principles to contributing docs
- Ignored local multi-skeleton test script in `.gitignore`

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
2026-06-11 18:34:33 +02:00
Tamil Adhavan S K 8a4063086f
chore: update YOLO OBB annotation export support (#2302)
* fix(yolo): validate OBB corner shape and test is_obb=False passthrough
* docs(config): add attribute docstring to ORIENTED_BOX_COORDINATES

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2026-06-10 15:28:42 +02:00
Shahid Ul Islam a549f44792
Add OBB support to ConfusionMatrix via MetricTarget (#2247)
* feat(metrics): OBB support in ConfusionMatrix, MASKS guard, shape validation
* refactor(tests): extract reusable ConfusionMatrix MASKS test cases
* refine(metrics): exclude metric_target from ConfusionMatrix.__eq__
* refactor(metrics): consolidate _assert_supported_target call sites
* fix(metrics): normalise OBB (N,4,2) shape explicitly in detections_to_tensor
* test(metrics): add OBB wrong-target-cols case to validate_input_tensors
* test(metrics): add OBB edge-case parametrize cases to detections_to_tensor
* test(metrics): replace validate_input_tensors with _validate_input_tensors in test_detection
* refactor(metrics): make ConfusionMatrix unhashable
* fix(metrics): add shape validation to evaluate_detection_batch
* fix(metrics): cast class_id to float32 in detections_to_tensor
* test(metrics): fix test_evaluate_detection_batch targets shape

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
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>
2026-06-10 13:29:33 +02:00
Agis Kounelis ace3ebd03e
fix(detection): make `Detections.area` OBB-aware (#2306)
* fix(detection): make Detections.area OBB-aware

When detections carry ORIENTED_BOX_COORDINATES (the four xyxyxyxy corners),
the area property returned the area of the derived axis-aligned bounding
box instead of the rotated body. The AABB overestimates by up to ~2x for a
45-degree rotation, which silently miscomputes downstream values — most
visibly the area-sorted z-ordering inside MaskAnnotator / HaloAnnotator,
and any user code that filters detections by area.

* docs(detection): use string literal in Detections.area doctest
* test(detection): single-line docstring on test_uses_oriented_box_corners_when_present
* fix(detection): validate (N,4,2) shape of OBB data field in Detections.area
* perf(detection): replace np.roll pair with cross-diagonal shoelace in Detections.area
* perf(detection): cast x/y slices to float64 instead of full corners array
* refactor(detection): extract obb_polygon_area to detection/utils/boxes.py
* test(detection): add test_raises_on_malformed_obb_coordinates_shape
* test(detection): assert per-branch dtype contract for Detections.area
* docs(detection): document OBB dispatch contract and dtype in Detections.area docstring

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2026-06-09 22:20:34 +02:00
Agis Kounelis 3b485f719a
refine(detection): make `with_nms` and `with_nmm` OBB-aware (#2303)
* fix(detection): make with_nms and with_nmm OBB-aware
* perf(detection): bound rasterization canvas in oriented_box_iou_batch
* fix(detection): with_nmm OBB/AABB xyxy fix; 3-path dispatch docs
* fix(detection): shape validation, NMM assert, docstring/Examples
* test(detection): with_nmm fallback, OBB AABB fix, boundary and IOS tests
* docs(changelog): document OBB with_nms/nmm behaviour change for #2303
* docs(detection): convert OBB NMS/NMM examples to doctests
* refactor(test): group OBB NMS/NMM tests into classes
* refactor(test): merge duplicate NMS class-awareness tests via parametrize
* refactor(test): parametrize overlap-metric and dispatch tests

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
2026-06-09 13:11:09 +02:00
Agis Kounelis c92458b70e
fix(dataset): preserve OBB rotation in `DetectionDataset.as_yolo` (#2289)
DetectionDataset.from_yolo accepts is_obb=True and stores the four
corners in detections.data["xyxyxyxy"], but DetectionDataset.as_yolo
has no matching option and only reads xyxy/mask. The standard
from_yolo -> split -> as_yolo flow silently writes 5-token
axis-aligned lines, and re-loading the saved file with is_obb=True
crashes the validator because it expects 9 tokens.

Add is_obb to as_yolo, save_yolo_annotations, and
detections_to_yolo_annotations. When True, the four corners from
data["xyxyxyxy"] are serialized via the existing object_to_yolo
polygon path. Masks are ignored, mirroring from_yolo(is_obb=True)
semantics. A missing xyxyxyxy raises ValueError early.

- Add UserWarning in as_yolo when area/approx params passed with is_obb=True (silently ignored)
- Add UserWarning in detections_to_yolo_annotations when mask present + is_obb=True
- Update ValueError message to include expected shape (N, 4, 2) for manual callers
- Add Google-style docstrings to detections_to_yolo_annotations and save_yolo_annotations
- Add test: N>1 OBB detections per image (corner indexing via data-dict slicing)
- Add test: dataset round-trip with background-only (no label file) image
- Add test: as_yolo() without is_obb=True on OBB-loaded dataset emits 5-token lines
- Replace all tempfile.TemporaryDirectory / os.path.join / os.makedirs
  with pytest tmp_path and pathlib Path
- Merge 3 load-mask tests into parametrized test_load_yolo_annotations_mask_behaviour
  (obb-no-mask, obb-force_masks-ignored, segmentation-produces-mask)
- Merge token-count tests into parametrized test_dataset_as_yolo_obb_output_token_count
  (obb-save-nine-tokens, default-save-five-tokens)
- Split corner accuracy into dedicated test_dataset_as_yolo_obb_round_trip_corner_accuracy
- Drop import os and import tempfile

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2026-06-08 15:31:04 +02:00
Andrew Barnes b82d6f95be
fix: normalize file extension filters (#2298)
* fix: normalize file extension filters
* fix(file): add is_file and empty-ext guards
* test(file): collapse extension tests into parametrized form
* fix: match multi-part extension suffix tails

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Codex <codex@openai.com>
2026-06-08 13:41:25 +02:00
Andrew Barnes b18a30ea1a
fix: support grayscale letterbox images (#2297)
- Delete letterbox_image alpha block (lines 266-270): block wrote to
  caller's input array, not image_with_borders; used wrong coordinate
  system (resized vs original dims); redundant since cv2.copyMakeBorder
  already sets alpha=0 in padded regions when given a 3-element value
- Add test_letterbox_image_for_rgba_opencv_image: asserts padded alpha=0,
  interior alpha preserved, and input array not mutated after call
- Update letterbox_image docstring: image param lists (H,W,3)/(H,W,4)/
  (H,W)/PIL shapes; add Note on BGRA alpha behavior; add grayscale doctest

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-06-07 11:06:21 -06:00
Andrew Barnes 35006d7342
fix: sort YOLO class names by numeric keys (#2296)
* fix: sort yolo class names by numeric keys
* fix(yolo): reject double-hyphen keys in _is_int_like predicate
* fix(yolo): raise ValueError for mixed numeric/non-numeric names keys
* test(yolo): parametrize _extract_class_names with all key-type cases
* refine(yolo): rename lambda param key→k to avoid shadowing outer variable
* docs(yolo): comment bool guard in _is_int_like
* docs(yolo): docstring for _extract_class_names

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-06-07 10:54:43 -06:00
Jirka Borovec 3410d92daa
refactor: privatize validation helpers (#2294)
* refactor: privatize validation helpers
* fix: correct error message in _validate_keypoint_confidence

- Fix f"({n, m})" -> f"({n}, {m})" (set literal -> proper shape string)
- Fix error message "1D" -> "2D" to match actual array dimensionality

* fix: correct error message in _validate_xy

- Fix f"({n, m},)" -> f"({n}, {m}, 2) or ({n}, {m}, 3)"
- Fix error message "2D" -> "3D" to match actual array dimensionality

* bump pydeprecate version to >=0.9,<0.10 and fix type ignore tag for decorator
* chore: extend deprecation removal timeline to 0.32.0 across validators

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-06-06 13:15:54 -06:00
Piotr Skalski 1e8a48559b
Revert "feat: store keypoints on detections (#2290)" (#2291)
This reverts commit e03111e67c.
2026-06-04 11:43:48 -06:00
Jirka Borovec e03111e67c
feat: store keypoints on detections (#2290)
* docs: add API design principles to contribution guidelines
* feat: store keypoints on detections
* test: add "keypoints" to internal test cases
* docs: document keypoints field semantics and add docstring + dtype guard
* refactor: deduplicate keypoints shape check and add K-mismatch guard
* docs: clarify Detections.keypoints vs sv.KeyPoints decision rule and add KeyPoints filter example
* feat(key_points): add KeyPoints.from_detections() cross-container adapter
* test: extend keypoints test coverage — dtype guard, __eq__, dynamic field sets
* test: expand keypoints test coverage (M7/M8)
* fix: correct validate_xy expected_shape and dimensionality message
* fix: add ndim guard in KeyPoints.from_detections
* test: add unit tests for KeyPoints.from_detections adapter
* refactor: fix class_id cast and import formatting in key_points

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-06-04 09:09:37 -06:00
Ritwij Aryan Parmar 7d2259669b
Fix OBB IoU for non-square canvases (#2282)
* Fix OBB IoU canvas dimensions
* test(metrics): fix OBB metric parametrize — remove MAP, add smoke test
* test(metrics): clarify MAP OBB test is smoke test only
* test(iou): parametrize OBB scaling invariance test with y-dominant case
* fix(iou): add empty-input guard and x/y axis docs to oriented_box_iou_batch

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-06-01 09:20:38 +02:00
Jirka Borovec 918b6139ef
feat(keypoints): add keypoint conversion bridge (#2277)
* feat(keypoints): add RF-DETR keypoint conversion bridge
* feat: add RF-DETR keypoint uncertainty visualization
* refactor(keypoints): remove deprecated RF-DETR keypoint conversion logic
* refactor: improve internal handling of keypoint data and detection utilities
* fix(keypoints): handle non-finite confidence values and empty keypoint arrays
* docs(keypoint): add VertexEllipseAnnotator to annotators docs
* docs(keypoints): add Example block to KeyPoints.from_rfdetr docstring
* docs(keypoints): document source_shape HW ordering in from_rfdetr
* feat(keypoints): validate precision_cholesky shape in from_rfdetr
* refine(keypoints): add warning log for silent precision matrix failures
* fix(keypoints): fix mypy type errors in VertexEllipseAnnotator
* test(keypoints): add confidence_threshold filter test for VertexEllipseAnnotator
* test(keypoints): add max_axis_length cap and constructor validator tests
* docs(keypoints): document max_axis_length=None risk in VertexEllipseAnnotator
* docs(keypoints): add Raises section to VertexEllipseAnnotator.annotate docstring
* docs(keypoints): document confidence scale convention in from_rfdetr
* docs(keypoints): note from_rfdetr input convention in KeyPoints class docstring
* fix(types): improve type hinting for internal and keypoints modules
* fix(keypoints): handle None class_id in from_rfdetr conversion

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-28 10:36:41 +02:00
Madhav-C 81218c5f1b
fix(coco): emit 1-indexed `category_id` in COCO export (#2276)
* fix): emit 1-indexed category_id in COCO export
* test): add regression and guard tests for 1-indexed category_id
* docs): warn in coco_annotations_to_detections that remap is required

---------

Co-authored-by: madhavcodez <madhavcodez@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-27 10:40:32 +02:00
Mahbod 2c3a2ef6f9
fix(detection): preserve `class_name` string dtype on empty `Detections.from_inference` (#2270)
* fix): preserve class_name string dtype on empty Detections.from_inference
* test): fix stale float64 dtype expectation in test_process_roboflow_result
* docs): document data[class_name] contract in from_inference Returns
* fix): set string-dtype class_name on empty from_ultralytics and from_vlm paths
* test): strengthen from_inference empty-path dtype test
* test): cover SDK .dict() path for empty predictions in from_inference
* docs): add docstring to process_roboflow_result
* test): use dtype.kind comparison for empty/non-empty class_name
* docs): update example in `process_roboflow_result` docstring

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-27 10:39:49 +02:00
Mahbod 2fdb970430
fix(annotators): avoid divide-by-zero in HeatMapAnnotator on empty detections (#2269)
When HeatMapAnnotator is called on a fresh annotator with empty detections
(common on the first frames of a video before the model produces any output),
self.heat_mask is all zeros, so temp / temp.max() raises
RuntimeWarning: invalid value encountered in divide and produces nan/inf
in-flight. Skip the normalisation when temp.max() == 0; the resulting
all-zero heat mask filters out via the > 0 check below, so the scene is
returned unchanged.

- Fix `kernel_size: int = 25` → `int | None = 25`; document None disables blur
- Add Note to annotate docstring: empty detections returns scene unchanged
- Add happy path test: single detection must produce visible heat output
- Add stateful tests: empty→real and real→empty sequence coverage

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-26 22:27:07 +02:00
Madhav-C befdb7c661
fix(dataset): make COCO annotation/image ids chainable across splits (#2267)
* fix(dataset): make COCO annotation/image ids chainable across splits (#768)

Exporting train/valid/test splits with DetectionDataset.as_coco
previously restarted image_id and annotation_id at 1 for every split,
producing three JSON files whose ids collided and could not be safely
merged into a single COCO collection.

Adds optional starting_image_id and starting_annotation_id parameters
to save_coco_annotations and DetectionDataset.as_coco (default 1 to
preserve existing behavior) and returns a (next_image_id,
next_annotation_id) tuple so callers can feed the result of one
export straight into the next:

    next_image, next_ann = train.as_coco(annotations_path="train.json")
    next_image, next_ann = valid.as_coco(
        annotations_path="valid.json",
        starting_image_id=next_image,
        starting_annotation_id=next_ann,
    )
    test.as_coco(
        annotations_path="test.json",
        starting_image_id=next_image,
        starting_annotation_id=next_ann,
    )

The images-only branch of as_coco (annotations_path=None) round-trips
the starting ids unchanged so chaining still works there.

Adds 4 regression tests covering defaults, custom starting ids,
end-to-end three-split chaining with global uniqueness assertions,
and the images-only round-trip.

* docs: address review polish on COCO id-chaining
* fix(dataset): align save_coco_annotations approximation_percentage default to 0.0
* docs(dataset): add one-line summary to save_coco_annotations docstring
* docs: add changelog entry for COCO id chaining (PR #2267)
* docs(dataset): document file_name uniqueness limitation in save_coco_annotations
* feat(dataset): validate starting_image_id and starting_annotation_id >= 1
* docs(dataset): add Example section to save_coco_annotations docstring
* docs(dataset): unpack final as_coco return value in chaining example
* test(dataset): add COCO chaining tests and fix test helper for zero detections

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-22 21:41:42 +02:00
Copilot cb259065a5
Add `from_coco` regression coverage for multi-segment COCO masks (#2258)
* test: cover from_coco multi-segment masks
* test: add from_coco multi-segment regression
* test: extract coco multi-segment fixture
* test(coco): move multi-segment mask test to TestFromCocoMasks
* test(coco): fix fixture area and document bbox intent
* test(coco): add force_masks=True sibling test for multi-segment masks
* test(coco): add uneven-length segments case to TestFromCocoMasks
* test(coco): parametrize force_masks in TestFromCocoMasks

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-22 20:42:11 +02:00
Copilot 6461d3fbac
Restructure annotator docs tabs to avoid Material’s 20-tab limit (#2257)
* Initial plan
* fix: split annotator docs tabs into categories
* test: harden annotator docs regression test
* docs: fix blur example assignment
* docs(annotators): restructure tabs, harden regression tests
* docs(annotators): remove broken oriented box preview image

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-22 19:54:33 +02:00
Copilot 5b883fed5b
Guard `InferenceSlicer` against OBB callback crashes when `thread_workers > 1` (#2256)
* fix: serialize OBB inference slicer callbacks
* test: simplify OBB slicer regression test
* refactor: simplify OBB slicer fallback path
* test: make OBB slicer regression deterministic
* fix(slicer): add thread_workers validation and lock for OBB warn flag
* docs(slicer): document OBB fallback, merge order, perf note, dual-use key

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-22 18:53:26 +02:00
Jirka Borovec e7376d558e
ci(tests): disable matplotlib GUI and exclude non-test dirs from collection (#2262) 2026-05-20 23:40:21 +02:00
Youssef Ibrahim 01ec36b31d
fix: return empty int ndarray instead of None for class_id on empty VLM parse (#2239)
When from_paligemma or from_google_gemini_2_0 find no detections (no regex
matches, JSON decode error, or empty bounding-box list), they previously
returned None for class_id. All other early-exit and filter paths already
return a zero-length ndarray of dtype int. This inconsistency causes
downstream AttributeError when callers unconditionally call .shape or
iterate over the result.

Affected paths:
- from_paligemma: matches.shape[0] == 0 branch
- from_google_gemini_2_0: JSONDecodeError branch and len(xyxy) == 0 branch

---------

Co-authored-by: YousefZahran1 <youssefzahran.y@gmail.com>
Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
2026-05-19 14:31:44 +02:00
SATISH K C 7e28315595
fix: preserve audio stream in process_video (#2252)
- Move `tempfile.mkstemp` + `os.close` inside `try` block so OSError (disk full,
  unwritable dir) is caught by the existing `except Exception` handler instead of
  propagating to the caller, preserving the warn-and-degrade contract
- Pass `dir=os.path.dirname(os.path.abspath(video_path))` so the temp file is on
  the same filesystem as the output, restoring `os.rename` semantics in `shutil.move`
- Initialise `tmp_path = None` before `try`; guard `finally` with
  `tmp_path is not None` to satisfy mypy and avoid referencing an unbound name
- Add `-loglevel error -nostats` so ffmpeg only writes actual errors to stderr
  (eliminates progress/stats spam that would buffer in PIPE indefinitely)
- Decode `result.stderr` and include it in the warning when ffmpeg exits
  non-zero, so failure messages surface diagnostically instead of being discarded
- Change bare `process_video(...)` call to `sv.process_video(...)` so the
  example matches the public API pattern and does not raise NameError for users
  copying the snippet
- Remove unused `import cv2` which was never referenced in the example body
- Clarify that missing/failing ffmpeg warns and continues rather than raising
- Add install hint for ffmpeg (apt/brew)
- Note that audio is truncated to match the processed video duration (-shortest)
- test_mux_audio_moves_file_on_success: mock subprocess.run returncode=0;
  assert shutil.move is called once with video_path as destination — catches
  any regression that drops the move call after a successful ffmpeg run
- test_mux_audio_swallows_subprocess_exception: mock subprocess.run raising
  OSError; assert no exception escapes _mux_audio and original file is intact
- Fix failed_result.stderr = b"" in test_mux_audio_warns_on_ffmpeg_failure
  to match the updated _mux_audio which now decodes result.stderr
- Skip _mux_audio when writer_worker.is_alive() after join timeout to avoid
  muxing an incomplete output file
- Fix test_mux_audio_moves_file_on_success: patch os.replace (not shutil.move)
  to match implementation changed in 2027938d
- Move four test_mux_audio_* free functions into TestMuxAudio class
- Strip mux_audio_ prefix from method names; class carries the unit
- Condense multi-line docstrings to single-line per testing rules
- Collapse test_warns_when_ffmpeg_missing, test_warns_on_ffmpeg_failure,
  test_swallows_subprocess_exception into one parametrized
  test_file_unchanged_on_failure[ffmpeg_missing|ffmpeg_fails|subprocess_raises]
- Promote two class methods back to module-level functions
- Collapse nested with-patch statements into single with a, b: form

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-19 14:09:45 +02:00
Jirka Borovec 153cde5854
feat(compact_mask): add `resize()` method and benchmark stage (#2227)
* feat: add resize() method and benchmark stage
* perf: optimise resize() — vectorised coords, L3 direct RLE
* refactor: split _rle_resize and extract _resize_crop
* test: expand resize() tests for scaling and edge cases
* refactor: switch resize helpers to F-order (column-major) RLE
* fix: merge True/True RLE junctions in _rle_join_cols
* perf: vectorize _rle_scale_col RLE re-encoding
* test: add density-dispatch and parallel-path resize tests
* refactor: harden resize() threading and RLE invariants
* fix: accurate resize timing and exact nearest-neighbour parity
* type: add explicit numpy typing to ndarray declarations

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-22 15:34:12 +02:00
Jirka Borovec de87030a21
refactor(rle): consolidate RLE primitives (#2230)
* consolidate RLE primitives
* remove wrapper fns, inline converters in CompactMask
* correct _delta_encode doctest example input
* add coverage for multi-byte base48, negative deltas, oversized RLE
* docs: fix RLE decoder example
* coerce mask_2d to bool before view(uint8) in _mask_to_rle_counts

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Codex <codex@openai.com>
2026-04-22 12:32:14 +02:00
Jirka Borovec 5a59dcdec6
refactor(masks): switch CompactMask RLE to F-order (#2228)
* refactor(masks): switch CompactMask RLE to F-order
* docs(masks): update _rle_area docstring example to F-order RLE
* test(masks): verify _rle_encode produces COCO-compatible F-order RLE

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-04-22 08:12:00 +02:00
Junghwan 6beabe3fb4
fix(dataset): reject COCO annotations whose file_name escapes the images directory (#2218)
* test: add regression tests for COCO loader path containment
* fix: reject COCO annotations whose file_name escapes the images directory
* docs: document ValueError contract in load_coco_annotations
* test: cover COCO equality-guard branch (file_name → images dir)
* test: cover COCO is_dir-guard branch (file_name → subdirectory)
* fix: wrap Path.resolve() for untrusted file_name in try/except
* test: add positive test for valid nested file_name in COCO loader
* test: add missing docstrings to COCO path-containment tests
* test: add `from __future__ import annotations` to JSON and CSV tests
* fix: replace `os.path.join` with `Path` for consistent path handling in COCO loader

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-18 00:58:44 +02:00
Junghwan 8df86e2599
fix(annotators): TraceAnnotator handles stationary tracker ids in smooth mode (#2217)
* test: add regression test for TraceAnnotator smooth on stationary tracker
* fix: TraceAnnotator handles stationary tracker ids in smooth mode
* test: strengthen moving-tracker smooth assertion
* fix: guard splprep against collinear input; use unique_xy in fallback
* test: add boundary and regression tests for smooth mode
* docs: document smooth fallback behavior in TraceAnnotator
* test: add shape preservation assertions in annotate tests

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-18 00:50:15 +02:00
Junghwan 06beb6ff2f
fix(sinks): slice list and tuple custom_data values per row (#2216)
* test: add regression tests for list/tuple custom_data slicing
* fix: slice list and tuple custom_data values per row
* docs: document custom_data slicing contract in append() docstrings
* docs: add docstring to _slice_value in CSVSink and JSONSink
* docs: add docstring to parse_detection_data in CSVSink and JSONSink
* test: add test for detections.data with plain Python list values
* test: add _slice_value edge-case unit tests
* docs: add per-row slicing note to CSVSink and JSONSink class docstrings

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-18 00:24:36 +02:00
Lee Clement 62efdee025
feat: Detections.from_inference supports compressed RLE masks (#2178)
* Detections.from_inference works on RLE-encoded masks
* Apply suggestions from code review
* fix: harden RLE handling in from_inference and decoder
* lint: fix cv2.fillPoly color type in polygon_to_mask
* fix: resize RLE mask to image dims when size mismatches
* fix: pass RLE counts directly in coco_annotations_to_masks
* test: document mixed RLE + box-only batch misalignment
* test: add compressed RLE iscrowd case to coco_annotations_to_detections
* fix: cast polygon mask to bool in process_roboflow_result
* fix: log warning when RLE decode fails in process_roboflow_result
* fix: replace assert with ValueError in rle_to_mask
* test: add bytes invalid UTF-8 case to rle_to_mask tests
* docs: note rle_to_mask dtype change from uint8 to bool in changelog
* refactor: tighten rle_to_mask NDArray input type to np.integer[Any]
* refactor: drop mask_to_rle overloads; cast at call site
* docs: clarify COCO column-major RLE order in rle_to_mask/mask_to_rle
* refactor: update @deprecated annotations and docstrings for mask_to_rle/rle_to_mask; add pydeprecate dependency
* refactor: replace mask_to_rle body with `void` function to suppress unused argument warnings

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-04-15 22:35:47 +02:00
Md Faruk Alam e514142b3d
fix: slice numpy array values in `custom_data` per row in CSVSink (#2199)
* fix: slice numpy array values in custom_data per row in CSVSink and JSONSink
* fix: restore non-ndarray custom_data passthrough in CSVSink
* test: add JSONSink test for numpy array custom_data slicing
* test: add mixed-type custom_data test (ndarray + scalar together)
* refactor: extract _slice_value helper; drop redundant ndarray test

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-14 00:51:52 +02:00
abritton2002 51dd062407
fix: VideoInfo.fps returns float instead of truncated int (#2210)
* VideoInfo.fps returns float instead of int

Truncating the raw CAP_PROP_FPS value with int() causes timing drift for
non-integer frame rates (23.976, 29.97, 59.94). Over a long video this
accumulates into noticeable sync errors — e.g. 23 vs 23.976 drifts ~1s
per minute of footage.

Changes:
- VideoInfo.fps type annotation: int -> float
- from_video_path: int(video.get(CAP_PROP_FPS)) -> float(...)
- ByteTrack.frame_rate type annotation: int -> float (already converts
  to int internally via max_time_lost = int(frame_rate / 30.0 * buffer))
- Tests: assert fps is float, add float_fps_video_path fixture at 23.976

* fix: update examples to cast float fps to int where required
* fix: wrap long docstring line in FPSBasedTimer (ruff E501)
* test: remove unused float_fps_video_path fixture

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-13 20:05:19 +02:00
abritton2002 e19f3120ca
fix: is_empty() returns False for empty tracker arrays (#2209)
* fix: is_empty() returns False for empty tracker arrays (closes #2195)
* fix: use tuple in pytest.mark.parametrize (ruff PT006)
* test: add mask regression case and improve test_is_empty quality
* docs: update is_empty() docstring with pycon examples for clarity and consistency

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-04-13 17:10:59 +02:00
Jirka Borovec 9b7099d3fc
feat: add CompactMask for memory-efficient crop-RLE mask storage (#2159)
Dense (N, H, W) bool masks cause OOM for aerial imagery (1000 objects x
4K image ~ 8.3 GB). CompactMask encodes each mask as a run-length
sequence of its bounding-box crop, reducing typical usage to ~2 MB.

* fix: correct bounding box coordinates in CompactMask doctests
* feat: implement memory-efficient IoU and NMS with CompactMask integration
* test: add extensive tests for CompactMask IoU, NMS, and InferenceSlicer integration
* feat(examples): add CompactMask demo and benchmark
* feat(examples): expand CompactMask benchmark with new stages and metrics
* feat(tests): add detailed CompactMask tests for NMM, centroids, holes, and segments
* feat(compact_mask): add repack(), fix merge perf, and add parity tests
* fix(masks): handle empty crops by defaulting centroid to (0, 0)
* feat(compact_mask): add `bbox_xyxy` property and improve type annotations
* feat(compact_mask): enhance `with_offset` for clipping and add tests
* docs(compact_mask): unwrap prose and add per-operation speedup analysis
* perf(compact_mask): fast path in with_offset avoids decode/re-encode
* fix(benchmark): count NMS mismatches and explain exact-vs-resize difference
* test(compact_mask): add 121 parametrised random-scenario parity tests
* refactor: rename single-char variables to descriptive names
* fix(nms): remove resize-to-640 approximation from mask_non_max_suppression
* docs(compact_mask): update README with fresh benchmark results
* refactor(benchmark): improve summary table logic, add CSV export
* docs(compact_mask): update README with revised benchmark speedups and cleanup

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-13 11:10:12 +02:00
Ishaan 48035c14e2
fixed precision converting annotations with `"force_mask=True"` (#1746)
* changing polygon format conversion
* reformating polygon type conversion
* handling mask dimensions
* fix: resolve unresolved PR #1746 review comments
* refactor(tests): restructure YOLO polygon mask precision tests with fixtures

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Codex <codex@openai.com>
2026-03-31 11:51:30 +02:00
Copilot ddb3515b56 Fix extreme memory usage when loading OBB datasets (#2187)
* fix: prevent mask generation for OBB annotations to avoid extreme memory usage
* docs: clarify force_masks is ignored when is_obb=True
* test: pin force_masks=True is ignored for OBB and segmentation mask regression

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-31 10:24:22 +02:00
Copilot 85ba8be9dd
Fix KeyPoints 2D boolean mask indexing (uniform-count selection) (#2188)
* Fix KeyPoints 2D boolean mask filtering (keypoints[keypoints.confidence > 0.5])
* Fix ruff E501 and mypy type annotation in KeyPoints 2D mask branch
* Add match= to pytest.raises to fix ruff PT011
* Add shape validation for 2D boolean mask in KeyPoints.__getitem__
* Add edge-case tests for KeyPoints 2D boolean mask filtering
* refactor: extract 2D bool mask handling into _get_by_2d_bool_mask private method
* Document 2D mask uniform-count requirement; add canonical single-object test

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-31 01:48:57 +02:00
Clemens 129118817a
make pixel and kernel size dynamic (#709)
* make pixel and kernel size dynamic
* fix: zero-area guard and is-not-None check in Blur/PixelateAnnotator

- Skip loop iteration when clip_boxes produces x2<=x1 or y2<=y1 (zero-area ROI) to prevent cv2.error crash in both annotators
- Replace falsy `or` pattern with explicit `is not None` so kernel_size=0 / pixel_size=0 are not silently treated as dynamic
- Replace hardcoded `cv2.mean(roi)[:3]` with ndim-aware fill: scalar for grayscale, channel-matched tuple for colour images; avoids shape mismatch broadcast error on single-channel frames
- test_annotate_bbox_smaller_than_pixel_size_does_not_raise: guards against the OpenCV resize crash from issue #703 when bbox < pixel_size
- test_annotate_grayscale_image_does_not_raise: normal pixelation path on 2-D grayscale frame
- test_annotate_grayscale_image_small_roi_does_not_raise: avg-fill fallback on 2-D grayscale frame
- Add ValueError guard in BlurAnnotator.__init__ and PixelateAnnotator.__init__ for explicit sizes < 1; previously passed straight to cv2 causing ZeroDivisionError or OpenCV assertion failures
- Add parametrized tests for invalid sizes (0, -1, -10) and zero-area bbox skipping for both annotators

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-03-30 22:17:53 +02:00
Vijay Vignesh 9ed1f07ca0
Add unittests for `supervision.key_points.core` (#2190)
* adding unit testcases for keypoints from_inference(), from_mediapipe() and from_yolo_nas() functions
* modifying test_from_mediapipe_input()
* Apply suggestions from code review

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-30 20:36:31 +02:00
Copilot 38be1be4b2
Fix lossy COCO round-trip: preserve `area` and `iscrowd` in `as_coco` (#2185)
* fix: preserve area and iscrowd from detection data in COCO export
* fix: use np.asarray().item() to satisfy mypy in iscrowd/area extraction
* test: shorten test name to fix ruff E501 line-length violation
* test: verify data["area"] overrides bbox area when mask is present
* test: stricter iscrowd type check (bool subclass fix)
* test: stricter iscrowd type check in preserves_iscrowd_from_data
* test: stricter iscrowd type check in iscrowd_is_int_when_mask_provided
* fix: prefer data["iscrowd"] over geometry when mask is present

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-03-30 20:17:42 +02:00
Copilot e6fab4b7fa
Add out-of-bounds detection warning to InferenceSlicer (#2186)
When a user's callback accidentally runs inference on the full image instead
of the provided slice, detections get incorrect offsets applied, causing a
repeating grid pattern. Add a validation check in _run_callback that emits a
SupervisionWarnings warning when any detection coordinate exceeds the slice
dimensions or is negative. An instance flag prevents repeated warnings across
many slices.

- Wrap _out_of_slice_bounds_warned check-and-set in threading.Lock to prevent duplicate warnings under ThreadPoolExecutor with thread_workers > 1
- Change stacklevel=2 to stacklevel=1 — under executor.submit the stacklevel=2 frame points into concurrent.futures internals, not user code
- Assert exactly 1 warning fires with thread_workers=4 (validates Lock fix)
- Assert no warning for detection touching but not exceeding slice boundary (pins > vs >= semantics)
- Assert second slicer call does not re-warn (documents once-per-instance semantic)
- Extract warning message into `msg` variable to satisfy E501 line-length limit


---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-03-30 19:26:33 +02:00
Mourtaza Ali 8b60ee1a0e feat: add support for hexadecimal RGBA color format (#2004)
This commit adds support for 4-digit and 8-digit hexadecimal color codes
with alpha channel (e.g., #FF00FF80 for 50% transparent magenta).

Changes:
- Extended Color dataclass with optional alpha field (default 255)
- Updated _validate_color_hex to accept lengths 3, 4, 6, 8
- Updated from_hex to parse 4-digit (#RGBA) and 8-digit (#RRGGBBAA) hex codes
- Modified as_hex to return #RRGGBBAA when alpha != 255
- Added as_rgba() and as_bgra() methods
- Added from_rgba_tuple() and from_bgra_tuple() class methods
- Updated __eq__ and __hash__ to include alpha channel
- Added comprehensive unit tests for all RGBA functionality
- Updated docstrings with examples of new alpha channel support

---------

Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-30 15:57:18 +02:00
Adithi Sreenath c010656161
fix: prevent single object from appearing in multiple polygon zones (#1991)
* fix: prevent single object from appearing in multiple polygon zones

when checking if a detection is inside a polygon zone, the previous implementation
would clip the bounding box to fit within each ROI's dimensions before calculating
anchor points. This caused the same detection to produce different anchor points
for different ROIs, allowing it to be counted as present in multiple zones.

* Add regression test for PolygonZone trigger issue #1987 and remove unused `frame_resolution_wh` attribute
* refactor(polygon_zone): vectorize trigger() and strengthen tests

Replace the O(n×m) Python double-loop in PolygonZone.trigger() with
vectorized NumPy. Semantics are identical: compute a (num_anchors,
num_detections) in_bounds mask, use np.clip solely for safe fancy-index
access, then AND with the polygon mask and reduce with np.all(axis=0).
Also removes the now-unused `from dataclasses import replace` import and
a latent np.all(axis=1) call on a 1D array.

Test improvements:
- Group into TestPolygonZoneInit / TestPolygonZoneTrigger classes
- Replace the trivially-passing regression (sum=0 on both old and new
  code) with adjacent zones + straddling detection that gives sum=2 on
  the old clip_boxes implementation and sum=1 on the fix
- Rename tests to describe behaviour, not issue numbers
- Add test_out_of_bounds_anchor_excluded and
  test_anchor_on_polygon_boundary_included edge cases

* test(polygon_zone): verify current_count updates with expected results during trigger

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 21:19:09 +01:00
Omkar Kabde 664bf3cf79
refactor docstrings in `scr/supervision/detection` (#2162)
* refactor docstrings in `scr/supervision/detection`
* Enhance docstrings across multiple modules: clarify attributes/args, improve formatting, and update logic for handling sentinel values in metrics calculation.
* Ensure consistent handling of `class_id` as integer across YOLO and Pascal VOC formats, fix NoneType handling in line zone logic, and add test coverage for multiclass annotator with None `class_id`.
* Enforce `class_id` as integer in YOLO export, update line zone class count docstrings, and add test for non-integer `class_id`.
* Apply suggestions from code review

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-10 18:40:05 +01:00
Omkar Kabde a673640aad
refactor docstrings in `draw`, `classification`, and `key_points` (#2161)
* refactor docstrings in draw, classification, and key_points
* Refactor type annotations, logging, and empty output handling across key modules
* Refactor type annotations in `core.py` to include conditional `TYPE_CHECKING` for `torch` imports
* Apply suggestions from code review

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-03-10 18:07:39 +01:00
Hee Jae Kim 9eba61de10
fix: populate class_name in DetectionDataset annotations (#2156)
DetectionDataset.__init__ now maps class_id to class names using
CLASS_NAME_DATA_FIELD so that LabelAnnotator displays human-readable
labels instead of raw integer IDs.

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
2026-02-25 19:37:59 +01:00
Copilot c2dedba3db
feat: replace print statements with structured logging (#2154)
* feat: implement logging system to replace print statements
* refactor: rename get_logger to _get_logger to mark as internal
* test: add logger tests, fix corrupted-file warning test, add docstring example

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Borda <6035284+Borda@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-02-20 13:14:53 +01:00
Youho99 6ca9555efd
Fix `detections_to_coco_annotations` function for empty polygons. (#1086)
* Fix `detections_to_coco_annotations` function for empty polygons.
* Add `segmentation` empty field for bboxes coco format
* update coco.py
Always include box, area, and segmentation in the result COCO JSON.
* `as_coco()` : Add COCO format disjoint masks support
* Fix `force_masks` parameter on `from_coco()` function
Allows reconstruction of disjointed masks
* Ensures the mask is binary
* Refactor `coco_annotations_to_masks` to handle disjoint polygon segmentation and missing segmentation gracefully. Add corresponding unit tests.
* Refactor `coco_annotations_to_masks` for improved type annotations and cleaner formatting
* Add warnings for handling empty polygons during COCO segmentation and related unit tests

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: jirka <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-20 12:08:26 +01:00
kymillev ae2c356321
Fix mask_annotate for int dtypes (#1445)
* Fix mask_annotate for int dtypes
* Add depreciation warning
* Add dtype=bool to test masks
* Remove ValueError (testing)
* Ensure boolean masks are consistently used in `Detections` and update validations, tests, and warnings for stricter type handling.
* Apply suggestions from code review

---------

Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-02-20 10:43:56 +01:00