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

Class Lambda

monai/transforms/utility/array.py:783–844  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

781
782
783class 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

Callers 11

__init__Method · 0.90
gaussian_occlusionMethod · 0.90
test_set_dataMethod · 0.90
test_set_dataMethod · 0.90
test_shapeMethod · 0.90
test_set_dataMethod · 0.90
test_correctMethod · 0.90
test_lambda_identityMethod · 0.90
test_lambda_slicingMethod · 0.90

Calls

no outgoing calls

Tested by 9

test_set_dataMethod · 0.72
test_set_dataMethod · 0.72
test_shapeMethod · 0.72
test_set_dataMethod · 0.72
test_correctMethod · 0.72
test_lambda_identityMethod · 0.72
test_lambda_slicingMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…