Skip to content

Commit 27728a1

Browse files
authored
Reject float-dtype labels with clear error in render_labels (#650)
1 parent 5e6f3a9 commit 27728a1

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

src/spatialdata_plot/pl/render.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1621,6 +1621,13 @@ def _render_labels(
16211621
is_label=True,
16221622
)
16231623

1624+
if np.issubdtype(label.dtype, np.floating):
1625+
raise ValueError(
1626+
f"Label element '{element}' has dtype {label.dtype}. Label arrays must use an "
1627+
f"integer dtype (e.g. int32 or uint16). Cast before plotting, e.g.:\n"
1628+
f" sdata['{element}'] = sdata['{element}'].astype('int32')"
1629+
)
1630+
16241631
# rasterize spatial image if necessary to speed up performance
16251632
if rasterize:
16261633
label = _rasterize_if_necessary(

tests/pl/test_render_labels.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,3 +473,20 @@ def track(x):
473473
plt.close(fig)
474474

475475
assert called, "transfunc was not called for continuous labels data"
476+
477+
478+
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64])
479+
def test_render_labels_rejects_float_dtype(dtype):
480+
# Regression test for #606: float-dtype labels must raise a clear
481+
# ValueError naming the element and dtype, not a cryptic skimage TypeError.
482+
arr = np.zeros((20, 20), dtype=dtype)
483+
arr[3:8, 3:8] = 1
484+
arr[12:17, 12:17] = 2
485+
sdata = SpatialData(labels={"lbl": Labels2DModel.parse(arr, dims=["y", "x"])})
486+
487+
fig, ax = plt.subplots()
488+
try:
489+
with pytest.raises(ValueError, match=r"Label element 'lbl'.*integer dtype"):
490+
sdata.pl.render_labels("lbl").pl.show(ax=ax)
491+
finally:
492+
plt.close(fig)

0 commit comments

Comments
 (0)