MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / CastToType

Class CastToType

monai/transforms/utility/array.py:337–380  ·  view source on GitHub ↗

Cast the Numpy data to specified numpy data type, or cast the PyTorch Tensor to specified PyTorch data type. Example: >>> import numpy as np >>> import torch >>> transform = CastToType(dtype=np.float32) >>> # Example with a numpy array >>> img_n

Source from the content-addressed store, hash-verified

335
336
337class CastToType(Transform):
338 """
339 Cast the Numpy data to specified numpy data type, or cast the PyTorch Tensor to
340 specified PyTorch data type.
341
342 Example:
343 >>> import numpy as np
344 >>> import torch
345 >>> transform = CastToType(dtype=np.float32)
346
347 >>> # Example with a numpy array
348 >>> img_np = np.array([0, 127, 255], dtype=np.uint8)
349 >>> img_np_casted = transform(img_np)
350 >>> img_np_casted
351 array([ 0. , 127. , 255. ], dtype=float32)
352
353 >>> # Example with a PyTorch tensor
354 >>> img_tensor = torch.tensor([0, 127, 255], dtype=torch.uint8)
355 >>> img_tensor_casted = transform(img_tensor)
356 >>> img_tensor_casted
357 tensor([ 0., 127., 255.]) # dtype is float32
358 """
359
360 backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
361
362 def __init__(self, dtype=np.float32) -> None:
363 """
364 Args:
365 dtype: convert image to this data type, default is `np.float32`.
366 """
367 self.dtype = dtype
368
369 def __call__(self, img: NdarrayOrTensor, dtype: DtypeLike | torch.dtype = None) -> NdarrayOrTensor:
370 """
371 Apply the transform to `img`, assuming `img` is a numpy array or PyTorch Tensor.
372
373 Args:
374 dtype: convert image to this data type, default is `self.dtype`.
375
376 Raises:
377 TypeError: When ``img`` type is not in ``Union[numpy.ndarray, torch.Tensor]``.
378
379 """
380 return convert_data_type(img, output_type=type(img), dtype=dtype or self.dtype)[0]
381
382
383class ToTensor(Transform):

Callers 6

__init__Method · 0.90
test_padMethod · 0.90
test_valueMethod · 0.90
test_typeMethod · 0.90
test_type_cupyMethod · 0.90
test_invertMethod · 0.90

Calls

no outgoing calls

Tested by 5

test_padMethod · 0.72
test_valueMethod · 0.72
test_typeMethod · 0.72
test_type_cupyMethod · 0.72
test_invertMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…