Pytorch

Transforms

class ToPytorch(transpose_mask: bool = True, always_apply: bool = True, normalize: None | Sequence[float] = None, p=1.0)[source]

Bases: BasicTransform

Convert image and mask to torch.Tensor. The numpy HWDC image is converted to pytorch CDHW tensor. If the image is in HWD format (grayscale image), it will be converted to pytorch DHW tensor.

Parameters:
  • transpose_mask (bool) – If True and an input mask has three spatial dimensions, this transform will transpose dimensions so the shape [height, width, depth, channel] becomes [channel, depth, height, width]. The latter format is a standard format for PyTorch Tensors. Default: True.

  • always_apply (bool) – Indicates whether this transformation should be always applied. Default: True.

  • p (float) – Probability of applying the transform. Default: 1.0.

apply(img: ndarray, **params) tensor[source]

Applies the transformation to the image

apply_to_mask(mask: ndarray, **params) tensor[source]

Applies the augmentation to a mask

apply_to_masks(masks: List[ndarray], **params) List[tensor][source]
get_params_dependent_on_targets(params: Dict[str, Any]) Dict[str, Any][source]

Returns additional parameters needed for the apply methods that depend on a target (e.g. apply_to_bboxes method expects image size)

get_transform_init_args_names() Tuple[str, ...][source]

Returns initialization argument names. (e.g. Transform(arg1 = 1, arg2 = 2) -> (‘arg1’, ‘arg2’))

property targets: Dict[str, Callable]

Returns the mapping of target to applicable apply method. (e.g. {‘image’: self.apply, ‘bboxes’, self.apply_to_bboxes})

Functional

img_to_tensor(im: ndarray, normalize: Dict[str, Sequence[float]] | None = None) tensor[source]

Casts a numpy array to a torch.tensor with the option to normalize

Parameters:
  • im (np.ndarray) – A numpy array

  • normalize (dict, None) – Optional keyword argument dictionary for torchvision.transforms.functional.normalize()

Returns:

A torch.tensor