Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/spatialdata/_core/operations/aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
16 changes: 16 additions & 0 deletions tests/core/operations/test_aggregations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading