Skip to content

fix: Clean elements outside mask for multiple otsu method#1319

Merged
Czaki merged 3 commits intodevelopfrom
mask_in_multiple_otsu
Oct 15, 2025
Merged

fix: Clean elements outside mask for multiple otsu method#1319
Czaki merged 3 commits intodevelopfrom
mask_in_multiple_otsu

Conversation

@Czaki
Copy link
Collaborator

@Czaki Czaki commented Oct 14, 2025

Fix problem from image:
IMG_20251015_011543.jpg

Summary by Sourcery

Bug Fixes:

  • Zero out segmentation voxels outside the mask when a mask is provided

Summary by CodeRabbit

  • Bug Fixes

    • Segmentation now properly respects masks: background/invalid regions are excluded from size calculations and threshold annotations, resulting in accurate component sizes and per-component thresholds when a mask is applied.
  • Chores

    • Project configuration updated to list an additional tool/library; this is a metadata change with no direct user-facing impact.

@Czaki Czaki added this to the 0.16.4 milestone Oct 14, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 14, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Ensures that segmentation outputs respect the provided mask by zeroing out elements outside it before further processing in the multiple OTUs method.

Sequence diagram for segmentation output masking in multiple OTUs method

sequenceDiagram
    participant "calculation_run()"
    participant "SimpleITK"
    participant "Mask"
    participant "Result Array"
    "calculation_run()"->>"SimpleITK": GetArrayFromImage(res)
    "SimpleITK"-->>"Result Array": Return array
    "calculation_run()"->>"Mask": Check if mask exists
    alt Mask exists
        "calculation_run()"->>"Result Array": Set elements outside mask to 0
    end
    "calculation_run()"->>"Result Array": Continue processing (bincount, etc.)
Loading

File-Level Changes

Change Details Files
Apply mask filter to segmentation result array
  • Check for presence of mask before mask-based operation
  • Set array values to zero where mask equals zero
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 14, 2025

Walkthrough

Added a dependency entry "otsu" to .github/project_dict.pws. Updated restartable segmentation in package/PartSegCore/segmentation/restartable_segmentation_algorithms.py to apply the mask to the ITK→NumPy result (setting res[mask==0]=0) before bincount and threshold/annotation computations.

Changes

Cohort / File(s) Summary
Project metadata
\.github/project_dict.pws
Added dependency entry otsu.
Segmentation mask handling
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py
After converting ITK result to NumPy, set res[mask==0] = 0 (applied mask) prior to bincount and threshold/annotation generation; affects sizing and per-component thresholds when a mask is present.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant I as Image + Mask
  participant A as RestartableSegmentation
  participant ITK as ITK Engine
  participant NP as NumPy Ops

  I->>A: Provide image and mask
  A->>ITK: Run segmentation
  ITK-->>A: Return ITK label image
  A->>NP: Convert ITK label image → NumPy `res`
  A->>NP: Apply mask: `res[mask==0] = 0`  %% New/changed step (mask enforced)
  A->>NP: Compute sizes (`bincount`)
  A->>A: Generate thresholds / annotations based on masked `res`
  A-->>I: Return segmentation labels and metadata
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibbled through arrays with a twitch and a hop,
Masking the meadows where zeros must stop.
Otsu came strolling, a neat little guest,
Labels now mind the places of rest.
Bins counted tidy, thresholds in sight—
Hoppy segmentation, snug and right! 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly summarizes the primary change by indicating a bug fix that zeros out elements outside the mask in the multiple Otsu method without introducing extraneous detail or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mask_in_multiple_otsu

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 and usage tips.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1)

645-646: Consider adding test coverage for mask application.

Ensure test coverage verifies that:

  1. Segmentation voxels outside the mask are properly zeroed
  2. Size counts exclude masked regions
  3. The behavior is correct when mask is None vs. when mask is provided

Would you like me to help draft unit tests for this masking behavior?

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11c3869 and 9d2c9bd.

📒 Files selected for processing (2)
  • .github/project_dict.pws (1 hunks)
  • package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (4)
package/PartSeg/common_gui/algorithms_description.py (1)
  • mask (685-686)
package/PartSeg/common_backend/base_settings.py (2)
  • mask (582-583)
  • mask (586-591)
package/PartSegImage/image.py (1)
  • mask (539-540)
package/PartSegCore/segmentation/algorithm_base.py (2)
  • mask (165-168)
  • mask (171-175)
🪛 GitHub Actions: Tests
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py

[error] 645-645: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: 4DNucleome.PartSeg (Tests_other test windows)
  • GitHub Check: 4DNucleome.PartSeg (Tests_linux test_linux)
  • GitHub Check: 4DNucleome.PartSeg (Tests_other test macos)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller windows)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller macos_arm)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller macos)
  • GitHub Check: 4DNucleome.PartSeg (Builds sdist)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller_linux)
  • GitHub Check: 4DNucleome.PartSeg (Documentation_check Notebook_check)
  • GitHub Check: 4DNucleome.PartSeg (formatting_check check_formating)
  • GitHub Check: 4DNucleome.PartSeg (Documentation_check help)
  • GitHub Check: 4DNucleome.PartSeg (GetTestData linux)
  • GitHub Check: 4DNucleome.PartSeg (manifest_check manifest_check)
  • GitHub Check: Sourcery review
🔇 Additional comments (2)
.github/project_dict.pws (1)

27-27: LGTM!

Adding "otsu" to the spell-check dictionary is appropriate for this codebase that implements Otsu thresholding algorithms.

package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1)

645-646: Only OtsuSegment needs explicit mask‐zeroing; other threshold algorithms use thr.calculate_mask (which respects self.mask) and don’t convert ITK images directly to NumPy.

@sonarqubecloud
Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1)

645-646: LGTM! The masking logic is correctly implemented.

The fix from the previous review has been applied—using if self.mask is not None: instead of if self.mask: correctly handles NumPy arrays. The masking operation (res[self.mask == 0] = 0) appropriately zeroes out segmentation values outside the mask before size counting and annotation generation.

This approach is sound because SimpleITK.OtsuMultipleThresholds doesn't accept a mask parameter, so post-processing the result is the correct way to constrain segmentation to the masked region.

Optional: Consider adding a clarifying comment.

For future maintainability, you might add a brief comment explaining why masking is applied here:

# Apply mask since SimpleITK.OtsuMultipleThresholds doesn't support masking
if self.mask is not None:
    res[self.mask == 0] = 0
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d2c9bd and ea69d22.

📒 Files selected for processing (1)
  • package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
package/PartSegCore/segmentation/restartable_segmentation_algorithms.py (3)
package/PartSeg/common_gui/algorithms_description.py (1)
  • mask (685-686)
package/PartSegImage/image.py (1)
  • mask (539-540)
package/PartSegCore/segmentation/algorithm_base.py (2)
  • mask (165-168)
  • mask (171-175)
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (18)
  • GitHub Check: 4DNucleome.PartSeg (Tests_other test windows)
  • GitHub Check: 4DNucleome.PartSeg (Tests_other test macos)
  • GitHub Check: 4DNucleome.PartSeg (Tests_linux test_linux)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller windows)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller macos_arm)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller macos)
  • GitHub Check: 4DNucleome.PartSeg (Builds sdist)
  • GitHub Check: 4DNucleome.PartSeg (Builds pyinstaller_linux)
  • GitHub Check: Base py3.11 / macos-15-intel py 3.11 latest PyQt5
  • GitHub Check: Base py3.10 / ubuntu-24.04 py 3.10 latest PyQt5
  • GitHub Check: test_coverage / ubuntu-24.04 py 3.12 latest PyQt5
  • GitHub Check: 4DNucleome.PartSeg (manifest_check manifest_check)
  • GitHub Check: 4DNucleome.PartSeg (Documentation_check Notebook_check)
  • GitHub Check: 4DNucleome.PartSeg (formatting_check check_formating)
  • GitHub Check: 4DNucleome.PartSeg (GetTestData linux)
  • GitHub Check: 4DNucleome.PartSeg (Documentation_check help)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Sourcery review

@codecov
Copy link

codecov bot commented Oct 15, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (11c3869) to head (ea69d22).
⚠️ Report is 29 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #1319   +/-   ##
========================================
  Coverage    93.16%   93.16%           
========================================
  Files          210      210           
  Lines        33285    33287    +2     
========================================
+ Hits         31009    31011    +2     
  Misses        2276     2276           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Czaki Czaki changed the title fix: Clean elements outside mask for multiple otus method fix: Clean elements outside mask for multiple otsu method Oct 15, 2025
@Czaki Czaki merged commit 3c5946c into develop Oct 15, 2025
58 of 60 checks passed
@Czaki Czaki deleted the mask_in_multiple_otsu branch October 15, 2025 06:56
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.

1 participant

Comments