Skip to content

Use native segmentation parser and mask#304

Merged
klemen1999 merged 15 commits into
mainfrom
feat/86ca5v4v7-86ca5y69r-native-segmentation
Jul 13, 2026
Merged

Use native segmentation parser and mask#304
klemen1999 merged 15 commits into
mainfrom
feat/86ca5v4v7-86ca5y69r-native-segmentation

Conversation

@rolandocortez

@rolandocortez rolandocortez commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Purpose

Use native DepthAI segmentation components in depthai-nodes.

This PR updates the segmentation flow to use native dai.SegmentationMask and native dai.node.SegmentationParser where applicable, while preserving the existing host-side depthai-nodes parser for hostOnly=True.

It also aligns host parser background semantics with the native parser and fixes visualization of binary segmentation masks where class 0 is a valid foreground class and 255 is background.

Additionally, this PR adds the missing setStrides(...) setter to YOLOExtendedParser.

Specification

  • Removed the custom depthai_nodes.message.segmentation.SegmentationMask message.
  • Added explicit copy_message(dai.SegmentationMask) support.
  • Updated ParserGenerator to use native dai.node.SegmentationParser when parser_name == "SegmentationParser" and hostOnly=False.
  • Preserved depthai_nodes.node.parsers.segmentation.SegmentationParser for hostOnly=True.
  • Added RVC2 handling for native segmentation parser by setting it to run on host.
  • Added background_class support to the host SegmentationParser.
  • Updated host parser semantics to match native behavior:
    • background_class=True maps class 0 to 255.
    • Foreground class ids are preserved.
    • Single-channel/unassigned-class behavior still shifts correctly.
    • classes_in_one_layer=True ignores background_class.
  • Updated ApplyColormap handling for native dai.SegmentationMask:
    • 255 background maps to visual background index 0.
    • class 0 maps to a visible foreground index.
  • Added YOLOExtendedParser.setStrides(...) for manually setting YOLO output head strides.

Dependencies & Potential Impact

This depends on a DepthAI version exposing native dai.SegmentationMask and dai.node.SegmentationParser.

Potential impact is limited to segmentation parsing, segmentation mask copying, segmentation visualization paths, and the new YOLO parser strides setter API. The existing host segmentation parser path remains available through hostOnly=True.

Direct Visualizer rendering of binary dai.SegmentationMask values [0, 255] may not visibly color class 0; the ApplyColormap -> ImgFrameOverlay path handles this correctly.

Deployment Plan

No special deployment steps required.

Rollback: revert this PR.

Testing & Validation

  • Focused unit tests passed:
    • tests/unittests/test_messages/test_copy_message.py
    • tests/unittests/test_nodes/test_host_nodes/test_apply_colormap_node.py
  • Validated host SegmentationParser.run() directly with synthetic NN output.
  • Confirmed host background semantics match native parser behavior:
    • class 0 -> 255 when background_class=True
    • foreground class ids are preserved
    • single-channel/unassigned-class path still shifts correctly
    • classes_in_one_layer=True ignores background_class
  • Validated with the segmentation MRE on OAK-1 / RVC2:
    • DeepLab 512 host output no longer has foreground off-by-one compared with native parser.
    • DeepLab person host/native outputs produce valid [0, 255] masks.
    • ApplyColormap -> ImgFrameOverlay correctly visualizes binary masks where foreground class id is 0.
  • Validated YOLOExtendedParser.setStrides(...) locally:
    • accepts list and tuple stride values
    • rejects invalid, empty, non-integer, zero, and negative stride values
  • python -m compileall passed for touched parser files.

Note: For luxonis/mediapipe-selfie-segmentation:256x144, a dual-parser MRE feeding the same NeuralNetwork output to both parsers showed native dai.node.SegmentationParser emitting only [0], while the host depthai-nodes parser emitted [0, 255] for the same sequence numbers and mask shape. Since both parsers consumed the same NN output, this appears isolated to the native parser/model metadata path rather than the host parser changes in this PR.

AI Usage

Assisted-by: ChatGPT

Submitted code was reviewed by a human: YES

The author is taking the responsibility for the contribution: YES

Summary by CodeRabbit

  • New Features
    • Added native DepthAI dai.SegmentationMask support across parsing/remapping and ApplyColormap processing.
    • Added background_class option to segmentation outputs.
    • Added setStrides support for extended YOLO parsing.
    • Updated message documentation to introduce SnapData (replacing the previous segmentation-mask documentation).
  • Bug Fixes
    • Standardized segmentation masks to uint8, with consistent handling for empty and unassigned pixels.
  • Documentation
    • Updated parser/node docs and type references to dai.SegmentationMask.
  • Tests
    • Updated unit, stability, and relevant node tests to validate the native mask API (including mask copying behavior).
  • Chores
    • Bumped DepthAI version to 3.8.0 in workflows and dependency constraints.

