Skip to content

Commit da82630

Browse files
committed
add bbox to metadata
- same format as scikit-image regionprops bbox - add test
1 parent 7fff6ff commit da82630

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

napari_crop/_function.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,20 @@ def crop_region(
110110

111111
# trim zeros
112112
non_zero = np.where(cropped_data != 0)
113-
indices = [slice(min(i_nz), max(i_nz) + 1) for i_nz in non_zero]
113+
slices = [slice(min(i_nz), max(i_nz) + 1) for i_nz in non_zero]
114114
if rgb:
115-
indices[-1] = slice(None)
116-
cropped_data = cropped_data[tuple(indices)]
115+
slices[-1] = slice(None)
116+
cropped_data = cropped_data[tuple(slices)]
117117

118118
new_layer_props = layer_props.copy()
119+
# Update start and stop values for bbox
120+
start = [slc.start for slc in slices if slc is not None]
121+
stop = [slc.stop for slc in slices if slc is not None]
122+
# Add cropped coordinates as metadata
123+
# bounding box: (min_row, max_row, min_col, max_col)
124+
# Pixels belonging to the bounding box are in the half-open interval [min_row; max_row) and [min_col; max_col).
125+
new_layer_props['metadata'] = {'bbox': (start[0], stop[0], start[1], stop[1])}
126+
119127
# If layer name is in viewer or is about to be added,
120128
# increment layer name until it has a different name
121129
while True:

napari_crop/_tests/test_function.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,10 @@
2323
[ 0, 6, 7, 8, 0],
2424
[10, 11, 12, 13, 14],
2525
[ 0, 0, 17, 0, 0]]), # fmt: skip
26-
2726
]
27+
bbox_expected = [(1.0, 5.0, 1.0, 4.0),
28+
(1.0, 5.0, 1.0, 4.0),
29+
(0.0, 4.0, 0.0, 5.0)]
2830

2931
# rectangle crop
3032
# array([[ 6, 7, 8],
@@ -62,6 +64,22 @@ def test_crop_function_values_2d(make_napari_viewer, shape, shape_type,
6264
assert np.array_equal(crop_expected, cropped_actual_arrays)
6365

6466

67+
@pytest.mark.parametrize(
68+
"shape,shape_type,bbox_expected",
69+
zip(shapes, shape_types, bbox_expected)
70+
)
71+
def test_bbox_values(make_napari_viewer, shape, shape_type,
72+
bbox_expected):
73+
"""Test that the bbox returned in metadata is correct."""
74+
75+
viewer = make_napari_viewer()
76+
img_layer = viewer.add_image(arr_2d)
77+
shapes_layer = viewer.add_shapes(shape, shape_type=shape_type)
78+
cropped_actual = crop_region(img_layer, shapes_layer)[0][1] # get layer properties
79+
bbox = cropped_actual['metadata']['bbox']
80+
assert np.array_equal(bbox_expected, bbox)
81+
82+
6583
def test_crop_multiple_shapes(make_napari_viewer):
6684
"""Test that 'n' drawn shapes return 'n' new cropped layers"""
6785

0 commit comments

Comments
 (0)