Apply a user-defined lambda as a transform. For example: .. code-block:: python :emphasize-lines: 2 image = np.ones((10, 2, 2)) lambd = Lambda(func=lambda x: x[:4, :, :]) print(lambd(image).shape) (4, 2, 2) Args: func: Lambda/funct
| 781 | |
| 782 | |
| 783 | class Lambda(InvertibleTransform): |
| 784 | """ |
| 785 | Apply a user-defined lambda as a transform. |
| 786 | |
| 787 | For example: |
| 788 | |
| 789 | .. code-block:: python |
| 790 | :emphasize-lines: 2 |
| 791 | |
| 792 | image = np.ones((10, 2, 2)) |
| 793 | lambd = Lambda(func=lambda x: x[:4, :, :]) |
| 794 | print(lambd(image).shape) |
| 795 | (4, 2, 2) |
| 796 | |
| 797 | Args: |
| 798 | func: Lambda/function to be applied. |
| 799 | inv_func: Lambda/function of inverse operation, default to `lambda x: x`. |
| 800 | track_meta: If `False`, then standard data objects will be returned (e.g., torch.Tensor` and `np.ndarray`) |
| 801 | as opposed to MONAI's enhanced objects. By default, this is `True`. |
| 802 | |
| 803 | Raises: |
| 804 | TypeError: When ``func`` is not an ``Optional[Callable]``. |
| 805 | |
| 806 | """ |
| 807 | |
| 808 | backend = [TransformBackends.TORCH, TransformBackends.NUMPY] |
| 809 | |
| 810 | def __init__( |
| 811 | self, func: Callable | None = None, inv_func: Callable = no_collation, track_meta: bool = True |
| 812 | ) -> None: |
| 813 | if func is not None and not callable(func): |
| 814 | raise TypeError(f"func must be None or callable but is {type(func).__name__}.") |
| 815 | self.func = func |
| 816 | self.inv_func = inv_func |
| 817 | self.track_meta = track_meta |
| 818 | |
| 819 | def __call__(self, img: NdarrayOrTensor, func: Callable | None = None): |
| 820 | """ |
| 821 | Apply `self.func` to `img`. |
| 822 | |
| 823 | Args: |
| 824 | func: Lambda/function to be applied. Defaults to `self.func`. |
| 825 | |
| 826 | Raises: |
| 827 | TypeError: When ``func`` is not an ``Optional[Callable]``. |
| 828 | |
| 829 | """ |
| 830 | fn = func if func is not None else self.func |
| 831 | if not callable(fn): |
| 832 | raise TypeError(f"func must be None or callable but is {type(fn).__name__}.") |
| 833 | out = fn(img) |
| 834 | # convert to MetaTensor if necessary |
| 835 | if isinstance(out, (np.ndarray, torch.Tensor)) and not isinstance(out, MetaTensor) and self.track_meta: |
| 836 | out = MetaTensor(out) |
| 837 | if isinstance(out, MetaTensor): |
| 838 | self.push_transform(out) |
| 839 | return out |
| 840 |
no outgoing calls
searching dependent graphs…