Skip to content

expose raw input, add example for saving raw tof data - #1890

Open
CasualMathEnjoyer wants to merge 5 commits into
developfrom
feature/expose_tof_rawInput
Open

expose raw input, add example for saving raw tof data#1890
CasualMathEnjoyer wants to merge 5 commits into
developfrom
feature/expose_tof_rawInput

Conversation

@CasualMathEnjoyer

@CasualMathEnjoyer CasualMathEnjoyer commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Purpose

Specification

None / not applicable

Dependencies & Potential Impact

None / not applicable

Deployment Plan

None / not applicable

Testing & Validation

None / not applicable

AI Usage

Assisted-by: AGENT_NAME:MODEL_VERSION [TOOL1] [TOOL2]

Submitted code was reviewed by a human: YES/NO

The author is taking the responsibility for the contribution: YES/NO

Summary by CodeRabbit

  • New Features
    • Added a new read-only Python property, rawInput, to access raw ToF input frames.
    • Extended Python ToFConfig with pipeType plus additional RVC4 post-processing tuning controls (bilateral, temporal noise reduction, flying pixel filter).
    • Added/updated Python examples to capture raw ToF frames with synchronized depth, replay saved raw frames, and live-tune exposed RVC4 settings (with optional verification).
  • Documentation
    • Clarified how to wire rawInput when using ToFBase directly.
  • Bug Fixes
    • Made depth color visualization use a consistent fixed range for stable color mapping across frames.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds RVC4 ToF post-processing configuration fields and Python bindings, exposes ToFBase.rawInput, and adds examples for live tuning, stable depth visualization, and raw-frame capture, verification, replay, and plotting.

Changes

RVC4 ToF controls and raw input

Layer / File(s) Summary
ToF configuration contract and bindings
include/depthai/pipeline/datatype/ToFConfig.hpp, bindings/python/src/pipeline/datatype/ToFConfigBindings.cpp
Adds pipe selection and optional bilateral, temporal, and flying-pixel controls, serializes them, and exposes them to Python.
Raw input contract and Python binding
include/depthai/pipeline/node/ToF.hpp, bindings/python/src/pipeline/node/ToFBindings.cpp
Documents direct RVC4 rawInput usage and exposes ToFBase.rawInput as a read-only Python property.
RVC4 tuning example
examples/python/ToF/tof_rvc4_exposed_settings.py
Adds configuration mapping, an OpenCV tuning interface, runtime updates, stream display, and headless frame validation.
Raw capture and replay example
examples/python/ToF/tof_raw_rvc4.py
Captures raw and depth frames, validates saved depth data, replays raw frames through host-fed ToFBase, and plots replayed depth output.
Stable depth visualization
examples/python/ToF/tof_align.py, examples/python/ToF/tof_all_queues.py, examples/python/ToF/tof_minimal.py
Uses fixed logarithmic depth bounds for consistent color mapping across frames.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PythonUI
  participant ToFConfig
  participant ToFBase
  participant HostStorage
  PythonUI->>ToFConfig: build and update tuning configuration
  ToFConfig->>ToFBase: apply initial and runtime settings
  ToFBase->>HostStorage: save raw and depth frames
  HostStorage->>ToFBase: replay raw frames through rawInput
  ToFBase->>PythonUI: return replayed depth frames
Loading

Possibly related PRs

Suggested reviewers: jakubfara

Poem

