Skip to content

feat(depth): measure distance with sv.DepthCamera and measure_detections - #2693

Merged
Borda merged 32 commits into
developfrom
feat/depth-3-metres
Oct 9, 2026
Merged

Borda merged 32 commits into
developfrom
feat/depth-3-metres

Conversation

@cfviotti

@cfviotti cfviotti commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor
A YOLO26 person detection labelled 3.64 m, measured from the Spring dataset's ground-truth stereo depth

A YOLO26 detection on a frame of the Spring movie. The label is the median distance inside the box, from the dataset's true stereo depth and its camera (focal length 1346.8 px, baseline 6.5 cm).

▶️📓 Notebook Playground Demo (all 4 PRs together)

Description

A depth map is most useful as a distance: how far is that person, that car. With the stereo rig's focal length and baseline, a disparity map gives metres, and measure_detections stores the median distance under each object in detections.data:

camera = sv.DepthCamera(fx_px=1346.8, baseline_m=0.065)
depth_map = sv.DepthMap(disparity, kind="disparity_px", camera=camera)

detections = depth_map.measure_detections(detections)
labels = [f"{name} {metres:.2f} m" for name, metres in zip(detections["class_name"], detections.data["depth_m"])]
annotated_image = sv.LabelAnnotator().annotate(image.copy(), detections, labels)