@rolandocortez
rolandocortez requested a review from klemen1999 July 3, 2026 09:02
@github-actions github-actions Bot added the enhancement New feature or request label Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@rolandocortez, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 32 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0d1bce9b-6d17-4c69-8163-0dcc9f71cbfd

📥 Commits

Reviewing files that changed from the base of the PR and between 23f9737 and d89ad06.

📒 Files selected for processing (1)
  • .github/workflows/e2e_tests.yaml
📝 Walkthrough

Walkthrough

This PR replaces the local segmentation-mask path with dai.SegmentationMask, updates segmentation parsing and remapping to use uint8 masks with 255 sentinels, bumps DepthAI versions to 3.8.0, adds YOLOExtendedParser.setStrides, and updates message documentation to SnapData.

Changes

Native SegmentationMask migration

Layer / File(s) Summary
Creator and export changes for native SegmentationMask
depthai_nodes/message/creators/segmentation.py, depthai_nodes/message/__init__.py, tests/unittests/test_creators/test_segmentation.py, tests/utils/messages/creators/arrays.py
Segmentation creation, exports, and tests now use dai.SegmentationMask with uint8 masks and setCvMask.
copy_message support for native SegmentationMask
depthai_nodes/message/utils/copy_message.py, tests/unittests/test_messages/test_copy_message.py
Native segmentation masks, CV data, labels, and metadata are copied with dedicated test coverage.
Segmentation parser and pipeline wiring
depthai_nodes/node/parser_generator.py, depthai_nodes/node/parsers/segmentation.py, depthai_nodes/node/parsers/fastsam.py, depthai_nodes/node/parsers/utils/fastsam.py, tests/stability_tests/run_parser_test.py
Parser construction and mask generation now support native segmentation masks, background_class, and 255-filled uint8 outputs.
Native mask consumers and remapping
depthai_nodes/node/apply_colormap.py, depthai_nodes/node/utils/message_remapping.py, depthai_nodes/node/utils/util_constants.py, tests/unittests/test_nodes/test_host_nodes/test_apply_colormap_node.py
Consumers and remapping use dai.SegmentationMask, native CV-mask accessors, and updated value normalization.
Native mask validation and test wiring
tests/stability_tests/check_messages.py, tests/utils/nodes/mocks/pipeline.py
Stability checks and test mocks support native mask types and parser configuration.

CI and dependency version bump

Layer / File(s) Summary
DepthAI version bump across workflows and requirements
.github/workflows/e2e_tests.yaml, .github/workflows/stability_tests.yaml, requirements.txt
Workflow defaults, job arguments, and the minimum depthai requirement now use version 3.8.0.

YOLOExtendedParser stride configuration

Layer / File(s) Summary
setStrides method addition
depthai_nodes/node/parsers/yolo.py
Adds a validated setter for configuring YOLO head strides.

SnapData documentation update

Layer / File(s) Summary
SnapData and native mask documentation
depthai_nodes/message/README.md, depthai_nodes/node/README.md
Documentation now describes SnapData and native dai.SegmentationMask outputs.

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

Possibly related PRs

Suggested reviewers: tersekmatija

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main shift to native DepthAI segmentation parser and mask support.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/86ca5v4v7-86ca5y69r-native-segmentation

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

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (2)
depthai_nodes/node/utils/message_remapping.py (1)

62-78: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Use a uint8 border sentinel here cv2.warpPerspective turns borderValue=-1 into 0 for uint8 masks, so remapped border pixels are labeled as class 0 instead of the unassigned sentinel used elsewhere (255). Set borderValue=255 or make it dtype-aware.

🤖 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 `@depthai_nodes/node/utils/message_remapping.py` around lines 62 - 78, The
remapping logic in remap_segmentation_mask_array uses a borderValue that does
not preserve the unassigned class for uint8 masks, so border pixels get remapped
to class 0 instead of the sentinel used elsewhere. Update the
cv2.warpPerspective call to use a uint8-safe sentinel such as 255, or make the
borderValue depend on the segmentation_mask dtype, while keeping the existing
transformation and interpolation behavior unchanged.
depthai_nodes/node/utils/util_constants.py (1)

12-23: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Change UNASSIGNED_MASK_LABEL to 255 in mask remapping. depthai_nodes/node/utils/message_remapping.py still uses this constant as borderValue for cv2.warpPerspective, and -1 gets clipped to 0 for uint8 masks, not 255. That turns padded/unassigned pixels into class 0 instead of background.