I’m a bunny tuning depth tonight,
Sliders make the ToF pixels bright.
Raw frames hop, then replay true,
Python plots their dancing view.
Filters bloom—what a delight! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main changes: exposing raw input and adding an example for saving raw ToF data.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/expose_tof_rawInput

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/python/ToF/tof_raw_rvc4.py`:
- Around line 25-27: Update the usage examples in the module docstring to
reference the actual script filename, tof_raw_rvc4.py, instead of
tof_raw_depth_test.py while preserving the existing arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: db6e7eb4-dcb6-44a3-9092-c9eb089142b7

📥 Commits

Reviewing files that changed from the base of the PR and between ae9000c and 9d62be7.

📒 Files selected for processing (3)
  • bindings/python/src/pipeline/node/ToFBindings.cpp
  • examples/python/ToF/tof_raw_rvc4.py
  • include/depthai/pipeline/node/ToF.hpp
📜 Review details
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-05-28T13:36:26.383Z
Learnt from: moratom
Repo: luxonis/depthai-core PR: 1812
File: examples/cpp/ImageManip/image_manip_remap.cpp:51-52
Timestamp: 2026-05-28T13:36:26.383Z
Learning: In depthai-core example code, do not set `ImageManip::Backend::GPU` unconditionally. The GPU backend is only available on RVC4 (not RVC2). Prefer leaving the backend as the default, or comment out the GPU backend selection and add a clear note explaining it is RVC4-only support (so the example won’t fail or mislead on RVC2).

Applied to files:

  • examples/python/ToF/tof_raw_rvc4.py
🪛 Ruff (0.15.20)
examples/python/ToF/tof_raw_rvc4.py

[error] 95-95: f-string without any placeholders

Remove extraneous f prefix

(F541)


[warning] 156-156: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


[warning] 167-170: Use contextlib.suppress(Exception) instead of try-except-pass

Replace try-except-pass with with contextlib.suppress(Exception): ...

(SIM105)


[error] 169-170: try-except-pass detected, consider logging the exception

(S110)


[warning] 169-169: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (6)
include/depthai/pipeline/node/ToF.hpp (1)

56-61: LGTM!

Also applies to: 77-78

bindings/python/src/pipeline/node/ToFBindings.cpp (1)

42-42: LGTM!

examples/python/ToF/tof_raw_rvc4.py (4)

58-74: LGTM!


77-87: LGTM!


90-123: LGTM!

Also applies to: 126-148, 151-170, 173-244


139-145: 🩺 Stability & Availability

Check the Python MessageQueue.get() overload first. get(timeout=...) only belongs in the fix if depthai’s Python API supports that keyword and timeout semantics.

Comment thread examples/python/ToF/tof_raw_rvc4.py Outdated

@aljazkonec1 aljazkonec1 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Need to change the test to camelCase instead of snake_case

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CamelCase instead of snake_case

CasualMathEnjoyer and others added 2 commits July 14, 2026 12:34
update old file name in description

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@CasualMathEnjoyer
CasualMathEnjoyer force-pushed the feature/expose_tof_rawInput branch from ca7a134 to 8fdaa1d Compare July 14, 2026 10:37

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/python/ToF/tof_raw_rvc4.py`:
- Line 95: Remove the unnecessary f-string prefix from the failure message in
the depth-file validation path, keeping the printed text unchanged.
- Around line 167-170: Update the exception handling around plt.show() to avoid
a bare Exception that silently suppresses failures: catch only the expected
matplotlib display exception, or log unexpected errors before continuing.
Preserve the intended behavior of ignoring known display-backend failures while
making unrelated failures distinguishable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e8004bce-84e6-4cd8-a728-571673baaeb0

📥 Commits

Reviewing files that changed from the base of the PR and between ca7a134 and 8fdaa1d.

📒 Files selected for processing (3)
  • bindings/python/src/pipeline/node/ToFBindings.cpp
  • examples/python/ToF/tof_raw_rvc4.py
  • include/depthai/pipeline/node/ToF.hpp
📜 Review details
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-05-28T13:36:26.383Z
Learnt from: moratom
Repo: luxonis/depthai-core PR: 1812
File: examples/cpp/ImageManip/image_manip_remap.cpp:51-52
Timestamp: 2026-05-28T13:36:26.383Z
Learning: In depthai-core example code, do not set `ImageManip::Backend::GPU` unconditionally. The GPU backend is only available on RVC4 (not RVC2). Prefer leaving the backend as the default, or comment out the GPU backend selection and add a clear note explaining it is RVC4-only support (so the example won’t fail or mislead on RVC2).

Applied to files:

  • examples/python/ToF/tof_raw_rvc4.py
🪛 Ruff (0.15.21)
examples/python/ToF/tof_raw_rvc4.py

