lambda_module.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Any, Callable
  18. from kornia.core import Module, Tensor
  19. class Lambda(Module):
  20. """Applies user-defined lambda as a transform.
  21. Args:
  22. func: Callable function.
  23. Returns:
  24. The output of the user-defined lambda.
  25. Example:
  26. >>> import kornia
  27. >>> x = torch.rand(1, 3, 5, 5)
  28. >>> f = Lambda(lambda x: kornia.color.rgb_to_grayscale(x))
  29. >>> f(x).shape
  30. torch.Size([1, 1, 5, 5])
  31. """
  32. def __init__(self, func: Callable[..., Tensor]) -> None:
  33. super().__init__()
  34. if not callable(func):
  35. raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}")
  36. self.func = func
  37. def forward(self, img: Tensor, *args: Any, **kwargs: Any) -> Tensor:
  38. return self.func(img, *args, **kwargs)