diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py index 02c4aa91c6..1d82bb3a44 100644 --- a/monai/transforms/utility/array.py +++ b/monai/transforms/utility/array.py @@ -364,10 +364,12 @@ def __call__(self, img) -> np.ndarray: Apply the transform to `img` and make it contiguous. """ if isinstance(img, torch.Tensor): - img = img.detach().cpu().numpy() # type: ignore + img = img.detach().cpu().numpy() elif has_cp and isinstance(img, cp_ndarray): - img = cp.asnumpy(img) # type: ignore - return np.ascontiguousarray(img) + img = cp.asnumpy(img) + + array: np.ndarray = np.asarray(img) + return np.ascontiguousarray(array) if array.ndim > 0 else array class ToCupy(Transform): @@ -380,7 +382,7 @@ def __call__(self, img): Apply the transform to `img` and make it contiguous. """ if isinstance(img, torch.Tensor): - img = img.detach().cpu().numpy() # type: ignore + img = img.detach().cpu().numpy() return cp.ascontiguousarray(cp.asarray(img)) diff --git a/tests/test_to_numpy.py b/tests/test_to_numpy.py index 6e112e6be8..291601ffeb 100644 --- a/tests/test_to_numpy.py +++ b/tests/test_to_numpy.py @@ -58,6 +58,13 @@ def test_list_tuple(self): result = ToNumpy()(test_data) np.testing.assert_allclose(result, np.asarray(test_data)) + def test_single_value(self): + for test_data in [5, np.array(5), torch.tensor(5)]: + result = ToNumpy()(test_data) + self.assertTrue(isinstance(result, np.ndarray)) + np.testing.assert_allclose(result, np.asarray(test_data)) + self.assertEqual(result.ndim, 0) + if __name__ == "__main__": unittest.main()