[error] 95-95: f-string without any placeholders

Remove extraneous f prefix

(F541)


[warning] 156-156: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


[warning] 167-170: Use contextlib.suppress(Exception) instead of try-except-pass

Replace try-except-pass with with contextlib.suppress(Exception): ...

(SIM105)


[error] 169-170: try-except-pass detected, consider logging the exception

(S110)


[warning] 169-169: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (4)
include/depthai/pipeline/node/ToF.hpp (1)

56-62: LGTM!

bindings/python/src/pipeline/node/ToFBindings.cpp (1)

40-43: LGTM!

examples/python/ToF/tof_raw_rvc4.py (2)

202-224: 🩺 Stability & Availability

Verify raw/depth pairing survives queue backpressure.

raw_q (fed by cam.raw) and depth_q (fed by tof_base.depth) are two independently-populated queues read in lockstep per loop iteration. The saved raw_<ts>.npz/depth_<ts>.npy pairing (and the whole capture→replay validation premise) is only correct if ToFBase produces exactly one depth frame per raw frame, in order, with neither queue dropping/reordering frames under load. Worth confirming the default createOutputQueue() blocking/size behavior actually guarantees this instead of assuming it.


139-146: 🗄️ Data Integrity & Integration

Confirm setCvFrame/getFrame round-trip fidelity for raw ToF frames.

Replay reconstructs ImgFrames via img.setCvFrame(data, frame_type) from arrays captured with raw_msg.getFrame(). This assumes the two are exact inverses for whatever raw pixel format the ToF sensor emits (e.g. packed RAW10/RAW16); if getFrame() returns something not directly re-ingestible by setCvFrame for this frame type, replay would silently produce depth from malformed input rather than failing loudly.


print(f"\n[Verify] Expected {expected_count} file(s), found {len(depth_files)}")
if len(depth_files) < expected_count:
print(f"[FAIL] Not enough depth files saved.")

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove extraneous f prefix.

f"[FAIL] Not enough depth files saved." has no placeholders.

