From 33d4617ec6de1cefdde838707f53192b2f9a4907 Mon Sep 17 00:00:00 2001 From: Zuolin Cheng Date: Mon, 30 Nov 2026 13:10:28 -0800 Subject: [PATCH] Allow raster aggregation when labels have no background --- src/spatialdata/_core/operations/aggregate.py | 2 +- tests/core/operations/test_aggregations.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/spatialdata/_core/operations/aggregate.py b/src/spatialdata/_core/operations/aggregate.py index 550c2f48c..cd667dec1 100644 --- a/src/spatialdata/_core/operations/aggregate.py +++ b/src/spatialdata/_core/operations/aggregate.py @@ -330,7 +330,7 @@ def _aggregate_image_by_labels( index = kwargs.get("zone_ids") # `zone_ids` allows the user to select specific labels to aggregate by if index is None: index = np.array(da.array.unique(by.data)) - assert np.array(index == np.insert(zones, 0, 0)).all(), "Index mismatch between zonal stats and labels." + assert np.array_equal(index[index != 0], zones), "Index mismatch between zonal stats and labels." return ad.AnnData( X, obs=pd.DataFrame(index=zones.astype(str)), diff --git a/tests/core/operations/test_aggregations.py b/tests/core/operations/test_aggregations.py index 7fadeb6ec..3f8e50f3f 100644 --- a/tests/core/operations/test_aggregations.py +++ b/tests/core/operations/test_aggregations.py @@ -361,6 +361,22 @@ def test_aggregate_image_by_labels(labels_blobs, image_schema, labels_schema) -> assert len(out) == 3 +@pytest.mark.parametrize("background", [False, True]) +def test_aggregate_image_by_labels_background_is_optional(background): + label_values = np.array([[1, 1, 2], [1, 2, 0 if background else 2]], dtype=np.int32) + image_values = np.arange(6).reshape(2, 3) + labels = Labels2DModel.parse(label_values) + image = Image2DModel.parse(image_values[np.newaxis, ...]) + + table = aggregate(values=image, by=labels, agg_func="mean").tables["table"] + + assert table.obs["instance_id"].tolist() == [1, 2] + np.testing.assert_allclose( + table.X.toarray().ravel(), + [image_values[label_values == label].mean() for label in (1, 2)], + ) + + @pytest.mark.parametrize("multiscale_values", [False, True]) @pytest.mark.parametrize("multiscale_by", [False, True]) def test_aggregate_image_by_labels_multiscale(