Esempio n. 1
0
    def __init__(
        self,
        keys: KeysCollection,
        degree: int = 3,
        coeff_range: Tuple[float, float] = (0.0, 0.1),
        dtype: DtypeLike = np.float32,
        prob: float = 1.0,
        allow_missing_keys: bool = False,
    ) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            degree: degree of freedom of the polynomials. The value should be no less than 1.
                Defaults to 3.
            coeff_range: range of the random coefficients. Defaults to (0.0, 0.1).
            dtype: output data type, defaut to float32.
            prob: probability to do random bias field.
            allow_missing_keys: don't raise exception if key is missing.

        """
        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob)

        self.rand_bias_field = RandBiasField(degree, coeff_range, dtype, prob)
Esempio n. 2
0
    def __init__(
        self,
        keys: KeysCollection,
        factors: Union[Tuple[float, float], float],
        prob: float = 0.1,
        allow_missing_keys: bool = False,
    ) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            factors: factor range to randomly scale by ``v = v * (1 + factor)``.
                if single number, factor value is picked from (-factors, factors).
            prob: probability of rotating.
                (Default 0.1, with 10% probability it returns a rotated array.)
            allow_missing_keys: don't raise exception if key is missing.

        """
        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob)

        if isinstance(factors, (int, float)):
            self.factors = (min(-factors, factors), max(-factors, factors))
        else:
            if len(factors) != 2:
                raise AssertionError(
                    "factors should be a number or pair of numbers.")
            self.factors = (min(factors), max(factors))
Esempio n. 3
0
    def __init__(
        self,
        keys: KeysCollection,
        spatial_size: Sequence[int],
        rand_size: Sequence[int],
        pad: int = 0,
        mode: Union[InterpolateModeType,
                    Sequence[InterpolateModeType]] = InterpolateMode.AREA,
        align_corners: Optional[bool] = None,
        prob: float = 0.1,
        gamma: Union[Sequence[float], float] = (0.5, 4.5),
        device: Optional[torch.device] = None,
    ):
        RandomizableTransform.__init__(self, prob)
        MapTransform.__init__(self, keys)

        self.mode = ensure_tuple_rep(mode, len(self.keys))

        self.trans = RandSmoothFieldAdjustContrast(
            spatial_size=spatial_size,
            rand_size=rand_size,
            pad=pad,
            mode=self.mode[0],
            align_corners=align_corners,
            prob=1.0,
            gamma=gamma,
            device=device,
        )
Esempio n. 4
0
    def __init__(
        self,
        keys: KeysCollection,
        prob: float = 0.1,
        width: Tuple[int, int] = (1450, 1550),
        level: Tuple[int, int] = (-550, -650),
        nonzero: bool = True,
        dtype: DtypeLike = np.float32,
        allow_missing_keys: bool = False,
    ) -> None:

        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob)

        self.nonzero = nonzero
        self.dtype = dtype

        if isinstance(width, tuple):
            self.width = (min(width), max(width))
        else:
            AssertionError("width is not a touple")
        if isinstance(level, tuple):
            self.level = (min(level), max(level))
        else:
            AssertionError("level is not a touple")

        self.width_value: Optional[int] = None
        self.level_value: Optional[int] = None
