Skip to content

Commit

Permalink
BoxToMask - explicit check for box extending over image shape (Projec…
Browse files Browse the repository at this point in the history
…t-MONAI#6637)

Fixes an unclear error message when BoxToMask is called with box
extending over passed spatial shape. Currently user face a numpy value
broadcast error.

### Description

An explicit check for box values vs `spatial_size`

### 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`.

Signed-off-by: Tomasz Bartczak <[email protected]>
  • Loading branch information
kretes authored Jun 22, 2023
1 parent d773ff3 commit 6de86a4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions monai/apps/detection/transforms/box_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,9 @@ def convert_box_to_mask(
boxes_mask_np = np.ones((labels.shape[0],) + spatial_size, dtype=np.int16) * np.int16(bg_label)

boxes_np: np.ndarray = convert_data_type(boxes, np.ndarray, dtype=np.int32)[0]
if np.any(boxes_np[:, spatial_dims:] > np.array(spatial_size)):
raise ValueError("Some boxes are larger than the image.")

labels_np, *_ = convert_to_dst_type(src=labels, dst=boxes_np)
for b in range(boxes_np.shape[0]):
# generate a foreground mask
Expand Down
18 changes: 18 additions & 0 deletions tests/test_box_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,24 @@ def test_value_3d_mask(self):
assert_allclose(data_back["boxes"], data["boxes"], type_test=False, device_test=False, atol=1e-3)
assert_allclose(data_back["labels"], data["labels"], type_test=False, device_test=False, atol=1e-3)

def test_shape_assertion(self):
test_dtype = torch.float32
image = np.zeros((1, 10, 10, 10))
boxes = np.array([[7, 8, 9, 10, 12, 13]])
data = {"image": image, "boxes": boxes, "labels": np.array((1,))}
data = CastToTyped(keys=["image", "boxes"], dtype=test_dtype)(data)
transform_to_mask = BoxToMaskd(
box_keys="boxes",
box_mask_keys="box_mask",
box_ref_image_keys="image",
label_keys="labels",
min_fg_label=0,
ellipse_mask=False,
)
with self.assertRaises(ValueError) as context:
transform_to_mask(data)
self.assertTrue("Some boxes are larger than the image." in str(context.exception))

@parameterized.expand(TESTS_3D)
def test_value_3d(
self,
Expand Down

0 comments on commit 6de86a4

Please sign in to comment.