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

Class ToTensor

monai/transforms/utility/array.py:383–423  ·  view source on GitHub ↗

Converts the input image to a tensor without applying any other transformations. Input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc. Will convert Tensor, Numpy array, float, int, bool to Tensor, strings and objects keep the original. For dict

Source from the content-addressed store, hash-verified

381
382
383class ToTensor(Transform):
384 """
385 Converts the input image to a tensor without applying any other transformations.
386 Input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc.
387 Will convert Tensor, Numpy array, float, int, bool to Tensor, strings and objects keep the original.
388 For dictionary, list or tuple, convert every item to a Tensor if applicable and `wrap_sequence=False`.
389
390 Args:
391 dtype: target data type to when converting to Tensor.
392 device: target device to put the converted Tensor data.
393 wrap_sequence: if `False`, then lists will recursively call this function, default to `True`.
394 E.g., if `False`, `[1, 2]` -> `[tensor(1), tensor(2)]`, if `True`, then `[1, 2]` -> `tensor([1, 2])`.
395 track_meta: whether to convert to `MetaTensor` or regular tensor, default to `None`,
396 use the return value of ``get_track_meta``.
397
398 """
399
400 backend = [TransformBackends.TORCH]
401
402 def __init__(
403 self,
404 dtype: torch.dtype | None = None,
405 device: torch.device | str | None = None,
406 wrap_sequence: bool = True,
407 track_meta: bool | None = None,
408 ) -> None:
409 super().__init__()
410 self.dtype = dtype
411 self.device = device
412 self.wrap_sequence = wrap_sequence
413 self.track_meta = get_track_meta() if track_meta is None else bool(track_meta)
414
415 def __call__(self, img: NdarrayOrTensor):
416 """
417 Apply the transform to `img` and make it contiguous.
418 """
419 if isinstance(img, MetaTensor):
420 img.applied_operations = [] # drops tracking info
421 return convert_to_tensor(
422 img, dtype=self.dtype, device=self.device, wrap_sequence=self.wrap_sequence, track_meta=self.track_meta
423 )
424
425
426class EnsureType(Transform):

Callers 15

__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
test_valueMethod · 0.90
test_class_valueMethod · 0.90
test_valueMethod · 0.90
test_class_valueMethod · 0.90
test_cachedatasetMethod · 0.90
test_decollation_listMethod · 0.90
test_array_inputMethod · 0.90

Calls

no outgoing calls

Tested by 14

test_valueMethod · 0.72
test_class_valueMethod · 0.72
test_valueMethod · 0.72
test_class_valueMethod · 0.72
test_cachedatasetMethod · 0.72
test_decollation_listMethod · 0.72
test_array_inputMethod · 0.72
test_single_inputMethod · 0.72
test_cupyMethod · 0.72
test_transform_arrayMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…