Esempio n. 5
0
    def __init__(
        self,
        keys: KeysCollection,
        factors: Union[Tuple[float, float], float],
        prob: float = 0.1,
        nonzero: bool = False,
        channel_wise: bool = False,
        allow_missing_keys: bool = False,
    ) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            factors: if tuple, the randomly picked range is (min(factors), max(factors)).
                If single number, the range is (-factors, factors).
            prob: probability of std shift.
            nonzero: whether only count non-zero values.
            channel_wise: if True, calculate on each channel separately.
            allow_missing_keys: don't raise exception if key is missing.
        """
        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob)

        if isinstance(factors, (int, float)):
            self.factors = (min(-factors, factors), max(-factors, factors))
        else:
            if len(factors) != 2:
                raise AssertionError(
                    "factors should be a number or pair of numbers.")
            self.factors = (min(factors), max(factors))
        self.nonzero = nonzero
        self.channel_wise = channel_wise
Esempio n. 6
0
 def __init__(
     self,
     keys: KeysCollection,
     label_key: str,
     spatial_size: Union[Sequence[int], int],
     pos: float = 1.0,
     neg: float = 1.0,
     num_samples: int = 1,
     image_key: Optional[str] = None,
     image_threshold: float = 0.0,
     fg_indices_key: Optional[str] = None,
     bg_indices_key: Optional[str] = None,
     allow_missing_keys: bool = False,
 ) -> None:
     RandomizableTransform.__init__(self)
     MapTransform.__init__(self, keys, allow_missing_keys)
     self.label_key = label_key
     self.spatial_size: Union[Tuple[int, ...], Sequence[int],
                              int] = spatial_size
     if pos < 0 or neg < 0:
         raise ValueError(
             f"pos and neg must be nonnegative, got pos={pos} neg={neg}.")
     if pos + neg == 0:
         raise ValueError("Incompatible values: pos=0 and neg=0.")
     self.pos_ratio = pos / (pos + neg)
     self.num_samples = num_samples
     self.image_key = image_key
     self.image_threshold = image_threshold
     self.fg_indices_key = fg_indices_key
     self.bg_indices_key = bg_indices_key
     self.centers: Optional[List[List[np.ndarray]]] = None
Esempio n. 7
0
 def __init__(
     self, keys: KeysCollection, prob: float = 0.1, mean: Union[Sequence[float], float] = 0.0, std: float = 0.1
 ) -> None:
     MapTransform.__init__(self, keys)
     RandomizableTransform.__init__(self, prob)
     self.mean = ensure_tuple_rep(mean, len(self.keys))
     self.std = std
     self._noise: List[np.ndarray] = []
Esempio n. 8
0
    def __init__(self,
                 keys: KeysCollection,
                 alpha: float = 0.5,
                 as_tensor_output: bool = True,
                 allow_missing_keys: bool = False) -> None:

        MapTransform.__init__(self, keys, allow_missing_keys)
        self.transform = GibbsNoise(alpha, as_tensor_output)
Esempio n. 9
0
 def __init__(
     self,
     keys: KeysCollection,
     roi_size: Union[Sequence[int], int],
     random_center: bool = True,
     random_size: bool = True,
     allow_missing_keys: bool = False,
 ) -> None:
     MapTransform.__init__(self, keys, allow_missing_keys)
     self.roi_size = roi_size
     self.random_center = random_center
     self.random_size = random_size
     self._slices: Optional[Tuple[slice, ...]] = None
     self._size: Optional[Sequence[int]] = None
Esempio n. 10
0
    def __init__(
        self,
        keys: KeysCollection,
        prob: float = 0.1,
        alpha: Sequence[float] = (0.0, 1.0),
        as_tensor_output: bool = True,
        allow_missing_keys: bool = False,
    ) -> None:

        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob=prob)
        self.alpha = alpha
        self.sampled_alpha = -1.0  # stores last alpha sampled by randomize()
        self.as_tensor_output = as_tensor_output
Esempio n. 11
0
 def __init__(
     self,
     keys: KeysCollection,
     roi_size: Union[Sequence[int], int],
     num_samples: int,
     random_center: bool = True,
     random_size: bool = True,
     allow_missing_keys: bool = False,
 ) -> None:
     RandomizableTransform.__init__(self)
     MapTransform.__init__(self, keys, allow_missing_keys)
     if num_samples < 1:
         raise ValueError(f"num_samples must be positive, got {num_samples}.")
     self.num_samples = num_samples
     self.cropper = RandSpatialCropd(keys, roi_size, random_center, random_size, allow_missing_keys)
Esempio n. 12
0
 def __init__(
     self, keys: KeysCollection, num_control_points: Union[Tuple[int, int], int] = 10, prob: float = 0.1
 ) -> None:
     MapTransform.__init__(self, keys)
     RandomizableTransform.__init__(self, prob)
     if isinstance(num_control_points, int):
         if num_control_points <= 2:
             raise AssertionError("num_control_points should be greater than or equal to 3")
         self.num_control_points = (num_control_points, num_control_points)
     else:
         if len(num_control_points) != 2:
             raise AssertionError("num_control points should be a number or a pair of numbers")
         if min(num_control_points) <= 2:
             raise AssertionError("num_control_points should be greater than or equal to 3")
         self.num_control_points = (min(num_control_points), max(num_control_points))
Esempio n. 13
0
 def __init__(
     self,
     keys: KeysCollection,
     w_key: str,
     spatial_size: Union[Sequence[int], int],
     num_samples: int = 1,
     center_coord_key: Optional[str] = None,
     allow_missing_keys: bool = False,
 ):
     MapTransform.__init__(self, keys, allow_missing_keys)
     self.spatial_size = ensure_tuple(spatial_size)
     self.w_key = w_key
     self.num_samples = int(num_samples)
     self.center_coord_key = center_coord_key
     self.centers: List[np.ndarray] = []
Esempio n. 14
0
 def __init__(
     self,
     keys: KeysCollection,
     sigma_x: Tuple[float, float] = (0.25, 1.5),
     sigma_y: Tuple[float, float] = (0.25, 1.5),
     sigma_z: Tuple[float, float] = (0.25, 1.5),
     approx: str = "erf",
     prob: float = 0.1,
 ) -> None:
     MapTransform.__init__(self, keys)
     RandomizableTransform.__init__(self, prob)
     self.sigma_x = sigma_x
     self.sigma_y = sigma_y
     self.sigma_z = sigma_z
     self.approx = approx
Esempio n. 15
0
 def __init__(
     self,
     keys: KeysCollection,
     global_prob: float = 0.1,
     prob: float = 1.0,
     mean: Union[Sequence[float], float] = 0.0,
     std: Union[Sequence[float], float] = 1.0,
     channel_wise: bool = False,
     relative: bool = False,
     sample_std: bool = True,
     allow_missing_keys: bool = False,
 ) -> None:
     MapTransform.__init__(self, keys, allow_missing_keys)
     RandomizableTransform.__init__(self, global_prob)
     self.rand_rician_noise = RandRicianNoise(prob, mean, std, channel_wise,
                                              relative, sample_std)
Esempio n. 16
0
    def __init__(
        self,
        keys: KeysCollection,
        sigma_x: Tuple[float, float] = (0.25, 1.5),
        sigma_y: Tuple[float, float] = (0.25, 1.5),
        sigma_z: Tuple[float, float] = (0.25, 1.5),
        approx: str = "erf",
        prob: float = 0.1,
        allow_missing_keys: bool = False,
    ) -> None:
        MapTransform.__init__(self, keys, allow_missing_keys)
        RandomizableTransform.__init__(self, prob)
        self.sigma_x, self.sigma_y, self.sigma_z = sigma_x, sigma_y, sigma_z
        self.approx = approx

        self.x, self.y, self.z = self.sigma_x[0], self.sigma_y[0], self.sigma_z[0]
Esempio n. 17
0
 def __init__(
     self,
     keys: KeysCollection,
     center_fractions: Sequence[float],
     accelerations: Sequence[float],
     spatial_dims: int = 2,
     is_complex: bool = True,
     allow_missing_keys: bool = False,
 ) -> None:
     MapTransform.__init__(self, keys, allow_missing_keys)
     self.masker = RandomKspaceMask(
         center_fractions=center_fractions,
         accelerations=accelerations,
         spatial_dims=spatial_dims,
         is_complex=is_complex,
     )
Esempio n. 18
0
 def __init__(
     self,
     keys: KeysCollection,
     roi_size: Union[Sequence[int], int],
     num_samples: int,
     max_roi_size: Optional[Union[Sequence[int], int]] = None,
     random_center: bool = True,
     random_size: bool = True,
     meta_key_postfix: str = "meta_dict",
     allow_missing_keys: bool = False,
 ) -> None:
     MapTransform.__init__(self, keys, allow_missing_keys)
     if num_samples < 1:
         raise ValueError(f"num_samples must be positive, got {num_samples}.")
     self.num_samples = num_samples
     self.cropper = RandSpatialCropd(keys, roi_size, max_roi_size, random_center, random_size, allow_missing_keys)
     self.meta_key_postfix = meta_key_postfix
Esempio n. 19
0
    def __init__(
        self,
        keys: KeysCollection,
        dtype: Union[Sequence[Union[DtypeLike, torch.dtype]], DtypeLike, torch.dtype] = np.float32,
    ) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            dtype: convert image to this data type, default is `np.float32`.
                it also can be a sequence of dtypes or torch.dtype,
                each element corresponds to a key in ``keys``.

        """
        MapTransform.__init__(self, keys)
        self.dtype = ensure_tuple_rep(dtype, len(self.keys))
        self.converter = CastToType()