🔧 Proposed fix
-        print(f"[FAIL] Not enough depth files saved.")
+        print("Not enough depth files saved.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
print(f"[FAIL] Not enough depth files saved.")
print("Not enough depth files saved.")
🧰 Tools
🪛 Ruff (0.15.21)

[error] 95-95: f-string without any placeholders

Remove extraneous f prefix

(F541)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_raw_rvc4.py` at line 95, Remove the unnecessary
f-string prefix from the failure message in the depth-file validation path,
keeping the printed text unchanged.

Source: Linters/SAST tools

Comment on lines +167 to +170
try:
plt.show()
except Exception:
pass

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.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Broad except Exception: pass silently swallows all errors.

Static analysis flags this as blind exception handling with no logging (S110/BLE001), and suggests contextlib.suppress for the pattern (SIM105). At minimum, narrow the exception or log it so real failures (e.g., a broken matplotlib backend vs. an unrelated bug) aren't indistinguishable.

♻️ Proposed refactor
+import contextlib
...
-    try:
-        plt.show()
-    except Exception:
-        pass
+    with contextlib.suppress(Exception):
+        plt.show()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
plt.show()
except Exception:
pass
import contextlib
with contextlib.suppress(Exception):
plt.show()
🧰 Tools
🪛 Ruff (0.15.21)

[warning] 167-170: Use contextlib.suppress(Exception) instead of try-except-pass

Replace try-except-pass with with contextlib.suppress(Exception): ...

(SIM105)


[error] 169-170: try-except-pass detected, consider logging the exception

(S110)


[warning] 169-169: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_raw_rvc4.py` around lines 167 - 170, Update the
exception handling around plt.show() to avoid a bare Exception that silently
suppresses failures: catch only the expected matplotlib display exception, or
log unexpected errors before continuing. Preserve the intended behavior of
ignoring known display-backend failures while making unrelated failures
distinguishable.

Source: Linters/SAST tools

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/python/ToF/tof_rvc4_exposed_settings.py`:
- Line 132: Apply the requested Ruff style fixes in the affected code: remove
redundant int casts around round results, replace unused loop variables such as
label with underscore, convert the indicated .format() calls to f-strings, use
dict.fromkeys instead of the equivalent dict comprehension, and remove unused
lambda arguments. Limit changes to these reported lint issues and preserve
behavior.
- Around line 332-446: Reduce main() complexity by extracting the --test
verification block into a run_test_mode(...) helper and the live
tuning/streaming loop into a run_live_mode(...) helper. Pass the existing
queues, configuration, and runtime state these helpers need, preserve their
current return values and behavior, and leave main() responsible only for setup,
platform validation, startup, and dispatching to the appropriate helper.
- Around line 371-393: Update the --test verification loop in the outputQueues
iteration to use a bounded timeout when retrieving each frame instead of
blocking indefinitely. Catch the timeout or missing-frame condition, print a
clear stream-specific diagnostic, and return a failure status while preserving
the existing per-stream counting and final result behavior for successful
retrievals.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: d1753ca3-48c2-4183-9d9b-85b0274c8b98

📥 Commits

Reviewing files that changed from the base of the PR and between 8fdaa1d and f6ce1d3.

📒 Files selected for processing (3)
  • bindings/python/src/pipeline/datatype/ToFConfigBindings.cpp
  • examples/python/ToF/tof_rvc4_exposed_settings.py
  • include/depthai/pipeline/datatype/ToFConfig.hpp
📜 Review details
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-05-28T13:36:26.383Z
Learnt from: moratom
Repo: luxonis/depthai-core PR: 1812
File: examples/cpp/ImageManip/image_manip_remap.cpp:51-52
Timestamp: 2026-05-28T13:36:26.383Z
Learning: In depthai-core example code, do not set `ImageManip::Backend::GPU` unconditionally. The GPU backend is only available on RVC4 (not RVC2). Prefer leaving the backend as the default, or comment out the GPU backend selection and add a clear note explaining it is RVC4-only support (so the example won’t fail or mislead on RVC2).

Applied to files:

  • examples/python/ToF/tof_rvc4_exposed_settings.py
🪛 Ruff (0.15.21)
examples/python/ToF/tof_rvc4_exposed_settings.py

[warning] 132-132: Value being cast to int is already an integer

Remove unnecessary int call

(RUF046)


[warning] 142-142: Loop control variable label not used within loop body

Rename unused label to _label

(B007)


[warning] 148-148: Value being cast to int is already an integer

Remove unnecessary int call

(RUF046)


[warning] 201-201: Loop control variable label not used within loop body

Rename unused label to _label

(B007)


[warning] 209-209: Value being cast to int is already an integer

Remove unnecessary int call

(RUF046)


[warning] 254-254: Value being cast to int is already an integer

Remove unnecessary int call

(RUF046)


[warning] 318-328: Use f-string instead of format call

Convert to f-string

(UP032)


[warning] 332-332: Too many branches (16 > 12)

(PLR0912)


[warning] 332-332: Too many statements (69 > 50)

(PLR0915)


[warning] 373-373: Unnecessary dict comprehension for iterable; use dict.fromkeys instead

Replace with dict.fromkeys(iterable))

(C420)


[warning] 410-410: Unused lambda argument: e

(ARG005)


[warning] 410-410: Unused lambda argument: f

(ARG005)

🔇 Additional comments (5)
include/depthai/pipeline/datatype/ToFConfig.hpp (1)

20-28: LGTM!

Also applies to: 84-139, 175-185

bindings/python/src/pipeline/datatype/ToFConfigBindings.cpp (1)

21-21: LGTM!

Also applies to: 42-46, 67-78

examples/python/ToF/tof_rvc4_exposed_settings.py (3)

73-73: 🎯 Functional Correctness | ⚡ Quick win

tnrStdFactor lacks the same zero-guard as bilateralStdFactor.

Both sliders share the same "x20, 0.05 steps" scale and comment style, but MIN_SLIDER only clamps bilateralStdFactor to avoid a rejected zero value; tnrStdFactor can still be dragged to 0. If the IPP TNR control also rejects a zero std factor, this would need the same MIN_SLIDER["tnrStdFactor"] = 1 guard.

Also applies to: 77-77, 96-98


1-450: LGTM!


343-346: 🎯 Functional Correctness

dai.ToFConfig.Profile is exposed in Python. The hasattr branch is valid here.

			> Likely an incorrect or invalid review comment.

def _x_to_pos(x: int, maxval: int, minpos: int) -> int:
frac = (x - TRACK_X0) / (TRACK_X1 - TRACK_X0)
frac = min(1.0, max(0.0, frac))
return max(minpos, min(maxval, int(round(frac * maxval))))

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.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Batch of ruff nits (redundant casts, unused loop vars, .format(), lambda args).

Static analysis flags several small style issues: redundant int() around already-int round() results (132, 148, 209, 254), unused loop variable label (142, 201), .format() instead of f-string (318-329), dict comprehension vs dict.fromkeys (373), and unused lambda args (410). None are functional bugs; safe to batch-fix with ruff --fix if desired.

Also applies to: 142-142, 148-148, 201-201, 209-209, 254-254, 318-329, 373-373, 410-410

🧰 Tools
🪛 Ruff (0.15.21)

[warning] 132-132: Value being cast to int is already an integer

Remove unnecessary int call

(RUF046)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_rvc4_exposed_settings.py` at line 132, Apply the
requested Ruff style fixes in the affected code: remove redundant int casts
around round results, replace unused loop variables such as label with
underscore, convert the indicated .format() calls to f-strings, use
dict.fromkeys instead of the equivalent dict comprehension, and remove unused
lambda arguments. Limit changes to these reported lint issues and preserve
behavior.

Source: Linters/SAST tools

Comment on lines +332 to +446
def main() -> int:
args = parse_args()

minDepth, maxDepth = 100, 7000
socket = getattr(dai.CameraBoardSocket, args.socket)
device = dai.Device(dai.DeviceInfo(args.ip)) if args.ip else None

pipeline = dai.Pipeline(device) if device is not None else dai.Pipeline()

tof = pipeline.create(dai.node.ToF)
# The mid-range profile enum moved across depthai versions; support both.
if hasattr(dai.ToFConfig, "Profile"):
tof.build(boardSocket=socket, profile=dai.ToFConfig.Profile.MID_RANGE)
else:
tof.build(boardSocket=socket, presetMode=dai.ImageFiltersPresetMode.TOF_MID_RANGE)

cfg = build_exposed_config()
tof.setInitialConfig(cfg)
print("Applying exposed RVC4 ToF settings via initial config:")
print(describe(cfg))

inputConfigQueue = tof.tofBaseInputConfig.createInputQueue()
outputQueues = {
"depth": tof.depth.createOutputQueue(maxSize=4, blocking=False),
"amplitude": tof.amplitude.createOutputQueue(maxSize=4, blocking=False),
"intensity": tof.intensity.createOutputQueue(maxSize=4, blocking=False),
"confidence": tof.confidence.createOutputQueue(maxSize=4, blocking=False),
}

with pipeline as p:
dev = p.getDefaultDevice()
if dev.getPlatform() != dai.Platform.RVC4:
print(f"ERROR: this example targets RVC4 devices, got {dev.getPlatform()}", file=sys.stderr)
return 2

p.start()
# Also exercise the runtime path: re-send the same config after start.
inputConfigQueue.send(cfg)

if args.test:
# Count frames per stream in which at least one non-zero pixel was produced.
got = {name: 0 for name in outputQueues}
for i in range(args.frames):
line = [f"frame {i:2d}:"]
for name, queue in outputQueues.items():
frame = queue.get().getCvFrame()
nonzero = int(np.count_nonzero(frame))
if nonzero > 0:
got[name] += 1
pct = 100.0 * nonzero / frame.size if frame.size else 0.0
line.append(f"{name}={pct:5.1f}%")
print(" ".join(line))

print()
all_ok = True
for name, count in got.items():
ok = count >= max(1, args.frames // 2)
all_ok = all_ok and ok
print(f" {name:10s}: {count}/{args.frames} frames with data [{'OK' if ok else 'FAIL'}]")
print("\nRESULT: PASS -- exposed settings accepted, all streams produced." if all_ok
else "\nRESULT: FAIL -- one or more streams had too little data.")
return 0 if all_ok else 1

# Live tuning: trackbars live in their own window so their labels are readable
# and the image windows stay undistorted. Moving any slider re-sends an updated
# ToFConfig to the running node via tofBaseInputConfig.
# Live tuning via a self-drawn slider panel (see render_panel/panel_mouse),
# so the labels render on any OpenCV backend. Dragging a slider re-sends an
# updated ToFConfig to the running node via tofBaseInputConfig.
tune_window = "tuning"
cv2.namedWindow(tune_window, cv2.WINDOW_AUTOSIZE)
panel_state = {"pos": initial_positions(cfg), "drag_row": None}
cv2.setMouseCallback(tune_window, panel_mouse, panel_state)
last_sent = None

# Track the cursor over the depth window so we can show the depth value there.
cv2.namedWindow("depth")
mouse = {"x": -1, "y": -1}
cv2.setMouseCallback("depth", lambda e, x, y, f, m: m.update(x=x, y=y), mouse)

latest = {} # name -> most recent raw cv frame

print("Streaming depth, amplitude, intensity, confidence.")
print("In the 'tuning' window: drag sliders and click the ON/OFF buttons to tune live.")
print("Hover over the 'depth' window to read the depth (mm) under the cursor. "
"Press 'q' to quit.")
while p.isRunning():
# Push a new config only when the sliders actually changed.
current = config_from_positions(panel_state["pos"])
key = tuple(getattr(current, attr) for _, attr, _, _ in TUNE_PARAMS)
if key != last_sent:
inputConfigQueue.send(current)
last_sent = key
print("Applied:", " ".join(f"{a}={getattr(current, a)}" for _, a, _, _ in TUNE_PARAMS))
cv2.imshow(tune_window, render_panel(panel_state["pos"]))

for name, queue in outputQueues.items():
frame = queue.tryGet()
if frame is not None:
latest[name] = frame.getCvFrame()

# Redraw depth every iteration (even without a new frame) so the hover
# readout follows the cursor smoothly.
if "depth" in latest:
depth_display = colorizeDepth(latest["depth"], minDepth, maxDepth)
draw_depth_hover(depth_display, latest["depth"], mouse)
cv2.imshow("depth", depth_display)
for name in ("amplitude", "intensity", "confidence"):
if name in latest:
cv2.imshow(name, normalizeFrame(latest[name]))

if cv2.waitKey(1) == ord("q"):
break

return 0

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.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

main() complexity flagged by static analysis.

Ruff reports 16 branches / 69 statements (PLR0912/PLR0915), exceeding recommended limits. Splitting the --test verification loop and the live-tuning loop into two helper functions (e.g. run_test_mode(...), run_live_mode(...)) called from main() would meaningfully improve readability for an example script meant to be read/copied by users.

🧰 Tools
🪛 Ruff (0.15.21)

[warning] 332-332: Too many branches (16 > 12)

(PLR0912)


[warning] 332-332: Too many statements (69 > 50)

(PLR0915)


[warning] 373-373: Unnecessary dict comprehension for iterable; use dict.fromkeys instead

Replace with dict.fromkeys(iterable))

(C420)


[warning] 410-410: Unused lambda argument: e

(ARG005)


[warning] 410-410: Unused lambda argument: f

(ARG005)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_rvc4_exposed_settings.py` around lines 332 - 446,
Reduce main() complexity by extracting the --test verification block into a
run_test_mode(...) helper and the live tuning/streaming loop into a
run_live_mode(...) helper. Pass the existing queues, configuration, and runtime
state these helpers need, preserve their current return values and behavior, and
leave main() responsible only for setup, platform validation, startup, and
dispatching to the appropriate helper.

Source: Linters/SAST tools

Comment on lines +371 to +393
if args.test:
# Count frames per stream in which at least one non-zero pixel was produced.
got = {name: 0 for name in outputQueues}
for i in range(args.frames):
line = [f"frame {i:2d}:"]
for name, queue in outputQueues.items():
frame = queue.get().getCvFrame()
nonzero = int(np.count_nonzero(frame))
if nonzero > 0:
got[name] += 1
pct = 100.0 * nonzero / frame.size if frame.size else 0.0
line.append(f"{name}={pct:5.1f}%")
print(" ".join(line))

print()
all_ok = True
for name, count in got.items():
ok = count >= max(1, args.frames // 2)
all_ok = all_ok and ok
print(f" {name:10s}: {count}/{args.frames} frames with data [{'OK' if ok else 'FAIL'}]")
print("\nRESULT: PASS -- exposed settings accepted, all streams produced." if all_ok
else "\nRESULT: FAIL -- one or more streams had too little data.")
return 0 if all_ok else 1

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Bound the per-stream wait in --test mode
queue.get() blocks forever here, so if any stream never produces a frame the verification loop hangs instead of failing with a diagnostic. Add a timeout and return a clear error when a stream is silent.

🧰 Tools
🪛 Ruff (0.15.21)

[warning] 373-373: Unnecessary dict comprehension for iterable; use dict.fromkeys instead

Replace with dict.fromkeys(iterable))

(C420)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_rvc4_exposed_settings.py` around lines 371 - 393,
Update the --test verification loop in the outputQueues iteration to use a
bounded timeout when retrieving each frame instead of blocking indefinitely.
Catch the timeout or missing-frame condition, print a clear stream-specific
diagnostic, and return a failure status while preserving the existing per-stream
counting and final result behavior for successful retrievals.

CasualMathEnjoyer and others added 2 commits July 15, 2026 16:53
Set slider ranges, min/max and initial defaults from the VD55H1 IPP
filter reference (TOF_IPP_FILTERS.md):

- bilateralKernelSize: snap to odd values in {3..15}
- flyingPixelDepthThreshold: mm (0..300, default 100), was mislabeled meters
- flyingPixelMinDepthOccurrence: max 16 -> 25, default 23
- tnrMaxGain: clamp min to 1, default 16
- bilateralStdFactor: 0.1..8.0, default 4.0; tnrStdFactor default 1.4

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
examples/python/ToF/tof_rvc4_exposed_settings.py (1)

169-175: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor cleanups: unused variable and redundant cast.

The loop variable label is unused, and the int() cast around round() is redundant since round() natively returns an integer in Python 3.

♻️ Proposed refactor
-    for label, attr, maxval, scale in TUNE_PARAMS:
+    for _label, attr, maxval, scale in TUNE_PARAMS:
         init = getattr(cfg, attr)
         if attr in ENUM_ATTRS:
             choices = ENUM_ATTRS[attr]
             pos = choices.index(init.name) if init is not None else 0
         else:
-            pos = int(round((bool(init) if attr in BOOL_ATTRS else (init or 0)) / scale))
+            pos = round((bool(init) if attr in BOOL_ATTRS else (init or 0)) / scale)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/ToF/tof_rvc4_exposed_settings.py` around lines 169 - 175, In
the loop over TUNE_PARAMS, replace the unused label binding with an underscore
and remove the redundant int() wrapper around round() in the non-enum position
calculation. Preserve the existing initialization, enum handling, boolean
conversion, scaling, and rounding behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@examples/python/ToF/tof_rvc4_exposed_settings.py`:
- Around line 169-175: In the loop over TUNE_PARAMS, replace the unused label
binding with an underscore and remove the redundant int() wrapper around round()
in the non-enum position calculation. Preserve the existing initialization, enum
handling, boolean conversion, scaling, and rounding behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: daff529a-94f7-482e-b9a7-1d15b78ca771

📥 Commits

Reviewing files that changed from the base of the PR and between f6ce1d3 and b93881d.

📒 Files selected for processing (4)
  • examples/python/ToF/tof_align.py
  • examples/python/ToF/tof_all_queues.py
  • examples/python/ToF/tof_minimal.py
  • examples/python/ToF/tof_rvc4_exposed_settings.py
📜 Review details
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-05-28T13:36:26.383Z
Learnt from: moratom
Repo: luxonis/depthai-core PR: 1812
File: examples/cpp/ImageManip/image_manip_remap.cpp:51-52
Timestamp: 2026-05-28T13:36:26.383Z
Learning: In depthai-core example code, do not set `ImageManip::Backend::GPU` unconditionally. The GPU backend is only available on RVC4 (not RVC2). Prefer leaving the backend as the default, or comment out the GPU backend selection and add a clear note explaining it is RVC4-only support (so the example won’t fail or mislead on RVC2).

Applied to files:

  • examples/python/ToF/tof_minimal.py
  • examples/python/ToF/tof_align.py
  • examples/python/ToF/tof_all_queues.py
  • examples/python/ToF/tof_rvc4_exposed_settings.py
🔇 Additional comments (3)
examples/python/ToF/tof_align.py (1)

30-35: LGTM!

examples/python/ToF/tof_all_queues.py (1)

20-25: LGTM!

examples/python/ToF/tof_minimal.py (1)

20-25: LGTM!

Comment on lines +22 to +25
# Map from the FIXED depth range (not the per-frame min/max) so a given depth
# always maps to the same color -- otherwise the mapping shifts every frame and
# the image flickers.
colored = np.interp(logDepth, (logMin, logMax), (0, 255))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like an unnecessarry comment?

Comment on lines +22 to +24
# Map from the FIXED depth range (not the per-frame min/max) so a given depth
# always maps to the same color -- otherwise the mapping shifts every frame and
# the image flickers.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, unnecessarry comment?

Comment on lines +32 to +34
# Map from the FIXED depth range (not the per-frame min/max) so a given depth
# always maps to the same color -- otherwise the mapping shifts every frame and
# the image flickers.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unecessarry no?

Comment on lines +84 to +138
/*
* RVC4 / VD55H1 depth post-processing tuning.
*
* The fields below map directly onto STMicroelectronics VD55H1 IPP controls
* and are only honored on RVC4 devices. Each is optional: leaving a field
* unset (std::nullopt) keeps the IPP/wrapper default for that control, so an
* unmodified ToFConfig reproduces the previous hardcoded behavior.
*/

/*
* Bilateral spatial filter. false => filter bypassed.
*/
std::optional<bool> enableBilateralFilter;
/*
* Bilateral filter standard-deviation factor (strength).
*/
std::optional<float> bilateralStdFactor;
/*
* Bilateral filter kernel size.
*/
std::optional<std::uint32_t> bilateralKernelSize;

/*
* Temporal noise reduction (TNR). false => filter bypassed.
*/
std::optional<bool> enableTemporalNoiseReduction;
/*
* TNR maximum gain.
*/
std::optional<std::uint32_t> tnrMaxGain;
/*
* TNR standard-deviation factor (strength).
*/
std::optional<float> tnrStdFactor;

/*
* Flying-pixel filter. false => filter bypassed.
*/
std::optional<bool> enableFlyingPixelFilter;
/*
* Flying-pixel filter depth threshold.
*/
std::optional<float> flyingPixelDepthThreshold;
/*
* Flying-pixel filter minimum depth occurrence: minimum number of neighbouring
* pixels at a similar depth required for a pixel to be kept (lower => more
* aggressive removal). Maps to the IPP "min depth occurence" parameter.
*/
std::optional<float> flyingPixelMinDepthOccurrence;

/*
* ToF illumination pipe type. AUTO (default) selects flood/dot from the sensor's
* detected illumination; FLOOD/DOT force it. Unset keeps the IPP default (AUTO).
*/
std::optional<PipeType> pipeType;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each RVC4 only field should specify its RVC4 only so that it renders properly on hover and in docs

@aljazkonec1

Copy link
Copy Markdown
Collaborator

@JakubFara did we want to close this as it is not relevant?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants