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
5 changes: 3 additions & 2 deletions monai/data/meta_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,8 @@ def astype(self, dtype, device=None, *_args, **_kwargs):
_kwargs: additional kwargs (currently unused).

Returns:
data array instance
``MetaTensor`` when a torch dtype is given (metadata is preserved),
or ``np.ndarray`` when a numpy dtype is given.
"""
if isinstance(dtype, str):
mod_str, *dtype = dtype.split(".", 1)
Expand All @@ -453,7 +454,7 @@ def astype(self, dtype, device=None, *_args, **_kwargs):

out_type: type[torch.Tensor] | type[np.ndarray] | None
if mod_str == "torch":
out_type = torch.Tensor
out_type = type(self)
elif mod_str in ("numpy", "np"):
out_type = np.ndarray
else:
Expand Down
8 changes: 6 additions & 2 deletions tests/data/meta_tensor/test_meta_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,8 +434,12 @@ def test_astype(self):
for np_types in ("float32", "np.float32", "numpy.float32", np.float32, float, "int", np.uint16):
self.assertIsInstance(t.astype(np_types), np.ndarray)
for pt_types in ("torch.float", torch.float, "torch.float64"):
self.assertIsInstance(t.astype(pt_types), torch.Tensor)
self.assertIsInstance(t.astype("torch.float", device="cpu"), torch.Tensor)
result = t.astype(pt_types)
self.assertIsInstance(result, MetaTensor)
self.assertEqual(result.meta.get("fname"), "filename")
result = t.astype("torch.float", device="cpu")
self.assertIsInstance(result, MetaTensor)
self.assertEqual(result.meta.get("fname"), "filename")

def test_transforms(self):
key = "im"
Expand Down
Loading