Esempio n. 20
0
    def __init__(
        self, keys: KeysCollection, prob: float = 0.1, gamma: Union[Tuple[float, float], float] = (0.5, 4.5)
    ) -> None:
        MapTransform.__init__(self, keys)
        RandomizableTransform.__init__(self, prob)

        if isinstance(gamma, (int, float)):
            if gamma <= 0.5:
                raise AssertionError(
                    "if gamma is single number, must greater than 0.5 and value is picked from (0.5, gamma)"
                )
            self.gamma = (0.5, gamma)
        else:
            if len(gamma) != 2:
                raise AssertionError("gamma should be a number or pair of numbers.")
            self.gamma = (min(gamma), max(gamma))

        self.gamma_value: Optional[float] = None
Esempio n. 21
0
 def __init__(
     self,
     keys: KeysCollection,
     label_key: str,
     background: int = 0,
     pert: float = 0.0,
     sigma: Union[Sequence[float], float, Sequence[torch.Tensor], torch.Tensor] = 3.0,
     rescale_min: float = -1.0,
     rescale_max: float = 1.0,
 ):
     MapTransform.__init__(self, keys)
     self.background = background
     self.pert = pert
     self.points: List[Tuple[int, ...]] = []
     self.label_key = label_key
     self.sigma = sigma
     self.rescale_min = rescale_min
     self.rescale_max = rescale_max
Esempio n. 22
0
    def __init__(self, keys: KeysCollection, offsets: Union[Tuple[float, float], float], prob: float = 0.1) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            offsets: offset range to randomly shift.
                if single number, offset value is picked from (-offsets, offsets).
            prob: probability of rotating.
                (Default 0.1, with 10% probability it returns a rotated array.)
        """
        MapTransform.__init__(self, keys)
        RandomizableTransform.__init__(self, prob)

        if isinstance(offsets, (int, float)):
            self.offsets = (min(-offsets, offsets), max(-offsets, offsets))
        else:
            if len(offsets) != 2:
                raise AssertionError("offsets should be a number or pair of numbers.")
            self.offsets = (min(offsets), max(offsets))
Esempio n. 23
0
    def __init__(
        self,
        keys: KeysCollection,
        name: str,
        allow_missing_keys: bool = False,
        *args,
        **kwargs,
    ) -> None:
        """
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            name: The transform name in TorchVision package.
            allow_missing_keys: don't raise exception if key is missing.
            args: parameters for the TorchVision transform.
            kwargs: parameters for the TorchVision transform.

        """
        MapTransform.__init__(self, keys, allow_missing_keys)
        self.trans = TorchVision(name, *args, **kwargs)
Esempio n. 24
0
    def __init__(
        self,
        keys: KeysCollection,
        spatial_size: Sequence[int],
        rand_size: Sequence[int],
        pad: int = 0,
        field_mode: Union[
            InterpolateModeType,
            Sequence[InterpolateModeType]] = InterpolateMode.AREA,
        align_corners: Optional[bool] = None,
        prob: float = 0.1,
        def_range: Union[Sequence[float], float] = 1.0,
        grid_dtype=torch.float32,
        grid_mode: Union[
            GridSampleModeType,
            Sequence[GridSampleModeType]] = GridSampleMode.NEAREST,
        grid_padding_mode: Union[GridSamplePadMode,
                                 str] = GridSamplePadMode.BORDER,
        grid_align_corners: Optional[bool] = False,
        device: Optional[torch.device] = None,
    ):
        RandomizableTransform.__init__(self, prob)
        MapTransform.__init__(self, keys)

        self.field_mode = ensure_tuple_rep(field_mode, len(self.keys))
        self.grid_mode = ensure_tuple_rep(grid_mode, len(self.keys))

        self.trans = RandSmoothDeform(
            rand_size=rand_size,
            spatial_size=spatial_size,
            pad=pad,
            field_mode=self.field_mode[0],
            align_corners=align_corners,
            prob=1.0,
            def_range=def_range,
            grid_dtype=grid_dtype,
            grid_mode=self.grid_mode[0],
            grid_padding_mode=grid_padding_mode,
            grid_align_corners=grid_align_corners,
            device=device,
        )
Esempio n. 25
0
 def __init__(
     self,
     keys: KeysCollection,
     sigma1_x: Tuple[float, float] = (0.5, 1.0),
     sigma1_y: Tuple[float, float] = (0.5, 1.0),
     sigma1_z: Tuple[float, float] = (0.5, 1.0),
     sigma2_x: Union[Tuple[float, float], float] = 0.5,
     sigma2_y: Union[Tuple[float, float], float] = 0.5,
     sigma2_z: Union[Tuple[float, float], float] = 0.5,
     alpha: Tuple[float, float] = (10.0, 30.0),
     approx: str = "erf",
     prob: float = 0.1,
 ):
     MapTransform.__init__(self, keys)
     RandomizableTransform.__init__(self, prob)
     self.sigma1_x = sigma1_x
     self.sigma1_y = sigma1_y
     self.sigma1_z = sigma1_z
     self.sigma2_x = sigma2_x
     self.sigma2_y = sigma2_y
     self.sigma2_z = sigma2_z
     self.alpha = alpha
     self.approx = approx
Esempio n. 26
0
 def __init__(self, keys: KeysCollection, meta_key: str, allow_missing_keys: bool = False) -> None:
     MapTransform.__init__(self, keys, allow_missing_keys)
     self.meta_key = meta_key