Skip to content

Commit 522697c

Browse files
aymuos15ericspod
andauthored
fix(data): skip empty foreground when computing DatasetSummary statistics (#9043)
### Description `DatasetSummary.calculate_statistics` crashed with a bare `RuntimeError` on any sample whose label had no foreground voxels at the given `foreground_threshold` (common with 2D slices or sparse annotations), and if every sample lacked foreground it would divide by zero in the mean/std. `calculate_percentiles` had the same empty-accumulation hazard. Both methods now skip empty foreground selections and, when no sample contributes any foreground voxels, raise an actionable `ValueError` that names `foreground_threshold` and points to setting it to `-1` to compute statistics over whole images: - `monai/data/dataset_summary.py` — `calculate_statistics` `continue`s past empty foreground selections and guards `voxel_ct == 0`; `calculate_percentiles` skips empty selections and guards the accumulated list before calling `np.percentile`. - `tests/data/test_dataset_summary.py` — two new tests: a mixed foreground/background dataset (statistics and percentiles computed from the remaining foreground), and an all-background dataset (`ValueError` raised by both methods). Behavior verified end-to-end: a dataset with one normal and one all-background sample now produces statistics from the normal sample (previously it crashed), and an all-background dataset raises the actionable `ValueError` from both `calculate_statistics` and `calculate_percentiles`. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not-applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk> Signed-off-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent e28a2c0 commit 522697c

2 files changed

Lines changed: 46 additions & 3 deletions

File tree

‎monai/data/dataset_summary.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,13 +159,20 @@ def calculate_statistics(self, foreground_threshold: int = 0):
159159
label, *_ = convert_data_type(data=label, output_type=torch.Tensor)
160160

161161
image_foreground = image[torch.where(label > foreground_threshold)]
162+
if image_foreground.numel() == 0:
163+
continue
162164

163165
voxel_max.append(image_foreground.max().item())
164166
voxel_min.append(image_foreground.min().item())
165167
voxel_ct += len(image_foreground)
166168
voxel_sum += image_foreground.sum()
167169
voxel_square_sum += torch.square(image_foreground).sum()
168170

171+
if voxel_ct == 0:
172+
raise ValueError(
173+
f"No foreground voxels found in any sample with {foreground_threshold=}; "
174+
"set foreground_threshold=-1 to compute statistics over whole images."
175+
)
169176
self.data_max, self.data_min = max(voxel_max), min(voxel_min)
170177
self.data_mean = (voxel_sum / voxel_ct).item()
171178
self.data_std = (torch.sqrt(voxel_square_sum / voxel_ct - self.data_mean**2)).item()
@@ -204,11 +211,17 @@ def calculate_percentiles(
204211
label, *_ = convert_data_type(data=label, output_type=torch.Tensor)
205212

206213
intensities = image[torch.where(label > foreground_threshold)].tolist()
207-
if sampling_flag:
208-
intensities = intensities[::interval]
209-
all_intensities.append(intensities)
214+
if intensities:
215+
if sampling_flag:
216+
intensities = intensities[::interval]
217+
all_intensities.append(intensities)
210218

211219
all_intensities = list(chain(*all_intensities))
220+
if not all_intensities:
221+
raise ValueError(
222+
f"No foreground voxels found in any sample with {foreground_threshold=}; "
223+
"set foreground_threshold=-1 to compute statistics over whole images."
224+
)
212225
self.data_min_percentile, self.data_max_percentile = np.percentile(
213226
all_intensities, [min_percentile, max_percentile]
214227
)

‎tests/data/test_dataset_summary.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import nibabel as nib
2020
import numpy as np
21+
import torch
2122

2223
from monai.data import Dataset, DatasetSummary, create_test_image_3d
2324
from monai.transforms import LoadImaged
@@ -99,6 +100,35 @@ def test_anisotropic_spacing(self):
99100
target_spacing = calculator.get_target_spacing(anisotropic_threshold=4.0, percentile=20.0)
100101
np.testing.assert_allclose(target_spacing, (1.0, 1.0, 1.8))
101102

103+
def test_mixed_foreground_and_background(self):
104+
data = [
105+
{"image": torch.rand(1, 4, 4), "label": torch.ones(1, 4, 4)},
106+
{"image": torch.rand(1, 4, 4), "label": torch.zeros(1, 4, 4)},
107+
]
108+
image = torch.cat([d["image"] for d in data])
109+
label = torch.cat([d["label"] for d in data])
110+
expected = image[torch.where(label > 0)]
111+
112+
calculator = DatasetSummary(data, num_workers=0)
113+
calculator.calculate_statistics()
114+
np.testing.assert_allclose(calculator.data_mean, expected.mean().item(), rtol=1e-5, atol=1e-5)
115+
np.testing.assert_allclose(calculator.data_std, expected.std(correction=0).item(), rtol=1e-5, atol=1e-5)
116+
np.testing.assert_allclose(calculator.data_max, expected.max().item(), rtol=1e-5, atol=1e-5)
117+
np.testing.assert_allclose(calculator.data_min, expected.min().item(), rtol=1e-5, atol=1e-5)
118+
119+
calculator.calculate_percentiles(sampling_flag=False)
120+
np.testing.assert_allclose(calculator.data_min_percentile, np.percentile(expected, 0.5), rtol=1e-5, atol=1e-5)
121+
np.testing.assert_allclose(calculator.data_max_percentile, np.percentile(expected, 99.5), rtol=1e-5, atol=1e-5)
122+
np.testing.assert_allclose(calculator.data_median, np.median(expected), rtol=1e-5, atol=1e-5)
123+
124+
def test_all_background(self):
125+
data = [{"image": torch.rand(1, 4, 4), "label": torch.zeros(1, 4, 4)}]
126+
calculator = DatasetSummary(data, num_workers=0)
127+
with self.assertRaisesRegex(ValueError, "foreground_threshold"):
128+
calculator.calculate_statistics()
129+
with self.assertRaisesRegex(ValueError, "foreground_threshold"):
130+
calculator.calculate_percentiles()
131+
102132

103133
if __name__ == "__main__":
104134
unittest.main()

0 commit comments

Comments
 (0)