expose raw input, add example for saving raw tof data - #1890
expose raw input, add example for saving raw tof data#1890CasualMathEnjoyer wants to merge 5 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds RVC4 ToF post-processing configuration fields and Python bindings, exposes ChangesRVC4 ToF controls and raw input
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
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
bindings/python/src/pipeline/node/ToFBindings.cppexamples/python/ToF/tof_raw_rvc4.pyinclude/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 & AvailabilityCheck the Python
MessageQueue.get()overload first.get(timeout=...)only belongs in the fix ifdepthai’s Python API supports that keyword and timeout semantics.
aljazkonec1
left a comment
There was a problem hiding this comment.
Thanks. Need to change the test to camelCase instead of snake_case
There was a problem hiding this comment.
CamelCase instead of snake_case
update old file name in description Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
ca7a134 to
8fdaa1d
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
bindings/python/src/pipeline/node/ToFBindings.cppexamples/python/ToF/tof_raw_rvc4.pyinclude/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 & AvailabilityVerify raw/depth pairing survives queue backpressure.
raw_q(fed bycam.raw) anddepth_q(fed bytof_base.depth) are two independently-populated queues read in lockstep per loop iteration. The savedraw_<ts>.npz/depth_<ts>.npypairing (and the whole capture→replay validation premise) is only correct ifToFBaseproduces exactly one depth frame per raw frame, in order, with neither queue dropping/reordering frames under load. Worth confirming the defaultcreateOutputQueue()blocking/size behavior actually guarantees this instead of assuming it.
139-146: 🗄️ Data Integrity & IntegrationConfirm
setCvFrame/getFrameround-trip fidelity for raw ToF frames.Replay reconstructs
ImgFrames viaimg.setCvFrame(data, frame_type)from arrays captured withraw_msg.getFrame(). This assumes the two are exact inverses for whatever raw pixel format the ToF sensor emits (e.g. packed RAW10/RAW16); ifgetFrame()returns something not directly re-ingestible bysetCvFramefor 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.") |
There was a problem hiding this comment.
📐 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.
| 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
| try: | ||
| plt.show() | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
📐 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.
| 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
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
bindings/python/src/pipeline/datatype/ToFConfigBindings.cppexamples/python/ToF/tof_rvc4_exposed_settings.pyinclude/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
tnrStdFactorlacks the same zero-guard asbilateralStdFactor.Both sliders share the same "x20, 0.05 steps" scale and comment style, but
MIN_SLIDERonly clampsbilateralStdFactorto avoid a rejected zero value;tnrStdFactorcan still be dragged to 0. If the IPP TNR control also rejects a zero std factor, this would need the sameMIN_SLIDER["tnrStdFactor"] = 1guard.Also applies to: 77-77, 96-98
1-450: LGTM!
343-346: 🎯 Functional Correctness
dai.ToFConfig.Profileis exposed in Python. Thehasattrbranch 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)))) |
There was a problem hiding this comment.
📐 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
| 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 |
There was a problem hiding this comment.
📐 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
| 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 |
There was a problem hiding this comment.
🩺 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.
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>
There was a problem hiding this comment.
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 valueMinor cleanups: unused variable and redundant cast.
The loop variable
labelis unused, and theint()cast aroundround()is redundant sinceround()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
📒 Files selected for processing (4)
examples/python/ToF/tof_align.pyexamples/python/ToF/tof_all_queues.pyexamples/python/ToF/tof_minimal.pyexamples/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.pyexamples/python/ToF/tof_align.pyexamples/python/ToF/tof_all_queues.pyexamples/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!
| # 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)) |
There was a problem hiding this comment.
Seems like an unnecessarry comment?
| # 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. |
There was a problem hiding this comment.
Again, unnecessarry comment?
| # 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. |
| /* | ||
| * 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; |
There was a problem hiding this comment.
Each RVC4 only field should specify its RVC4 only so that it renders properly on hover and in docs
|
@JakubFara did we want to close this as it is not relevant? |
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
rawInput, to access raw ToF input frames.ToFConfigwithpipeTypeplus additional RVC4 post-processing tuning controls (bilateral, temporal noise reduction, flying pixel filter).rawInputwhen usingToFBasedirectly.