🤖 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 `@depthai_nodes/node/utils/util_constants.py` around lines 12 - 23, The mask
remapping background sentinel is wrong: UNASSIGNED_MASK_LABEL should be set to
255 so padded pixels stay as background instead of being clipped to 0 for uint8
masks. Update the constant in util_constants and keep message_remapping’s
cv2.warpPerspective borderValue usage aligned with that sentinel so unassigned
mask areas remain correctly marked.
🤖 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 @.github/workflows/e2e_tests.yaml:
- Around line 114-115: The `exec hil_runner` command in the workflow is
interpolating `github.ref_name` directly into a shell string, which can allow
template/shell injection on the runner. Move `github.ref_name` and the other
`${{ }}` values used in `--docker-run-args` into step-level `env:` variables,
then reference them as shell variables inside the `run:` command. Keep the fix
localized to this workflow step so the `exec hil_runner` invocation no longer
embeds attacker-influenced values directly.

In `@depthai_nodes/node/parsers/fastsam.py`:
- Around line 380-382: The empty-detection fallback in merge_masks handling is
using an all-255 mask, which gets treated as active pixels and overwrites the
output instead of preserving the background/unassigned sentinel. Update the
no-results branch in fastsam.py around the results_masks initialization so the
fallback is zero-filled before calling merge_masks(), keeping the inactive path
truly inactive.

In `@depthai_nodes/node/parsers/segmentation.py`:
- Around line 47-58: The SegmentationParser currently skips the
`background_class` remap whenever `classes_in_one_layer` is true, so class 0
remains unchanged in that combination. Update the parsing logic in
`SegmentationParser` so the background remap is still applied when
`background_class` is enabled, even if `classes_in_one_layer` is set, or
explicitly validate/document that this flag combination is unsupported. Use the
`SegmentationParser` initializer and the class-remapping branch in its parse
flow to locate the change.

In `@depthai_nodes/node/utils/message_remapping.py`:
- Around line 81-92: remap_segmentation_mask currently rebuilds a new
dai.SegmentationMask but only transfers the CV mask, so labels metadata is lost.
Update remap_segmentation_mask in message_remapping.py to preserve labels the
same way copy_message.py does: read labels from the input segmentation_mask when
available, and set them on new_mask after setCvMask, using the same guarded
getLabels/setLabels pattern as the existing message-copy logic.

---

Outside diff comments:
In `@depthai_nodes/node/utils/message_remapping.py`:
- Around line 62-78: The remapping logic in remap_segmentation_mask_array uses a
borderValue that does not preserve the unassigned class for uint8 masks, so
border pixels get remapped to class 0 instead of the sentinel used elsewhere.
Update the cv2.warpPerspective call to use a uint8-safe sentinel such as 255, or
make the borderValue depend on the segmentation_mask dtype, while keeping the
existing transformation and interpolation behavior unchanged.

In `@depthai_nodes/node/utils/util_constants.py`:
- Around line 12-23: The mask remapping background sentinel is wrong:
UNASSIGNED_MASK_LABEL should be set to 255 so padded pixels stay as background
instead of being clipped to 0 for uint8 masks. Update the constant in
util_constants and keep message_remapping’s cv2.warpPerspective borderValue
usage aligned with that sentinel so unassigned mask areas remain correctly
marked.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: cb782501-6076-47ad-931e-5f93cb42ebc7

📥 Commits

Reviewing files that changed from the base of the PR and between 90b4974 and 5a93ce6.

📒 Files selected for processing (23)
  • .github/workflows/e2e_tests.yaml
  • .github/workflows/stability_tests.yaml
  • depthai_nodes/message/README.md
  • depthai_nodes/message/__init__.py
  • depthai_nodes/message/creators/segmentation.py
  • depthai_nodes/message/segmentation.py
  • depthai_nodes/message/utils/copy_message.py
  • depthai_nodes/node/README.md
  • depthai_nodes/node/apply_colormap.py
  • depthai_nodes/node/parser_generator.py
  • depthai_nodes/node/parsers/fastsam.py
  • depthai_nodes/node/parsers/segmentation.py
  • depthai_nodes/node/parsers/utils/fastsam.py
  • depthai_nodes/node/parsers/yolo.py
  • depthai_nodes/node/utils/message_remapping.py
  • depthai_nodes/node/utils/util_constants.py
  • requirements.txt
  • tests/stability_tests/check_messages.py
  • tests/unittests/test_creators/test_segmentation.py
  • tests/unittests/test_messages/test_copy_message.py
  • tests/unittests/test_messages/test_segmentation_msg.py
  • tests/unittests/test_nodes/test_host_nodes/test_apply_colormap_node.py
  • tests/utils/messages/creators/arrays.py