Part 3 of 4. Needs PR 1 (#2691).

Motivation and Context

Follows #2691. Distance per object is the most asked-for use of depth next to colouring it.

Changes Made

  • sv.DepthCamera(fx_px, baseline_m, doffs_px=0.0) and DepthMap.to_depth(): disparity to metres with fx_px * baseline_m / (disparity + doffs_px).
  • DepthMap.measure_detections(detections): median depth inside each dense mask, CompactMask or box. It is stored under depth_m when the map can give metres, else under disparity_px or relative_inverse (constants in supervision.config). Objects with no depth get NaN.
  • sv.DepthAnnotator(quantity="depth") colours metres instead of disparity (sv.DepthQuantity), with near still warm.
  • resize, crop and value_at:
    • Sizes change without blending holes into depth.
    • resize(method="foreground") keeps thin near objects when shrinking.
    • Disparity and the camera scale with the width.
  • Docs: the how-to's distance section, reference entries and a changelog entry.

Testing

pytest tests/depth --doctest-modules src/supervision/depth   77 passed (38 new)
pytest                                                       4872 passed, 79 skipped
pre-commit run                                               all hooks pass
mkdocs build                                                 no new warnings
  • Added/updated tests, and the full suite passes locally
  • Updated docs (docstrings / mkdocs entry) for new or changed public API
  • Added a changelog entry in docs/changelog.md under Unreleased
  • The image above: yolo26n detection, distance from Spring's ground-truth disparity and its rig (fx 1346.8 px, baseline 6.5 cm)

Additional Notes

  • quantity="depth" on a map without metres raises ValueError naming what is missing (a camera, or a metric map).

cfviotti and others added 4 commits October 7, 2026 13:09
Colour any depth array over an image. Wrap a stereo disparity, metric
depth or relative depth array in sv.DepthMap with the kind of value it
holds, then draw it with sv.DepthAnnotator: near objects come out warm,
far ones cool, and pixels without depth stay unpainted so the image
shows through. It works on NumPy and Pillow images without OpenCV.

- sv.DepthKind names what the values measure. NaN, infinities and
  values at or below 0 (below 0 for relative maps) are no depth, and
  valid_mask marks the rest.
- sv.DepthAnnotator takes a colour table (sv.DepthColormap: Turbo,
  Viridis, Cividis, Inferno, Magma or grayscale), a display_range of
  "auto" (the map's own 2nd to 98th percentile) or a fixed (low, high)
  tuple, and an opacity. A metric map is coloured as inverse depth, so
  near detail gets most of the colours.
- Reference pages, a how-to guide and a changelog entry.

Closes #1313

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Turn a depth map into distances. Give a stereo disparity map the rig's
focal length and baseline with sv.DepthCamera and to_depth returns
metres; measure_detections then stores the median depth under each
object in detections.data["depth_m"], ready for sv.LabelAnnotator
labels such as "car 12.4 m".

- sv.DepthAnnotator(quantity="depth") colours metres instead of
  disparity (sv.DepthQuantity), with the near end still warm.
- resize and crop change a map's size without blending holes into
  depth; resize(method="foreground") keeps thin near objects when
  shrinking, and disparity and the camera scale with the width.
- value_at reads the value under one point, or None where there is no
  depth.
- measure_detections reads dense or compact masks, or boxes without
  masks, and falls back to disparity_px or relative_inverse when the
  map has no metres. The data keys are constants in supervision.config.
- Reference pages, the how-to's labelling section and a changelog
  entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	docs/changelog.md
@Borda
Borda requested a balanced review from Copilot October 7, 2026 17:31
@Borda Borda added the enhancement New feature or request label Oct 7, 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.

🟡 Changes recommended

Converted invalid metric depths can still be painted, and public size validation and documentation require correction.

5 open findings
What changed in this PR

Extends the depth subsystem from #2691 with metric conversion, detection measurements, resizing, cropping, and depth-based annotation.

Changes:

  • Adds stereo camera calibration and metric-depth conversion.
  • Adds depth-map spatial operations and per-detection measurements.
  • Expands annotation modes, tests, documentation, and public exports.

Review scores: Code quality 4/5 · Testing 4/5 · Documentation 3/5

File Description
src/​supervision/​depth/​core.py Implements camera conversion, map operations, and detection measurements.
src/​supervision/​depth/​annotators.py Adds selectable depth/disparity colouring.
src/​supervision/​config.py Defines detection depth-data keys.
src/​supervision/​__init__.py Exports new public depth APIs.
tests/​depth/​test_core.py Tests conversion, spatial operations, and measurements.
tests/​depth/​test_annotators.py Tests metric colouring and invalid quantities.
docs/​how_to/​visualize_depth.md Documents conversion and distance labels.
docs/​depth/​core.md Adds DepthCamera reference documentation.
docs/​depth/​annotators.md Documents metric annotation options.
docs/​changelog.md Records the feature under Unreleased.

🧠 Review effort: Balanced


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

Comment thread src/supervision/depth/annotators.py Resolved
Comment thread src/supervision/depth/core.py Resolved
Comment thread docs/changelog.md Resolved
Comment thread docs/how_to/visualize_depth.md Resolved
Comment thread src/supervision/depth/annotators.py Resolved
cfviotti and others added 7 commits October 7, 2026 14:43
The how-to and the DepthAnnotator example read the image through
supervision._cv2, which the OpenCV migration guide marks private and not
application API. They now open it with Pillow, so the examples stay
OpenCV-free like the feature itself.

A fixed display_range narrower than 1e-20 no longer gets stretched by a
floor on its width; every range is already validated as low < high.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The six colour tables now come from matplotlib, already a dependency,
instead of 140 lines of vendored hex. Colours are byte-identical to the
old tables on matplotlib 3.6.3 and 3.10.3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No other annotator validates opacity, so DepthAnnotator no longer does
either. Also fixes a test docstring that mentioned cameras, which this
PR does not add.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The changelog says the annotator does not require OpenCV rather than
that it runs without it, and uses the ([#N](...)) link style. The
DepthKind docstring says relative_inverse only promises larger is nearer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cfviotti and others added 3 commits October 7, 2026 15:12
# Conflicts:
#	docs/changelog.md
#	docs/depth/annotators.md
#	docs/how_to/visualize_depth.md
#	tests/depth/test_annotators.py
Indexing a CompactMask already returns the dense mask, so
measure_detections needs no separate branch for it. Results are
unchanged; the CompactMask test still passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A metric map without a camera, coloured as disparity (the default), is
ranged in 1 / metres. The guide's labelling example now creates the
detections it measures, and the changelog bullet is shorter with the
([#N](...)) link style.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Base automatically changed from feat/depth-1-show to develop October 8, 2026 22:28
Brings in #2691 as squash-merged with the maintainer's edits. Adaptations:
- display_range stays in the map's own unit for every quantity: with
  quantity="depth" on a disparity map with a camera it is read in pixels and
  converted to metres; a range with low + doffs_px <= 0 is rejected.
- The auto range comes from annotators._percentile_range with the quantity's
  conversion; DepthMap._percentile_range(quantity=...) is gone.
- A flat range paints the far end for quantity="depth" too: the near_is_low
  flip runs after the maintainer's flat-range early return.
- DepthMap.resize("nearest") samples with 1-D takes per axis.
- Docs and docstrings describe display_range in the map's unit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.59184% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93%. Comparing base (9a774bf) to head (b943e1a).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop   #2693    +/-   ##
========================================
  Coverage       93%     93%            
========================================
  Files           82      82            
  Lines        12597   12822   +225     
========================================
+ Hits         11743   11967   +224     
- Misses         854     855     +1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

A typo in DepthAnnotator(quantity=...), a DepthMap camera that is not a
sv.DepthCamera, and a DepthCamera field that is not a number are now pinned
by tests. A non-number DepthCamera field now raises ValueError like every
other bad DepthCamera or DepthMap argument, instead of TypeError, and the
DepthAnnotator docstring lists `quantity` among the arguments it rejects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The relative-depth snippet above reassigns depth_map, so name the map the
distance example measures and note it must have the image's size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cfviotti
cfviotti marked this pull request as ready for review October 9, 2026 05:50
@cfviotti
cfviotti requested a review from SkalskiP as a code owner October 9, 2026 05:50
cfviotti and others added 2 commits October 9, 2026 03:00
…sizes

Colouring metres painted disparities with disparity + doffs_px <= 0 and let
them into the auto range; it now colours only the pixels to_depth keeps.
value_at(resolution_wh=...) now raises ValueError for a zero or negative size,
as resize does, instead of dividing by zero or mirroring the point.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Borda
Borda requested a balanced review from Copilot October 9, 2026 07:09

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

Compact-mask measurement currently materializes a full-frame mask per detection, undermining scalability on high-resolution images.

2 open findings
5 resolved since last review

🧠 Review effort: Balanced

Comment thread src/supervision/depth/core.py Resolved
Comment thread src/supervision/depth/core.py Resolved
cfviotti and others added 3 commits October 9, 2026 13:05
Brings in DepthClipRange (#2692) as merged, with the maintainer's changes.
Adaptations:
- DepthAnnotator takes quantity alongside display_range="auto" | tuple |
  DepthClipRange; a clip range, like a tuple, stays in the map's own unit and
  is converted through the camera when colouring metres.
- _convert_display_range keeps develop's flat-range rules (equal ends and ends
  a reciprocal brings to one float32 value stay flat) and takes the quantity's
  conversion, checking low + doffs_px > 0 for disparity coloured as depth.
- Tests: the camera range test and the infinite-depth rejection test also run
  with a DepthClipRange, flat included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
resize and value_at documented a ValueError for sizes that are not two
positive integers, but (None, 2) raised TypeError and (inf, 2) OverflowError.
Each side must now be a Python or NumPy integer, not a bool, and positive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
measure_detections decoded a full-image mask for every CompactMask
detection. It now reads each crop at its origin through the annotators'
_iter_mask_crops, giving the same medians as dense masks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Borda and others added 7 commits October 9, 2026 18:28
# Conflicts:
#	docs/changelog.md
#	docs/how_to/visualize_depth.md
#	src/supervision/__init__.py
#	src/supervision/depth/annotators.py
#	tests/depth/test_annotators.py
…epth-3-metres

# Conflicts:
#	docs/how_to/visualize_depth.md
#	tests/depth/test_annotators.py
- fix(depth): reject a resolution that is not a pair with ValueError
- feat(depth): measure detections from an image of another size
- docs(depth): show value_at reads a pixel index at its centre
- fix(depth): clip boxes in float before casting to pixels
- fix(depth): reject a camera on a relative map, share kind data keys

[resolve group] PR #2693 — items 6 9 10 11 12

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- test(depth): pin that measure_detections reads inside the mask
- test(depth): parametrize crop and box-measurement edge cases
- test(depth): cover value_at scaling, edges and return type
- test(depth): resize gradients, grids, anisotropy and camera
- test(depth): cover DepthCamera, to_depth edges and DepthScale

[resolve group] PR #2693 — items 13 14 15 16 17

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- perf(depth): measure only the gathered pixels in metres
- perf(depth): check only the read pixel in value_at
- perf(depth): convert the frame once when colouring metres
- perf(depth): skip pooling temporaries when upscaling
- Rename the unreleased DepthQuantity {disparity, depth} to DepthScale {inverse, metric} and the annotator argument quantity to scale, so the enum names the real colour axis and no longer reads like a DepthKind value.
- Keep measure_detections keyed by what the map can give, with no output selector so the new DepthScale enum keeps one meaning; document which data key each map kind writes, that a same-named column is replaced, and that value_at returns the map's own unit.
- Keep display_range in the map's own unit, matching auto and DepthClipRange, and document in the annotator docstring, the clip range docstring and the how-to that a disparity_px range depends on the map's resolution.
- Move the new scale argument of DepthAnnotator to the end, after opacity, so the positional order (colormap, display_range, opacity) matches develop and DepthAnnotator("turbo", (1.0, 10.0)) keeps working.
- Let DepthMap.resize take a new exported DepthResizeMethod enum or its case-insensitive string like the sibling option enums, and import Detections only under TYPE_CHECKING in depth/core.py; the other grouped sub-items are left as the challenge verdict advised.

[resolve group] PR #2693 — items 18 19 20 21 25 26 27 28 29

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- docs(depth): measure_detections shares the input's arrays
- docs(depth): document unit, sentinel and hole conventions

[resolve group] PR #2693 — items 22 23

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Comment thread tests/depth/test_core.py Resolved
@Borda
Borda merged commit f3379af into develop Oct 9, 2026
38 of 40 checks passed
@Borda
Borda deleted the feat/depth-3-metres branch October 9, 2026 17:53
Borda added a commit to Talhax55z/supervision that referenced this pull request Oct 11, 2026
Changes:
- Integrate target updates for DepthMap loaders and measurement, keypoint mAP, compact-mask resizing, and mAP support with their exports, docs, and tests.
- Resolve the changelog collision by preserving the PR mAR entry and target PR roboflow#2694, roboflow#2693, roboflow#2692, and roboflow#2697 entries; update date_modified.

Impact:
- The PR branch includes the fetched develop changes before report-item work, so follow-up validation runs against integrated code.
- The changelog keeps both sets of release notes without dropping target or PR intent.

Verification:
- git diff --check passed after resolution.
- Changelog assertions confirmed the PR and target entries and no conflict markers.
- git diff --name-only --diff-filter=U returned no paths.

Residual limits:
- The full project gate bundle remains before remediation closure.
- No source-specific regression tests have run after integration.

---

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

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants