fix(utils): fixes a bug in fill_holes_and_remove_small_masks #1367
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Bug Fix: fill_holes_and_remove_small_masks - Incorrect Label Removal
Problem Identified
When running celposeSAM with different cellprob_threshold I found that with lower thresholds I was missing cells, which was quite odd and should not be the case. The problem seems to be related the function
fill_holes_and_remove_small_masksincellpose/utils.py, that I think has a critical bug when removing small masks.Here an example with two thresholds where some cells are missing for cellprob_threshold = -5, both using min_size=500 and flow_threshold=0.95
cellprob_threshold = 0

cellprob_threshold = -5 (see that some obvious cells are missing)

The Buggy Code seems to be in (lines 645-647):
The code assumed mask labels are always sequential (1, 2, 3, ...), but this assumption is violated when
remove_bad_flow_masks()indynamics.pyremoves masks with poor flow quality.Example scenario:
get_masks_torch: labels = [1, 2, 3, 4]remove_bad_flow_masksremoves mask 2: labels = [1, 3, 4] (non-sequential!)fastremap.unique()returns counts in order of labels: [count_1, count_3, count_4]index + 1 = 1 + 1 = 2→ tries to remove label 2 (which doesn't exist!)Impact
Proposed Fix
This fix is applied to both filtering locations (before and after fill_voids).
Example image with cellprob_threshold = -5 after the fix