💤 Files with no reviewable changes (4)
  • depthai_nodes/message/init.py
  • depthai_nodes/message/segmentation.py
  • tests/unittests/test_messages/test_segmentation_msg.py
  • depthai_nodes/message/README.md

Comment thread .github/workflows/e2e_tests.yaml Outdated
Comment thread depthai_nodes/node/parsers/fastsam.py Outdated
Comment thread depthai_nodes/node/parsers/segmentation.py
Comment thread depthai_nodes/node/utils/message_remapping.py

@klemen1999 klemen1999 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.

Few comments but overall looks good

Comment thread depthai_nodes/message/utils/copy_message.py Outdated
Comment thread depthai_nodes/node/parsers/utils/fastsam.py
Comment thread depthai_nodes/node/parsers/fastsam.py Outdated
Comment thread depthai_nodes/node/parsers/segmentation.py Outdated
@klemen1999

Copy link
Copy Markdown
Collaborator

TODO: Before merge we need next DepthAI version released. This means that we need to wait with merge and update the requirements.txt

Comment thread depthai_nodes/node/parser_generator.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 `@tests/stability_tests/run_parser_test.py`:
- Around line 93-96: The stability test currently forces SegmentationParser to
use the host-side path, so it never validates the native
dai.node.SegmentationParser flow. Update the test around parser_generator.build
in run_parser_test.py to add a separate SegmentationParser case or parameterize
hostOnly so both host-only and native segmentation parsing are exercised, while
keeping the existing parser_name-based logic for the other parsers.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: ba14b24d-a601-46b7-846e-fc0328c0b379

📥 Commits

Reviewing files that changed from the base of the PR and between 5a93ce6 and c74ea5b.

📒 Files selected for processing (3)
  • depthai_nodes/node/parsers/fastsam.py
  • tests/stability_tests/check_messages.py
  • tests/stability_tests/run_parser_test.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/stability_tests/check_messages.py
  • depthai_nodes/node/parsers/fastsam.py

Comment thread tests/stability_tests/run_parser_test.py
@rolandocortez

Copy link
Copy Markdown
Contributor Author

Got it. Pushed the follow-up fixes and CI is green now. I fixed the stability failures from the native SegmentationMask migration, addressed the review comments around getLabels/setLabels, background_class handling, and setNNArchiveHead(head), and updated the parser mock to match the new ParserGenerator API usage.

Comment thread depthai_nodes/node/parsers/fastsam.py Outdated
Comment thread tests/stability_tests/check_messages.py Outdated
Comment thread tests/stability_tests/run_parser_test.py
@codecov-commenter

codecov-commenter commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 38.23529% with 42 lines in your changes missing coverage. Please review.
✅ Project coverage is 48.34%. Comparing base (90b4974) to head (d89ad06).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
depthai_nodes/node/parsers/segmentation.py 9.52% 19 Missing ⚠️
depthai_nodes/node/parsers/yolo.py 9.09% 10 Missing ⚠️
depthai_nodes/node/parser_generator.py 30.00% 7 Missing ⚠️
depthai_nodes/node/utils/message_remapping.py 0.00% 3 Missing ⚠️
depthai_nodes/node/parsers/fastsam.py 0.00% 2 Missing ⚠️
depthai_nodes/node/parsers/utils/fastsam.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #304      +/-   ##
==========================================
- Coverage   48.69%   48.34%   -0.35%     
==========================================
  Files         100       99       -1     
  Lines        6430     6410      -20     
==========================================
- Hits         3131     3099      -32     
- Misses       3299     3311      +12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 @.github/workflows/e2e_tests.yaml:
- Around line 114-115: Update both hil_runner command call sites around the
visible --docker-run-args invocations to avoid direct interpolation of
github.ref_name into shell command strings. Define the branch name through the
workflow step-level env configuration, then reference the quoted shell variable
in each command while preserving the existing BRANCH value behavior.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: d06aafb0-40c3-4834-bde1-f0fa3fe6acbc

📥 Commits

Reviewing files that changed from the base of the PR and between ea03305 and 23f9737.

📒 Files selected for processing (3)
  • .github/workflows/e2e_tests.yaml
  • .github/workflows/stability_tests.yaml
  • requirements.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • requirements.txt

Comment thread .github/workflows/e2e_tests.yaml Outdated
@klemen1999
klemen1999 merged commit 981ecf7 into main Jul 13, 2026
13 checks passed
@klemen1999
klemen1999 deleted the feat/86ca5v4v7-86ca5y69r-native-segmentation branch July 13, 2026 12:58
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