Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

stablish Torch core (#3432)

Edgar Riba9e521cac016f
diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md
deleted file mode 100644
index 9ec91541c..000000000
--- a/.github/pull-request-template.md
+++ /dev/null
@@ -1,26 +0,0 @@
-#### Changes
-<!-- Please include a summary of the change and which issue is fixed. -->
-<!-- Please also include relevant motivation and context. -->
-<!-- List any dependencies that are required for this change. -->
-
-Fixes # (issue)
-
-
-#### Type of change
-<!-- Please delete options that are not relevant. -->
-- [ ] πŸ“š Documentation Update
-- [ ] πŸ§ͺ Tests Cases
-- [ ] 🐞 Bug fix (non-breaking change which fixes an issue)
-- [ ] πŸ”¬ New feature (non-breaking change which adds functionality)
-- [ ] 🚨 Breaking change (fix or feature that would cause existing functionality to not work as expected)
-- [ ] πŸ“ This change requires a documentation update
-
-
-#### Checklist
-
-- [ ] My code follows the style guidelines of this project
-- [ ] I have performed a self-review of my own code
-- [ ] I have commented my code, particularly in hard-to-understand areas
-- [ ] I have made corresponding changes to the documentation
-- [ ] My changes generate no new warnings
-- [ ] Did you update CHANGELOG in case of a major change?
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 000000000..fd2dc3360
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,37 @@
+## πŸ“ Description
+**Fixes/Relates to:** # (issue number)
+
+---
+
+## πŸ› οΈ Changes Made
+- [ ] Item 1
+- [ ] Item 2
+
+---
+
+## πŸ§ͺ How Was This Tested?
+- [ ] **Unit Tests:** (List new/updated tests)
+- [ ] **Manual Verification:** (Describe the steps you took)
+- [ ] **Performance/Edge Cases:** (How does this handle nulls, large data, etc.?)
+
+---
+
+## πŸ•΅οΈ AI Usage Disclosure
+*Check one of the following:*
+- [ ] 🟒 **No AI used.**
+- [ ] 🟑 **AI-assisted:** I used AI for boilerplate/refactoring but have manually reviewed and tested every line.
+- [ ] πŸ”΄ **AI-generated:** (Note: These PRs may be subject to stricter scrutiny or immediate closure if the logic is not explained).
+
+---
+
+## 🚦 Checklist
+- [ ] I have performed a **self-review** of my code (no "ghost" variables or hallucinations).
+- [ ] My code follows the existing style guidelines of this project.
+- [ ] I have commented my code, particularly in hard-to-understand areas.
+- [ ] I have added tests that prove my fix is effective or that my feature works.
+- [ ] (Optional) I have attached screenshots/recordings for UI changes.
+
+---
+
+## πŸ’­ Additional Context
+Add any other context or screenshots about the pull request here.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ed8fde677..9eb0d06cb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -4,8 +4,9 @@ Welcome! This guide will help you contribute to Kornia.
## Policies and Guidelines
+- **AI-Assisted Development**: AI tools (e.g., GitHub Copilot, ChatGPT, Cursor) may be used to assist with coding, but all contributions must be authored and reviewed by humans. PRs that are fully AI-generated without human understanding, oversight, or ability to explain the code will be rejected. Contributors must understand all code they submit and be able to respond to review feedback.
+ - **Automated Detection**: Automated review systems (including GitHub Copilot) analyze PRs for AI-generated content. PRs flagged as having excessive AI-generated content without sufficient human authorship will be rejected. Ensure your contributions reflect genuine human understanding and modification of any AI-assisted code.
- **15-Day Rule**: PRs with no activity for 15+ days will be automatically closed.
-- **Quality Control**: AI-generated PRs without human oversight will be flagged. If a PR doesn't improve after review iterations, it will be closed.
- **Transparency**: All discussions must be public.
We're all volunteers. These policies help us focus on high-impact work.
@@ -143,7 +144,7 @@ We're all volunteers. These policies help us focus on high-impact work.
5. **Develop and test:**
**Requirements:**
- - No AI-generated code without human oversight
+ - AI tools may assist with coding, but you must understand and review all code before submission
- **All local tests must pass before submitting PRs**
Create test cases for your code. Run tests with:
@@ -249,21 +250,32 @@ We're all volunteers. These policies help us focus on high-impact work.
- **Type hints** (Python >= 3.11):
- Use typing when it improves readability
- - Import from `kornia.core`, e.g. `from kornia.core import Tensor`
+ - **Use `torch.Tensor` directly** for type hints (preferred) or import from `kornia.core` for backward compatibility
+ - Use `torch.nn.Module` directly for module classes (preferred) or import from `kornia.core` for backward compatibility
- For non-JIT modules, use `from __future__ import annotations`
- **Always** type function inputs and outputs:
- Run type checking with `pixi run typecheck` (uses `ty`)
```python
from __future__ import annotations
- from kornia.core import Tensor
+ import torch
def homography_warp(
- patch_src: Tensor,
- dst_homo_src: Tensor,
+ patch_src: torch.Tensor,
+ dst_homo_src: torch.Tensor,
dsize: tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros'
- ) -> Tensor:
+ ) -> torch.Tensor:
+ ```
+
+ For module classes:
+ ```python
+ from __future__ import annotations
+ import torch.nn as nn
+
+ class MyModule(nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x
```
- **Code style:**
@@ -285,7 +297,7 @@ We're all volunteers. These policies help us focus on high-impact work.
- Link PR to an issue (use "Closes #123" or "Fixes #123")
- Pass all local tests before submission
- 15-Day Rule: Inactive PRs (>15 days) will be closed
-- Quality: AI-generated PRs without oversight will be flagged/closed
+- AI-Assisted Development: AI tools may assist, but PRs must be human-authored and reviewed. Fully AI-generated PRs without human understanding will be rejected. Automated systems (including GitHub Copilot) detect excessive AI-generated content and may reject PRs.
- Transparency: Keep discussions public
**Note:** Tickets may be closed during cleanup. Feel free to reopen if you plan to finish the work.
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index ed33d96a0..89e9f3e71 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -29,10 +29,10 @@ import matplotlib.pyplot as plt
import numpy as np
import requests
import torch
+import torch.nn.functional as F
from kornia_moons.feature import visualize_LAF
import kornia as K
-from kornia.core import Tensor
mpl.use("Agg")
@@ -66,14 +66,14 @@ def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **r
return img_t
-def transparent_pad(src: Tensor, shape: tuple[int, int]) -> Tensor:
+def transparent_pad(src: torch.Tensor, shape: tuple[int, int]) -> torch.Tensor:
"""Apply a transparent pad to src (centerized) to match with shape (h, w)"""
w_pad = abs(int(src.shape[-1] - shape[-1]) // 2)
h_pad = abs(int(src.shape[-2] - shape[-2]) // 2)
- return torch.nn.functional.pad(K.color.rgb_to_rgba(src, 1.0), (w_pad, w_pad, h_pad, h_pad), "constant", 0.0)
+ return F.pad(K.color.rgb_to_rgba(src, 1.0), (w_pad, w_pad, h_pad, h_pad), "constant", 0.0)
-def draw_bbox_kpts(imgs, bboxes, keypoints):
+def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Tensor) -> torch.Tensor:
rectangle = torch.zeros(imgs.shape[0], imgs.shape[1], 4)
rectangle[..., 0] = bboxes[..., 0] # x1
rectangle[..., 1] = bboxes[..., 1] # y1
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 18360b5a4..b9e1a5ca9 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -17,11 +17,11 @@
from typing import Any, Dict, Optional
+import torch
from torch import float16, float32, float64
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
-from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.utils import eye_like, is_autocast_enabled
@@ -45,13 +45,15 @@ class AugmentationBase2D(_AugmentationBase):
"""
- def validate_tensor(self, input: Tensor) -> None:
- """Check if the input tensor is formatted as expected."""
+ def validate_tensor(self, input: torch.Tensor) -> None:
+ """Check if the input torch.tensor is formatted as expected."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
if len(input.shape) != 4:
raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")
- def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
+ def transform_tensor(
+ self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True
+ ) -> torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
@@ -78,20 +80,24 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
"""
- _transform_matrix: Optional[Tensor]
+ _transform_matrix: Optional[torch.Tensor]
@property
- def transform_matrix(self) -> Optional[Tensor]:
+ def transform_matrix(self) -> Optional[torch.Tensor]:
return self._transform_matrix
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return 3x3 identity matrix."""
return eye_like(3, input)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def generate_transformation_matrix(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
"""Generate transformation matrices with the given input and param settings."""
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
@@ -114,33 +120,53 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
return trans_matrix
def inverse_inputs(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def inverse_masks(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def inverse_boxes(
- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
raise NotImplementedError
def inverse_keypoints(
- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Keypoints,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
raise NotImplementedError
def inverse_classes(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def apply_func(
- self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, in_tensor: torch.Tensor, params: Dict[str, torch.Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if flags is None:
flags = self.flags
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 2dd241e2e..4b44d4152 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -17,16 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
-from kornia.core import Tensor, as_tensor
-from kornia.geometry.conversions import deg2rad
from kornia.geometry.transform import get_affine_matrix2d, warp_affine
class RandomAffine(GeometricAugmentationBase2D):
- r"""Apply a random 2D affine transformation to a tensor image.
+ r"""Apply a random 2D affine transformation to a torch.tensor image.
.. image:: _static/img/RandomAffine.png
@@ -50,9 +50,9 @@ class RandomAffine(GeometricAugmentationBase2D):
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
resample: resample mode from "nearest" (0) or "bilinear" (1).
- padding_mode: padding mode from "zeros" (0), "border" (1), "reflection" (2) or "fill" (3).
+ padding_mode: padding mode from "torch.zeros" (0), "border" (1), "reflection" (2) or "fill" (3).
fill_value: the value to be filled in the padding area when padding_mode="fill".
- Can be a float, int, or a tensor of shape (C) or (1).
+ Can be a float, int, or a torch.tensor of shape (C) or (1).
same_on_batch: apply the same transformation across the batch.
align_corners: interpolation flag.
p: probability of applying the transformation.
@@ -96,23 +96,23 @@ class RandomAffine(GeometricAugmentationBase2D):
def __init__(
self,
- degrees: Union[Tensor, float, Tuple[float, float]],
- translate: Optional[Union[Tensor, Tuple[float, float]]] = None,
- scale: Optional[Union[Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
- shear: Optional[Union[Tensor, float, Tuple[float, float]]] = None,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False,
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
- fill_value: Optional[Union[float, int, Tensor]] = None, # Updated type hint
+ fill_value: Optional[Union[float, int, torch.Tensor]] = None, # Updated type hint
p: float = 0.5,
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator: rg.AffineGenerator = rg.AffineGenerator(degrees, translate, scale, shear)
- if fill_value is not None and not isinstance(fill_value, Tensor):
- fill_value = as_tensor(fill_value)
+ if fill_value is not None and not isinstance(fill_value, torch.Tensor):
+ fill_value = torch.as_tensor(fill_value)
self.flags = {
"resample": Resample.get(resample),
@@ -121,22 +121,28 @@ class RandomAffine(GeometricAugmentationBase2D):
"fill_value": fill_value,
}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return get_affine_matrix2d(
- as_tensor(params["translations"], device=input.device, dtype=input.dtype),
- as_tensor(params["center"], device=input.device, dtype=input.dtype),
- as_tensor(params["scale"], device=input.device, dtype=input.dtype),
- as_tensor(params["angle"], device=input.device, dtype=input.dtype),
- deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
- deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
+ torch.as_tensor(params["translations"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["scale"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["angle"], device=input.device, dtype=input.dtype),
+ torch.deg2rad(torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
+ torch.deg2rad(torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, _, height, width = input.shape
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -150,16 +156,16 @@ class RandomAffine(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 807c46eca..d8abcb2a6 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor, as_tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.utils.helpers import _torch_inverse_cast
@@ -41,21 +42,24 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""By default, the exact transformation as ``apply_transform`` will be used."""
raise NotImplementedError
- def compute_inverse_transformation(self, transform: Tensor) -> Tensor:
+ def compute_inverse_transformation(self, transform: torch.Tensor) -> torch.Tensor:
"""Compute the inverse transform of given transformation matrices."""
return _torch_inverse_cast(transform)
def get_transformation_matrix(
- self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ flags: Optional[Dict[str, Any]] = None,
+ ) -> torch.Tensor:
"""Obtain transformation matrices.
Return the current transformation matrix if existed. Generate a new one, otherwise.
@@ -68,17 +72,25 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
transform = self.generate_transformation_matrix(input, params, flags)
else:
transform = self.transform_matrix
- return as_tensor(transform, device=input.device, dtype=input.dtype)
+ return torch.as_tensor(transform, device=input.device, dtype=input.dtype)
def apply_non_transform_mask(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process masks corresponding to the inputs that are no transformation applied."""
return input
def apply_transform_mask(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process masks corresponding to the inputs that are transformed.
Note:
@@ -95,13 +107,21 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
return output
def apply_non_transform_box(
- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process boxes corresponding to the inputs that are no transformation applied."""
return input
def apply_transform_box(
- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process boxes corresponding to the inputs that are transformed."""
if transform is None:
@@ -112,13 +132,21 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
return input.transform_boxes_(transform)
def apply_non_transform_keypoint(
- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Keypoints,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
"""Process keypoints corresponding to the inputs that are no transformation applied."""
return input
def apply_transform_keypoint(
- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Keypoints,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
"""Process keypoints corresponding to the inputs that are transformed."""
if transform is None:
@@ -129,25 +157,33 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
return input.transform_keypoints_(transform)
def apply_non_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process class tags corresponding to the inputs that are no transformation applied."""
return input
def apply_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process class tags corresponding to the inputs that are transformed."""
return input
def inverse_inputs(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
batch_prob = params["batch_prob"]
@@ -180,12 +216,12 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
def inverse_masks(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
resample_method: Optional[Resample] = None
if "resample" in flags:
resample_method = flags["resample"]
@@ -198,9 +234,9 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
def inverse_boxes(
self,
input: Boxes,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Boxes:
output = input.clone()
@@ -208,7 +244,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("`transform` has to be a tensor. Got None.")
+ raise RuntimeError("`transform` has to be a torch.tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -228,15 +264,15 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
def inverse_keypoints(
self,
input: Keypoints,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Keypoints:
"""Inverse the transformation on keypoints.
Args:
- input: input keypoints tensor or object.
+ input: input keypoints torch.tensor or object.
params: the corresponding parameters for an operation.
flags: static parameters.
transform: the inverse transformation matrix
@@ -248,7 +284,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("`transform` has to be a tensor. Got None.")
+ raise RuntimeError("`transform` has to be a torch.tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -267,19 +303,21 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
def inverse_classes(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
return input
- def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
+ def inverse(
+ self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, **kwargs: Any
+ ) -> torch.Tensor:
"""Perform inverse operations.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: the corresponding parameters for an operation.
If None, a new parameter suite will be generated.
**kwargs: key-value pairs to override the parameters and flags.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index cd80a46c6..38da2e5e8 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
class CenterCrop(GeometricAugmentationBase2D):
- r"""Crop a given image tensor at the center.
+ r"""Crop a given image torch.tensor at the center.
.. image:: _static/img/CenterCrop.png
@@ -38,7 +39,7 @@ class CenterCrop(GeometricAugmentationBase2D):
p: probability of applying the transformation for the whole batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -88,7 +89,7 @@ class CenterCrop(GeometricAugmentationBase2D):
cropping_mode: str = "slice",
) -> None:
# same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1])
@@ -105,25 +106,36 @@ class CenterCrop(GeometricAugmentationBase2D):
"padding_mode": "zeros",
}
- def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
- transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
- input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
+ input,
+ transform[:, :2, :],
+ self.size,
+ flags["resample"].name.lower(),
+ "zeros",
+ flags["align_corners"],
)
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
return crop_by_indices(input, params["src"], flags["size"])
@@ -131,19 +143,19 @@ class CenterCrop(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
if size is None:
size = self.size
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
transform[:, :2, :],
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index cb477dd9c..0aa0f4dec 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -18,18 +18,18 @@
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
+import torch.nn.functional as F
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor, pad, tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
class RandomCrop(GeometricAugmentationBase2D):
- r"""Crop random patches of a tensor image on a given size.
+ r"""Crop random patches of a torch.tensor image on a given size.
.. image:: _static/img/RandomCrop.png
@@ -38,10 +38,10 @@ class RandomCrop(GeometricAugmentationBase2D):
Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
padding: Optional padding on each border
of the image. Default is None, i.e no padding. If a sequence of length
- 4 is provided, it is used to pad left, top, right, bottom borders
+ 4 is provided, it is used to F.pad left, top, right, bottom borders
respectively. If a sequence of length 2 is provided, it is used to
- pad left/right, top/bottom borders, respectively.
- pad_if_needed: It will pad the image if smaller than the
+ F.pad left/right, top/bottom borders, respectively.
+ pad_if_needed: It will F.pad the image if smaller than the
desired size to avoid raising an exception. Since cropping is done
after padding, the padding seems to be done at a random offset.
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
@@ -54,7 +54,7 @@ class RandomCrop(GeometricAugmentationBase2D):
p: probability of applying the transformation for the whole batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -64,9 +64,9 @@ class RandomCrop(GeometricAugmentationBase2D):
- Output: :math:`(B, C, out_h, out_w)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -104,7 +104,7 @@ class RandomCrop(GeometricAugmentationBase2D):
keepdim: bool = False,
cropping_mode: str = "slice",
) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.CropGenerator(size)
self.flags = {
@@ -135,12 +135,12 @@ class RandomCrop(GeometricAugmentationBase2D):
if flags["pad_if_needed"]:
needed_padding: Tuple[int, int] = (flags["size"][0] - shape[-2], flags["size"][1] - shape[-1]) # HW
- # If crop width is larger than input width pad equally left and right
+ # If crop width is larger than input width F.pad equally left and right
if needed_padding[1] > 0:
# Only use the extra padding if actually needed after possible fixed padding
padding[0] = max(needed_padding[1], padding[0])
padding[1] = max(needed_padding[1], padding[1])
- # If crop height is larger than input height pad equally top and bottom
+ # If crop height is larger than input height F.pad equally top and bottom
if needed_padding[0] > 0:
# Only use the extra padding if actually needed after possible fixed padding
padding[2] = max(needed_padding[0], padding[2])
@@ -148,22 +148,24 @@ class RandomCrop(GeometricAugmentationBase2D):
return padding
def precrop_padding(
- self, input: Tensor, padding: Optional[List[int]] = None, flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, padding: Optional[List[int]] = None, flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
flags = self.flags if flags is None else flags
if padding is None:
padding = self.compute_padding(input.shape)
if any(padding):
- input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
return input
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
src = params["src"].to(input)
dst = params["dst"].to(input)
- transform: Tensor = get_perspective_transform(src, dst)
+ transform: torch.Tensor = get_perspective_transform(src, dst)
# Fast scaling correction when output exceeds input and padding disabled
if not flags.get("pad_if_needed", False):
@@ -177,36 +179,48 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def apply_transform_keypoint(
- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Keypoints,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
"""Process keypoints corresponding to the inputs that are no transformation applied."""
- # For pad the keypoints properly.
+ # For F.pad the keypoints properly.
padding_size = params["padding_size"].to(device=input.device)
input = input.pad(padding_size)
return super().apply_transform_keypoint(input=input, params=params, flags=flags, transform=transform)
def apply_transform_box(
- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process keypoints corresponding to the inputs that are no transformation applied."""
- # For pad the boxes properly.
+ # For F.pad the boxes properly.
padding_size = params["padding_size"]
input = input.pad(padding_size)
return super().apply_transform_box(input=input, params=params, flags=flags, transform=transform)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
padding_size: Optional[List[int]] = None
- if "padding_size" in params and isinstance(params["padding_size"], Tensor):
+ if "padding_size" in params and isinstance(params["padding_size"], torch.Tensor):
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
input = self.precrop_padding(input, padding_size, flags)
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
- # Fit the arg to F.pad
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
+ # Fit the arg to F.F.pad
if flags["padding_mode"] == "constant":
padding_mode = "zeros"
elif flags["padding_mode"] == "replicate":
@@ -230,20 +244,20 @@ class RandomCrop(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
if size is None:
raise RuntimeError("`size` has to be a tuple. Got None.")
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
- # Fit the arg to F.pad
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
+ # Fit the arg to F.F.pad
if flags["padding_mode"] == "constant":
padding_mode = "zeros"
elif flags["padding_mode"] == "replicate":
@@ -263,12 +277,12 @@ class RandomCrop(GeometricAugmentationBase2D):
def inverse_inputs(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
@@ -283,9 +297,9 @@ class RandomCrop(GeometricAugmentationBase2D):
def inverse_boxes(
self,
input: Boxes,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Boxes:
if flags["cropping_mode"] != "resample":
@@ -301,9 +315,9 @@ class RandomCrop(GeometricAugmentationBase2D):
def inverse_keypoints(
self,
input: Keypoints,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Keypoints:
if flags["cropping_mode"] != "resample":
@@ -317,7 +331,7 @@ class RandomCrop(GeometricAugmentationBase2D):
return output.unpad(params["padding_size"].to(device=input.device))
# Override parameters for precrop
- def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
input_pad = self.compute_padding(batch_shape)
batch_shape_new = torch.Size(
(
@@ -326,7 +340,7 @@ class RandomCrop(GeometricAugmentationBase2D):
batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
)
)
- padding_size = tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
+ padding_size = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
_params = super().forward_parameters(batch_shape_new)
_params.update({"padding_size": padding_size})
return _params
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index faba55bfc..549dd9584 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -21,13 +21,12 @@ import torch
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import elastic_transform2d
class RandomElasticTransform(AugmentationBase2D):
- r"""Add random elastic transformation to a tensor image.
+ r"""Add random elastic transformation to a torch.tensor image.
.. image:: _static/img/RandomElasticTransform.png
@@ -39,7 +38,7 @@ class RandomElasticTransform(AugmentationBase2D):
in the y and x directions, respectively.
align_corners: Interpolation flag used by `grid_sample`.
resample: Interpolation mode used by `grid_sample`. Either 'nearest' (0) or 'bilinear' (1).
- padding_mode: The padding used by ```grid_sample```. Either 'zeros', 'border' or 'refection'.
+ padding_mode: The padding used by ```grid_sample```. Either 'torch.zeros', 'border' or 'refection'.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -86,7 +85,7 @@ class RandomElasticTransform(AugmentationBase2D):
"padding_mode": padding_mode,
}
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
B, _, H, W = shape
if self.same_on_batch:
noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W)
@@ -95,8 +94,12 @@ class RandomElasticTransform(AugmentationBase2D):
return {"noise": noise * 2 - 1}
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return elastic_transform2d(
input,
params["noise"].to(input),
@@ -109,25 +112,41 @@ class RandomElasticTransform(AugmentationBase2D):
)
def apply_non_transform_mask(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return input
def apply_transform_mask(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process masks corresponding to the inputs that are transformed."""
return self.apply_transform(input, params=params, flags=flags, transform=transform)
def apply_transform_box(
- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process masks corresponding to the inputs that are transformed."""
# We assume that boxes may not be affected too much by the deformation.
return input
def apply_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process class tags corresponding to the inputs that are transformed."""
return input
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index 017392e37..31ab715a5 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import AugmentationBase2D
-from kornia.core import Tensor
from kornia.geometry.transform import remap
from kornia.utils import create_meshgrid
@@ -58,9 +59,9 @@ class RandomFisheye(AugmentationBase2D):
def __init__(
self,
- center_x: Tensor,
- center_y: Tensor,
- gamma: Tensor,
+ center_x: torch.Tensor,
+ center_y: torch.Tensor,
+ gamma: torch.Tensor,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
@@ -75,16 +76,20 @@ class RandomFisheye(AugmentationBase2D):
(gamma[:, None], "gamma", None, None),
)
- def _check_tensor(self, data: Tensor) -> None:
- if not isinstance(data, Tensor):
- raise TypeError(f"Invalid input type. Expected Tensor - got: {type(data)}")
+ def _check_tensor(self, data: torch.Tensor) -> None:
+ if not isinstance(data, torch.Tensor):
+ raise TypeError(f"Invalid input type. Expected torch.Tensor - got: {type(data)}")
if len(data.shape) != 1 and data.shape[0] != 2:
- raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.")
+ raise ValueError(f"torch.Tensor must be of shape (2,). Got: {data.shape}.")
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
# create the initial sampling fields
B, _, H, W = input.shape
grid = create_meshgrid(H, W, normalized_coordinates=True)
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 8174cb46e..fc4ee6ea2 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -17,22 +17,24 @@
from typing import Any, Dict, Optional, Tuple
-from torch import Tensor
+import torch
+# from torch import Tensor (use torch.Tensor instead)
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
-from kornia.core import as_tensor, tensor
from kornia.geometry.transform import hflip
class RandomHorizontalFlip(GeometricAugmentationBase2D):
- r"""Apply a random horizontal flip to a tensor image or a batch of tensor images with a given probability.
+ r"""Apply a random horizontal flip to a torch.tensor image or a batch of torch.tensor images.
+
+ The flip is applied with a given probability.
.. image:: _static/img/RandomHorizontalFlip.png
- Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
+ Input should be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
the corresponding transformation matrix that has been applied to them. In this case the module
- will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the
+ will Horizontally flip the tensors and torch.cat the corresponding transformation matrix to the
previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
Args:
@@ -71,29 +73,37 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
"""
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
w: int = int(params["forward_input_shape"][-1])
- flip_mat: Tensor = tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.expand(input.shape[0], 3, 3)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return hflip(input)
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 07afbc34b..02baf6f73 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor, as_tensor
from kornia.geometry.transform import get_perspective_transform, warp_perspective
class RandomPerspective(GeometricAugmentationBase2D):
- r"""Apply a random perspective transformation to an image tensor with a given probability.
+ r"""Apply a random perspective transformation to an image torch.tensor with a given probability.
.. image:: _static/img/RandomPerspective.png
@@ -75,7 +76,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
def __init__(
self,
- distortion_scale: Union[Tensor, float] = 0.5,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False,
@@ -88,15 +89,21 @@ class RandomPerspective(GeometricAugmentationBase2D):
self.flags: Dict[str, Any] = {"align_corners": align_corners, "resample": Resample.get(resample)}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, _, height, width = input.shape
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return warp_perspective(
input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
@@ -104,16 +111,16 @@ class RandomPerspective(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 4eb4b22b9..e2035be01 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -22,7 +22,6 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
from kornia.utils import eye_like
@@ -62,19 +61,25 @@ class Resize(GeometricAugmentationBase2D):
"antialias": antialias,
}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
if params["output_size"] == input.shape[-2:]:
return eye_like(3, input)
- transform: Tensor = torch.as_tensor(
+ transform: torch.Tensor = torch.as_tensor(
get_perspective_transform(params["src"], params["dst"]), dtype=input.dtype, device=input.device
)
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
B, C, _, _ = input.shape
out_size = tuple(params["output_size"][0].tolist())
out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype)
@@ -97,16 +102,16 @@ class Resize(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
if not isinstance(size, tuple):
raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index f5001cdd5..0c49faa06 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
class RandomResizedCrop(GeometricAugmentationBase2D):
- r"""Crop random patches in an image tensor and resizes to a given size.
+ r"""Crop random patches in an image torch.tensor and resizes to a given size.
.. image:: _static/img/RandomResizedCrop.png
@@ -40,7 +41,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
p: probability of the augmentation been applied.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -50,9 +51,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
- Output: :math:`(B, C, out_h, out_w)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Example:
>>> rng = torch.manual_seed(0)
@@ -81,8 +82,8 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
def __init__(
self,
size: Tuple[int, int],
- scale: Union[Tensor, Tuple[float, float]] = (0.08, 1.0),
- ratio: Union[Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.08, 1.0),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = True,
@@ -90,7 +91,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
keepdim: bool = False,
cropping_mode: str = "slice",
) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens all the time.
+ # Since PyTorch does not support ragged torch.tensor. So cropping function happens all the time.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.ResizedCropGenerator(size, scale, ratio)
self.flags = {
@@ -101,19 +102,25 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
"padding_mode": "zeros",
}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
- transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
@@ -135,11 +142,11 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
@@ -147,8 +154,8 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
if not isinstance(size, tuple):
raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 4cabe6319..a5d778783 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -17,17 +17,18 @@
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor, as_tensor
from kornia.geometry.transform import affine
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
from kornia.utils.misc import eye_like
class RandomRotation(GeometricAugmentationBase2D):
- r"""Apply a random rotation to a tensor image or a batch of tensor images given an amount of degrees.
+ r"""Apply a random rotation to a torch.tensor image or a batch of torch.tensor images given an amount of degrees.
.. image:: _static/img/RandomRotation.png
@@ -79,7 +80,7 @@ class RandomRotation(GeometricAugmentationBase2D):
def __init__(
self,
- degrees: Union[Tensor, float, Tuple[float, float], List[float]],
+ degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = True,
@@ -91,47 +92,53 @@ class RandomRotation(GeometricAugmentationBase2D):
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
# TODO: Update to use `get_rotation_matrix2d`
- angles: Tensor = params["degrees"].to(input)
+ angles: torch.Tensor = params["degrees"].to(input)
- center: Tensor = _compute_tensor_center(input)
- rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
+ center: torch.Tensor = _compute_tensor_center(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
# rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
- trans_mat: Tensor = eye_like(3, input, shared_memory=False)
+ trans_mat: torch.Tensor = eye_like(3, input, shared_memory=False)
trans_mat[:, 0] = rotation_mat[:, 0]
trans_mat[:, 1] = rotation_mat[:, 1]
return trans_mat
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
class RandomRotation90(GeometricAugmentationBase2D):
- r"""Apply a random 90 * n degree rotation to a tensor image or a batch of tensor images.
+ r"""Apply a random 90 * n degree rotation to a torch.tensor image or a batch of torch.tensor images.
Args:
times: the range of n times 90 degree rotation needs to be applied.
@@ -191,40 +198,46 @@ class RandomRotation90(GeometricAugmentationBase2D):
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
- def compute_transformation(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: dict[str, torch.Tensor], flags: dict[str, Any]
+ ) -> torch.Tensor:
# TODO: Update to use `get_rotation_matrix2d`
- angles: Tensor = 90.0 * params["times"].round().to(input)
+ angles: torch.Tensor = 90.0 * params["times"].round().to(input)
- center: Tensor = _compute_tensor_center(input)
- rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
+ center: torch.Tensor = _compute_tensor_center(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
# rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
- trans_mat: Tensor = eye_like(3, input, shared_memory=False)
+ trans_mat: torch.Tensor = eye_like(3, input, shared_memory=False)
trans_mat[:, 0] = rotation_mat[:, 0]
trans_mat[:, 1] = rotation_mat[:, 1]
return trans_mat
def apply_transform(
- self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ self,
+ input: torch.Tensor,
+ params: dict[str, torch.Tensor],
+ flags: dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 39e992b9f..6a1333013 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -17,16 +17,18 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
-from kornia.core import Tensor, as_tensor
-from kornia.geometry.conversions import deg2rad
+
+# from kornia.geometry.conversions import deg2rad (use torch.deg2rad instead)
from kornia.geometry.transform import get_shear_matrix2d, warp_affine
class RandomShear(GeometricAugmentationBase2D):
- r"""Apply a random 2D shear transformation to a tensor image.
+ r"""Apply a random 2D shear transformation to a torch.tensor image.
The transformation is computed so that the image center is kept invariant.
@@ -37,7 +39,7 @@ class RandomShear(GeometricAugmentationBase2D):
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
resample: resample mode from "nearest" (0) or "bilinear" (1).
- padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2).
+ padding_mode: padding mode from "torch.zeros" (0), "border" (1) or "reflection" (2).
same_on_batch: apply the same transformation across the batch.
align_corners: interpolation flag.
p: probability of applying the transformation.
@@ -77,7 +79,7 @@ class RandomShear(GeometricAugmentationBase2D):
def __init__(
self,
- shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],
+ shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False,
@@ -93,19 +95,25 @@ class RandomShear(GeometricAugmentationBase2D):
"align_corners": align_corners,
}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return get_shear_matrix2d(
- as_tensor(params["center"], device=input.device, dtype=input.dtype),
- deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
- deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
+ torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ torch.deg2rad(torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
+ torch.deg2rad(torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, _, height, width = input.shape
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -118,16 +126,16 @@ class RandomShear(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index 19ff5f33c..87acc3a25 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import SamplePadding
-from kornia.core import Tensor, tensor
from kornia.geometry.transform import get_tps_transform, warp_image_tps
@@ -72,15 +71,19 @@ class RandomThinPlateSpline(AugmentationBase2D):
}
self.dist = torch.distributions.Uniform(-scale, scale)
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
B, _, _, _ = shape
- src = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
+ src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
dst = src + self.dist.rsample(src.shape)
return {"src": src, "dst": dst}
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
src = params["src"].to(input)
dst = params["dst"].to(input)
# NOTE: warp_image_tps need to use inverse parameters
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index 4afa1a39d..d5be7f353 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
-from kornia.core import Tensor, as_tensor, stack
from kornia.geometry.transform import get_translation_matrix2d, warp_affine
class RandomTranslate(GeometricAugmentationBase2D):
- r"""Apply a random 2D affine transformation to a tensor image.
+ r"""Apply a random 2D affine transformation to a torch.tensor image.
Args:
translate_x: tuple of maximum absolute fraction for horizontal translations.
@@ -35,7 +36,7 @@ class RandomTranslate(GeometricAugmentationBase2D):
For example translate_y=(a, b), then vertical shift
is randomly sampled in the range img_height * a < dy < img_height * b.
resample: resample mode from "nearest" (0) or "bilinear" (1).
- padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2).
+ padding_mode: padding mode from "torch.zeros" (0), "border" (1) or "reflection" (2).
same_on_batch: apply the same transformation across the batch.
align_corners: interpolation flag.
p: probability of applying the transformation.
@@ -75,8 +76,8 @@ class RandomTranslate(GeometricAugmentationBase2D):
def __init__(
self,
- translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None,
- translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ translate_x: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ translate_y: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False,
@@ -92,16 +93,22 @@ class RandomTranslate(GeometricAugmentationBase2D):
"align_corners": align_corners,
}
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- translations = stack([params["translate_x"], params["translate_y"]], dim=-1)
- return get_translation_matrix2d(as_tensor(translations, device=input.device, dtype=input.dtype))
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ translations = torch.stack([params["translate_x"], params["translate_y"]], dim=-1)
+ return get_translation_matrix2d(torch.as_tensor(translations, device=input.device, dtype=input.dtype))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, _, height, width = input.shape
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -114,16 +121,16 @@ class RandomTranslate(GeometricAugmentationBase2D):
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index facf0852f..8c808f00a 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -17,13 +17,14 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
-from kornia.core import Tensor, as_tensor, tensor
from kornia.geometry.transform import vflip
class RandomVerticalFlip(GeometricAugmentationBase2D):
- r"""Apply a random vertical flip to a tensor image or a batch of tensor images with a given probability.
+ r"""Apply a random vertical flip to a torch.tensor image or a batch of torch.tensor images with a given probability.
.. image:: _static/img/RandomVerticalFlip.png
@@ -63,29 +64,37 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
"""
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
h: int = int(params["forward_input_shape"][-2])
- flip_mat: Tensor = tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.expand(input.shape[0], 3, 3)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return vflip(input)
def inverse_transform(
self,
- input: Tensor,
+ input: torch.Tensor,
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
- transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index a57788dfc..02d2b1287 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -17,13 +17,14 @@
from typing import Any, Dict, Optional
+import torch
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import normalize_min_max
class RandomAutoContrast(IntensityAugmentationBase2D):
- r"""Apply a random auto-contrast of a tensor image.
+ r"""Apply a random auto-contrast of a torch.tensor image.
Args:
p: probability of applying the transformation.
@@ -48,8 +49,12 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
self.clip_output = clip_output
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
out = normalize_min_max(input)
if self.clip_output:
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index e100d500b..a2c13006d 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.utils import _range_bound
-from kornia.core import Tensor
from kornia.enhance.adjust import adjust_brightness
class RandomBrightness(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness of a tensor image.
+ r"""Apply a random transformation to the brightness of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -81,13 +82,17 @@ class RandomBrightness(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.brightness: Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
+ self.brightness: torch.Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
self.clip_output = clip_output
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
brightness_factor = params["brightness_factor"].to(input)
return adjust_brightness(input, brightness_factor - 1, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index 5a37c9eaf..5a83a5a7e 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional
+import torch
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import ChannelDropoutGenerator
-from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
@@ -88,7 +89,7 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
0.0 <= fill_value <= 1.0,
f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}",
)
- self.fill_value = tensor(fill_value)
+ self.fill_value = torch.tensor(fill_value)
KORNIA_CHECK_TYPE(num_drop_channels, int, f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}")
KORNIA_CHECK(
@@ -100,8 +101,12 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
self._param_generator = ChannelDropoutGenerator(self.num_drop_channels)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
self.num_drop_channels <= input.shape[1],
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index fef1d4056..4e132fab6 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -20,7 +20,6 @@ from typing import Any, Dict, Optional, Tuple
import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
class RandomChannelShuffle(IntensityAugmentationBase2D):
@@ -55,14 +54,18 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
B, C, _, _ = shape
channels = torch.rand(B, C).argsort(dim=1)
return {"channels": channels}
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
out = torch.empty_like(input)
for i in range(out.shape[0]):
out[i] = input[i, params["channels"][i]]
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 9142b1b26..64bb64e8a 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -19,14 +19,15 @@ from __future__ import annotations
from typing import Any, Optional
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import equalize_clahe
class RandomClahe(IntensityAugmentationBase2D):
- r"""Apply CLAHE equalization on the input tensor randomly.
+ r"""Apply CLAHE equalization on the input torch.tensor randomly.
.. image:: _static/img/equalize_clahe.png
@@ -77,7 +78,11 @@ class RandomClahe(IntensityAugmentationBase2D):
self.flags = {"grid_size": grid_size, "slow_and_differentiable": slow_and_differentiable}
def apply_transform(
- self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: dict[str, torch.Tensor],
+ flags: dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
clip_limit = float(params["clip_limit_factor"][0])
return equalize_clahe(input, clip_limit, flags["grid_size"], flags["slow_and_differentiable"])
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 7bfd8acd1..363e14314 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.constants import pi
-from kornia.core import Tensor
from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation
class ColorJiggle(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.tensor image.
.. image:: _static/img/ColorJiggle.png
@@ -74,10 +75,10 @@ class ColorJiggle(IntensityAugmentationBase2D):
def __init__(
self,
- brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
@@ -90,8 +91,12 @@ class ColorJiggle(IntensityAugmentationBase2D):
self._param_generator = rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
transforms = [
lambda img: adjust_brightness(img, params["brightness_factor"] - 1)
if (params["brightness_factor"] - 1 != 0).any()
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 274da9a04..aaf8d92f7 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -22,7 +22,6 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.constants import pi
-from kornia.core import Tensor
from kornia.enhance import (
adjust_brightness_accumulative,
adjust_contrast_with_mean_subtraction,
@@ -32,7 +31,7 @@ from kornia.enhance import (
class ColorJitter(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision. However, it does not
follow the color theory and is not be actively maintained. Prefer using
@@ -88,10 +87,10 @@ class ColorJitter(IntensityAugmentationBase2D):
def __init__(
self,
- brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
@@ -112,11 +111,11 @@ class ColorJitter(IntensityAugmentationBase2D):
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
transforms = [
lambda img: (
self._brightness_fn(img, params["brightness_factor"])
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index dab5a21b6..6fcaf0f61 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.utils import _range_bound
-from kornia.core import Tensor
from kornia.enhance.adjust import adjust_contrast
class RandomContrast(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the contrast of a tensor image.
+ r"""Apply a random transformation to the contrast of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -80,13 +81,17 @@ class RandomContrast(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.contrast: Tensor = _range_bound(contrast, "contrast", center=1.0)
+ self.contrast: torch.Tensor = _range_bound(contrast, "contrast", center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
self.clip_output = clip_output
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
contrast_factor = params["contrast_factor"].to(input)
return adjust_contrast(input, contrast_factor, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.py
index 74f751c51..67104b7fd 100644
--- a/kornia/augmentation/_2d/intensity/dissolving.py
+++ b/kornia/augmentation/_2d/intensity/dissolving.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.filters import StableDiffusionDissolving
@@ -70,6 +71,10 @@ class RandomDissolving(IntensityAugmentationBase2D):
self._param_generator = rg.PlainUniformGenerator((self.step_range, "step_range_factor", None, None))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return self._dslv(input, params["step_range_factor"][0].long().item())
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index 7e54efad1..137e8b45e 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor, where
from kornia.geometry.bbox import bbox_generator, bbox_to_mask
class RandomErasing(IntensityAugmentationBase2D):
- r"""Erase a random rectangle of a tensor image according to a probability p value.
+ r"""Erase a random rectangle of a torch.tensor image according to a probability p value.
.. image:: _static/img/RandomErasing.png
@@ -49,9 +50,9 @@ class RandomErasing(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> rng = torch.manual_seed(0)
@@ -72,8 +73,8 @@ class RandomErasing(IntensityAugmentationBase2D):
def __init__(
self,
- scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3),
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
value: float = 0.0,
same_on_batch: bool = False,
p: float = 0.5,
@@ -86,20 +87,28 @@ class RandomErasing(IntensityAugmentationBase2D):
self._param_generator = rg.RectangleEraseGenerator(scale, ratio, value)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, c, h, w = input.size()
values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
- transformed = where(mask == 1.0, values, input)
+ transformed = torch.where(mask == 1.0, values, input)
return transformed
def apply_transform_mask(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
_, c, h, w = input.size()
values = params["values"][..., None, None, None].repeat(1, *input.shape[1:]).to(input)
@@ -109,5 +118,5 @@ class RandomErasing(IntensityAugmentationBase2D):
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
- transformed = where(mask == 1.0, values, input)
+ transformed = torch.where(mask == 1.0, values, input)
return transformed
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index 2dd0d4745..00b9450c6 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance.adjust import adjust_gamma
class RandomGamma(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the gamma of a tensor image.
+ r"""Apply a random transformation to the gamma of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -83,8 +84,12 @@ class RandomGamma(IntensityAugmentationBase2D):
)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
gamma_factor = params["gamma_factor"].to(input)
gain_factor = params["gain_factor"].to(input)
return adjust_gamma(input, gamma_factor, gain_factor)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index eb781e2d5..3860f9ff9 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerator
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
@@ -162,22 +161,22 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
self._param_generator = GaussianIlluminationGenerator(gain, center, sigma, sign)
def _apply_transform(
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return input.add_(params["gradient"]).clamp_(0, 1)
self._fn = _apply_transform
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
return self._fn(input=input, params=params, flags=flags, transform=transform)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index e1355afc9..1f662a503 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -20,10 +20,9 @@ from typing import Any, Dict, Optional, Tuple
import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
-def _randn_like(input: Tensor, mean: float, std: float) -> Tensor:
+def _randn_like(input: torch.Tensor, mean: float, std: float) -> torch.Tensor:
x = torch.randn_like(input) # Generating on GPU is fastest with `torch.randn_like(...)`
if std != 1.0: # `if` is cheaper than multiplication
x *= std
@@ -66,12 +65,16 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self.flags = {"mean": mean, "std": std}
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
return {}
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
if "gaussian_noise" in params:
gaussian_noise = params["gaussian_noise"]
else:
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 2b049cb58..9c7996210 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -17,16 +17,17 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.utils import _range_bound
from kornia.constants import pi
-from kornia.core import Tensor
from kornia.enhance.adjust import adjust_hue
class RandomHue(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the hue of a tensor image.
+ r"""Apply a random transformation to the hue of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -75,11 +76,15 @@ class RandomHue(IntensityAugmentationBase2D):
self, hue: Tuple[float, float] = (0.0, 0.0), same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.hue: Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5))
+ self.hue: torch.Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5))
self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
hue_factor = params["hue_factor"].to(input)
return adjust_hue(input, hue_factor * 2 * pi)
diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.py
index 035162e46..299c0fb38 100644
--- a/kornia/augmentation/_2d/intensity/jpeg.py
+++ b/kornia/augmentation/_2d/intensity/jpeg.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import jpeg_codec_differentiable
class RandomJPEG(IntensityAugmentationBase2D):
- r"""Applies random (differentiable) JPEG coding to a tensor image.
+ r"""Applies random (differentiable) JPEG coding to a torch.tensor image.
.. image:: _static/img/RandomJPEG.png
@@ -59,7 +60,7 @@ class RandomJPEG(IntensityAugmentationBase2D):
def __init__(
self,
- jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0,
+ jpeg_quality: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 50.0,
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
@@ -69,7 +70,11 @@ class RandomJPEG(IntensityAugmentationBase2D):
self._param_generator = rg.JPEGGenerator(jpeg_quality)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- jpeg_output: Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ jpeg_output: torch.Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])
return jpeg_output
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index 1bcf5a6be..07443c7a5 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGenerator
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
@@ -121,11 +122,11 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
return input.add(params["gradient"].to(input)).clamp(0, 1)
@@ -228,10 +229,10 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
return input.add(params["gradient"].to(input)).clamp(0, 1)
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index d89465244..767210f0a 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -22,12 +22,11 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.constants import BorderType, Resample
-from kornia.core import Tensor, tensor
from kornia.filters import motion_blur
class RandomMotionBlur(IntensityAugmentationBase2D):
- r"""Perform motion blur on 2D images (4D tensor).
+ r"""Perform motion blur on 2D images (4D torch.tensor).
.. image:: _static/img/RandomMotionBlur.png
@@ -55,9 +54,9 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
@@ -86,8 +85,8 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]],
- angle: Union[Tensor, float, Tuple[float, float]],
- direction: Union[Tensor, float, Tuple[float, float]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
resample: Union[str, int, Resample] = Resample.NEAREST.name,
same_on_batch: bool = False,
@@ -98,14 +97,18 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)}
- def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
params = super().generate_parameters(batch_shape)
- params["idx"] = tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))
+ params["idx"] = torch.tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))
return params
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
# sample a kernel size
kernel_size_list: List[int] = params["ksize_factor"].tolist()
@@ -113,7 +116,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
# selected random index --- `params["idx"][0]` --- to determine the applied kernel size.
# 2. The `VideoSequential` flattens the first two dimensions, effectively creating a larger batch.
# Its method `VideoSequential.__repeat_param_across_channels__` repeats the previously selected index,
- # creating a tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit.
+ # creating a torch.tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit.
idx: int = cast(int, params["idx"][0])
return motion_blur(
input,
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index 793099aa4..e1ce62355 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, List, Optional, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor, stack, tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
-def get_planckian_coeffs(mode: str) -> Tensor:
+def get_planckian_coeffs(mode: str) -> torch.Tensor:
if mode.lower() == "blackbody":
- coefs = tensor(
+ coefs = torch.tensor(
[
[0.6743, 0.4029, 0.0013],
[0.6281, 0.4241, 0.1665],
@@ -56,7 +57,7 @@ def get_planckian_coeffs(mode: str) -> Tensor:
)
elif mode.upper() == "CIED":
- coefs = tensor(
+ coefs = torch.tensor(
[
[0.5829, 0.4421, 0.2288],
[0.5510, 0.4514, 0.2948],
@@ -86,11 +87,11 @@ def get_planckian_coeffs(mode: str) -> Tensor:
else:
raise RuntimeError(f"Unexpected mode. Gotcha {mode}")
- return stack((coefs[:, 0] / coefs[:, 1], coefs[:, 2] / coefs[:, 1]), 1)
+ return torch.stack((coefs[:, 0] / coefs[:, 1], coefs[:, 2] / coefs[:, 1]), 1)
class RandomPlanckianJitter(IntensityAugmentationBase2D):
- r"""Apply planckian jitter transformation to input tensor.
+ r"""Apply planckian jitter transformation to input torch.tensor.
.. image:: _static/img/RandomPlanckianJitter.png
@@ -113,7 +114,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
.. note::
- Input tensor must be float and normalized into [0, 1].
+ Input torch.tensor must be float and normalized into [0, 1].
Examples:
To apply planckian jitter based on mode
@@ -175,7 +176,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
if select_from is not None:
_pl = _pl[select_from]
self.register_buffer("pl", _pl)
- self.pl: Tensor
+ self.pl: torch.Tensor
# the range of the sampling parameters
_param_min: float = 0.0
@@ -184,8 +185,12 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
self._param_generator = rg.PlanckianJitterGenerator([_param_min, _param_max])
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
list_idx = params["idx"].tolist()
KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"])
self.pl = self.pl.to(device=input.device)
@@ -198,6 +203,6 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
g = input[..., 1, :, :]
b = input[..., 2, :, :] * b_w
- output = stack([r, g, b], -3)
+ output = torch.stack([r, g, b], -3)
return output.clamp(max=1.0)
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index 9cefcbe6c..c48fe8126 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -17,10 +17,11 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.contrib import diamond_square
-from kornia.core import Tensor
class RandomPlasmaBrightness(IntensityAugmentationBase2D):
@@ -66,8 +67,12 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
)
def apply_transform(
- self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ image: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
B, C, H, W = image.shape
roughness = params["roughness"].to(image)
intensity = params["intensity"].to(image).view(-1, 1, 1, 1)
@@ -115,8 +120,12 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
self._param_generator = rg.PlainUniformGenerator((roughness, "roughness", None, None))
def apply_transform(
- self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ image: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
B, C, H, W = image.shape
roughness = params["roughness"].to(image)
contrast_map = 4 * diamond_square((B, C, H, W), roughness, device=image.device, dtype=image.dtype)
@@ -170,8 +179,12 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
)
def apply_transform(
- self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ image: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
B, _, H, W = image.shape
roughness = params["roughness"].to(image)
shade_intensity = params["shade_intensity"].to(image).view(-1, 1, 1, 1)
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index 2786273cd..f39825685 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import posterize
class RandomPosterize(IntensityAugmentationBase2D):
- r"""Posterize given tensor image or a batch of tensor images randomly.
+ r"""Posterize given torch.tensor image or a batch of torch.tensor images randomly.
.. image:: _static/img/RandomPosterize.png
@@ -65,7 +66,7 @@ class RandomPosterize(IntensityAugmentationBase2D):
def __init__(
self,
- bits: Union[float, Tuple[float, float], Tensor] = 3,
+ bits: Union[float, Tuple[float, float], torch.Tensor] = 3,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
@@ -75,6 +76,10 @@ class RandomPosterize(IntensityAugmentationBase2D):
self._param_generator = rg.PosterizeGenerator(bits)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return posterize(input, params["bits_factor"].to(input.device))
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index 0f4dedf48..05e6343ac 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -23,7 +23,6 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import RainGenerator
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
@@ -65,8 +64,12 @@ class RandomRain(IntensityAugmentationBase2D):
self._param_generator = RainGenerator(number_of_drops, drop_height, drop_width)
def apply_transform(
- self, image: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ image: torch.Tensor,
+ params: dict[str, torch.Tensor],
+ flags: dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
# Check array and drops size
KORNIA_CHECK(image.shape[1] in {3, 1}, "Number of color channels should be 1 or 3.")
KORNIA_CHECK(
@@ -84,9 +87,9 @@ class RandomRain(IntensityAugmentationBase2D):
modeified_img = image.clone()
for i in range(image.shape[0]):
number_of_drops: int = int(params["number_of_drops_factor"][i])
- # We generate tensor with maximum number of drops, and then remove unnecessary drops.
+ # We generate torch.tensor with maximum number of drops, and then remove unnecessary drops.
- coordinates_of_drops: Tensor = params["coordinates_factor"][i][:number_of_drops]
+ coordinates_of_drops: torch.Tensor = params["coordinates_factor"][i][:number_of_drops]
height_of_drop: int = int(params["drop_height_factor"][i])
width_of_drop: int = int(params["drop_width_factor"][i])
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index fe285d46d..4896c49a7 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import shift_rgb
@@ -39,7 +40,7 @@ class RandomRGBShift(IntensityAugmentationBase2D):
to the batch form ``False``.
Note:
- Input tensor must be float and normalized into [0, 1].
+ Input torch.tensor must be float and normalized into [0, 1].
Examples:
>>> import torch
@@ -108,6 +109,10 @@ class RandomRGBShift(IntensityAugmentationBase2D):
)
def apply_transform(
- self, inp: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ inp: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
return shift_rgb(inp, params["r_shift"], params["g_shift"], params["b_shift"])
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index a3577ff4f..8af4c714c 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -22,12 +22,11 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.color import hls_to_rgb, rgb_to_hls
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
class RandomSnow(IntensityAugmentationBase2D):
- r"""Generates snow effect on given tensor image or a batch tensor images.
+ r"""Generates snow effect on given torch.tensor image or a batch torch.tensor images.
Args:
snow_coefficient: A tuple of floats (lower and upper bound) between 0 and 1 that control
@@ -36,7 +35,7 @@ class RandomSnow(IntensityAugmentationBase2D):
brightness of the snow.
same_on_batch: If True, apply the same transformation to each image in a batch. Default: False.
p: Probability of applying the transformation. Default: 0.5.
- keepdim: Keep the output tensor with the same shape as input. Default: False.
+ keepdim: Keep the output torch.tensor with the same shape as input. Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
@@ -68,8 +67,12 @@ class RandomSnow(IntensityAugmentationBase2D):
)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
KORNIA_CHECK(input.shape[1] == 3, "Number of color channels should be 3.")
KORNIA_CHECK(len(input.shape) in (3, 4), "Wrong input dimension.")
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index 5cf169ab7..11ddd2f49 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -17,9 +17,10 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import SaltAndPepperGenerator
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
@@ -128,11 +129,11 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
r"""Apply random Salt and Pepper noise transformation to the input image."""
KORNIA_CHECK(len(input.shape) in (3, 4), "Wrong input dimension.")
if len(input.shape) == 3:
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index a016899e4..cab0e23de 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.utils import _range_bound
-from kornia.core import Tensor
from kornia.enhance.adjust import adjust_saturation
class RandomSaturation(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the saturation of a tensor image.
+ r"""Apply a random transformation to the saturation of a torch.tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -78,11 +79,15 @@ class RandomSaturation(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.saturation: Tensor = _range_bound(saturation, "saturation", center=1.0)
+ self.saturation: torch.Tensor = _range_bound(saturation, "saturation", center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.saturation, "saturation_factor", None, None))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
saturation_factor = params["saturation_factor"].to(input)
return adjust_saturation(input, saturation_factor)
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
index 89283b86b..a25bf43f5 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import sharpness
class RandomSharpness(IntensityAugmentationBase2D):
- r"""Sharpen given tensor image or a batch of tensor images randomly.
+ r"""Sharpen given torch.tensor image or a batch of torch.tensor images randomly.
.. image:: _static/img/RandomSharpness.png
@@ -63,7 +64,7 @@ class RandomSharpness(IntensityAugmentationBase2D):
def __init__(
self,
- sharpness: Union[Tensor, float, Tuple[float, float]] = 0.5,
+ sharpness: Union[torch.Tensor, float, Tuple[float, float]] = 0.5,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
@@ -72,7 +73,11 @@ class RandomSharpness(IntensityAugmentationBase2D):
self._param_generator = rg.PlainUniformGenerator((sharpness, "sharpness", 0.0, (0, float("inf"))))
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
factor = params["sharpness"]
return sharpness(input, factor)
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index fb7e9fc1e..5a8ac6146 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -17,14 +17,15 @@
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-from kornia.core import Tensor
from kornia.enhance import solarize
class RandomSolarize(IntensityAugmentationBase2D):
- r"""Solarize given tensor image or a batch of tensor images randomly.
+ r"""Solarize given torch.tensor image or a batch of torch.tensor images randomly.
.. image:: _static/img/RandomSolarize.png
@@ -68,8 +69,8 @@ class RandomSolarize(IntensityAugmentationBase2D):
def __init__(
self,
- thresholds: Union[Tensor, float, Tuple[float, float], List[float]] = 0.1,
- additions: Union[Tensor, float, Tuple[float, float], List[float]] = 0.1,
+ thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
+ additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
@@ -80,10 +81,14 @@ class RandomSolarize(IntensityAugmentationBase2D):
)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
thresholds = params["thresholds"]
- additions: Optional[Tensor]
+ additions: Optional[torch.Tensor]
if "additions" in params:
additions = params["additions"]
else:
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index f036c435d..8d1512e6c 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -27,7 +27,6 @@ from kornia.augmentation.utils import (
_validate_input_dtype,
)
from kornia.constants import DataKey, DType
-from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_UNWRAP
from kornia.geometry.boxes import Boxes
@@ -63,7 +62,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
if data_keys is not None:
self.data_keys = [DataKey.get(inp) for inp in data_keys]
- def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
+ def transform_tensor(
+ self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True
+ ) -> torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -72,15 +73,21 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
else:
return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel)
- def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- # NOTE: apply_transform receives the whole tensor, but returns only altered elements.
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ # NOTE: apply_transform receives the whole torch.tensor, but returns only altered elements.
raise NotImplementedError
- def apply_non_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- # For the images where batch_prob == False.
+ def apply_non_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ # For the images torch.where batch_prob == False.
return input
- def transform_input(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def transform_input(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
@@ -95,7 +102,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
output = _transform_output_shape(output, ori_shape) if self.keepdim else output
return output
- def transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def transform_mask(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
@@ -105,11 +114,13 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
output = self.apply_transform_mask(input, params, flags)
return output
- def transform_boxes(self, input: Union[Tensor, Boxes], params: Dict[str, Tensor], flags: Dict[str, Any]) -> Boxes:
+ def transform_boxes(
+ self, input: Union[torch.Tensor, Boxes], params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> Boxes:
# input is BxNx4x2 or Boxes.
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
- raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx4x2 torch.tensor is supported. Got {input.shape}.")
input = Boxes(input, False, mode="vertices_plus")
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
@@ -120,7 +131,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
output = self.apply_transform_boxes(output, params, flags)
return output
- def transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def transform_keypoint(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
@@ -130,7 +143,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
output = self.apply_transform_keypoint(input, params, flags)
return output
- def transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def transform_class(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
@@ -140,36 +155,48 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
output = self.apply_transform_class(input, params, flags)
return output
- def apply_non_transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_non_transform_mask(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def apply_transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_mask(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def apply_non_transform_boxes(self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Boxes:
+ def apply_non_transform_boxes(self, input: Boxes, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> Boxes:
return input
- def apply_transform_boxes(self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Boxes:
+ def apply_transform_boxes(self, input: Boxes, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> Boxes:
raise NotImplementedError
- def apply_non_transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_non_transform_keypoint(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return input
- def apply_transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_keypoint(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def apply_non_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_non_transform_class(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return input
- def apply_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_class(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
def forward( # type: ignore[override]
self,
- *input: Tensor,
- params: Optional[Dict[str, Tensor]] = None,
+ *input: torch.Tensor,
+ params: Optional[Dict[str, torch.Tensor]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
- ) -> Union[Tensor, List[Tensor]]:
+ ) -> Union[torch.Tensor, List[torch.Tensor]]:
keys: List[DataKey]
if data_keys is None:
keys = self.data_keys
@@ -178,16 +205,16 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
if params is None:
in_tensor_idx: int = keys.index(DataKey.INPUT)
- in_tensor: Tensor = input[in_tensor_idx]
+ in_tensor: torch.Tensor = input[in_tensor_idx]
in_tensor = self.transform_tensor(in_tensor)
self._params = self.forward_parameters(in_tensor.shape)
- self._params.update({"dtype": tensor(DType.get(in_tensor.dtype).value)})
+ self._params.update({"dtype": torch.tensor(DType.get(in_tensor.dtype).value)})
else:
self._params = params
- outputs: List[Tensor] = []
+ outputs: List[torch.Tensor] = []
for dcate, _input in zip(keys, input):
- output: Tensor
+ output: torch.Tensor
if dcate == DataKey.INPUT:
output = self.transform_input(_input, self._params, self.flags)
elif dcate == DataKey.MASK:
@@ -195,15 +222,15 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
elif dcate == DataKey.BBOX:
box = Boxes.from_tensor(_input, mode="vertices", validate_boxes=False)
box = self.transform_boxes(box, self._params, self.flags)
- output = KORNIA_UNWRAP(box.to_tensor("vertices"), Tensor)
+ output = KORNIA_UNWRAP(box.to_tensor("vertices"), torch.Tensor)
elif dcate == DataKey.BBOX_XYXY:
box = Boxes.from_tensor(_input, mode="xyxy", validate_boxes=False)
box = self.transform_boxes(box, self._params, self.flags)
- output = KORNIA_UNWRAP(box.to_tensor("xyxy"), Tensor)
+ output = KORNIA_UNWRAP(box.to_tensor("xyxy"), torch.Tensor)
elif dcate == DataKey.BBOX_XYWH:
box = Boxes.from_tensor(_input, mode="xywh", validate_boxes=False)
box = self.transform_boxes(box, self._params, self.flags)
- output = KORNIA_UNWRAP(box.to_tensor("xywh"), Tensor)
+ output = KORNIA_UNWRAP(box.to_tensor("xywh"), torch.Tensor)
elif dcate == DataKey.KEYPOINTS:
output = self.transform_keypoint(_input, self._params, self.flags)
elif dcate == DataKey.CLASS:
@@ -216,9 +243,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return outputs
@torch.jit.ignore
- def inverse(self, **kwargs: Any) -> Optional[Tensor]:
+ def inverse(self, **kwargs: Any) -> Optional[torch.Tensor]:
raise RuntimeError(f"Inverse for {self.__class__.__name__} is not supported.")
@property
- def transform_matrix(self) -> Optional[Tensor]:
+ def transform_matrix(self) -> Optional[torch.Tensor]:
raise RuntimeError(f"Transformation matrices for {self.__class__.__name__} is not supported.")
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 4a7cf52ec..0df93feb4 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -17,23 +17,24 @@
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, DType
-from kornia.core import Tensor, stack, zeros
from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
class RandomCutMixV2(MixAugmentationBaseV2):
- r"""Apply CutMix augmentation to a batch of tensor images.
+ r"""Apply CutMix augmentation to a batch of torch.tensor images.
.. image:: _static/img/RandomCutMixV2.png
Implementation for `CutMix: Regularization Strategy to Train Strong Classifiers with
Localizable Features` :cite:`yun2019cutmix`.
- The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images
- while the labels is a :math:`(\text{num_mixes}, B, 3)` tensor that contains (label_permuted_batch, lambda)
+ The function returns (inputs, labels), in which the inputs is the torch.tensor that contains the mixup images
+ while the labels is a :math:`(\text{num_mixes}, B, 3)` torch.tensor that contains (label_permuted_batch, lambda)
for each cutmix.
The implementation referred to the following repository: `https://github.com/clovaai/CutMix-PyTorch
@@ -62,7 +63,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
- Raw labels, shape of :math:`(B)`.
Returns:
- Tuple[Tensor, Tensor]:
+ Tuple[torch.Tensor, torch.Tensor]:
- Adjusted image, shape of :math:`(B, C, H, W)`.
- Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, num_mix, 3)`.
@@ -91,8 +92,8 @@ class RandomCutMixV2(MixAugmentationBaseV2):
def __init__(
self,
num_mix: int = 1,
- cut_size: Optional[Union[Tensor, Tuple[float, float]]] = None,
- beta: Optional[Union[Tensor, float]] = None,
+ cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ beta: Optional[Union[torch.Tensor, float]] = None,
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
@@ -112,7 +113,9 @@ class RandomCutMixV2(MixAugmentationBaseV2):
stacklevel=2,
)
- def apply_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_class(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
height, width = params["image_shape"]
out_labels = []
@@ -124,7 +127,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
lam = 1 - lam_val if self.use_correct_lambda else lam_val
out_labels.append(
- stack(
+ torch.stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
labels_permute.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
@@ -134,16 +137,16 @@ class RandomCutMixV2(MixAugmentationBaseV2):
)
)
- return stack(out_labels, 0)
+ return torch.stack(out_labels, 0)
def apply_non_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
out_labels = []
- lam = zeros((len(input)), device=input.device, dtype=DType.to_torch(int(params["dtype"].item())))
+ lam = torch.zeros((len(input)), device=input.device, dtype=DType.to_torch(int(params["dtype"].item())))
for _ in range(self._param_generator.num_mix):
out_labels.append(
- stack(
+ torch.stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
@@ -153,11 +156,11 @@ class RandomCutMixV2(MixAugmentationBaseV2):
)
)
- return stack(out_labels, 0)
+ return torch.stack(out_labels, 0)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
height, width = input.size(2), input.size(3)
out_inputs = input.clone()
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index f4f97033a..0811ea186 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -22,7 +22,6 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey
-from kornia.core import Tensor
__all__ = ["RandomJigsaw"]
@@ -71,8 +70,8 @@ class RandomJigsaw(MixAugmentationBaseV2):
self.flags = {"grid": grid}
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
# different from the Base class routine. This function will not refer to any non-transformation images.
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 3a169a3aa..8b9e9fd25 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -17,21 +17,22 @@
from typing import Any, Dict, List, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, DType
-from kornia.core import Tensor, stack, zeros
class RandomMixUpV2(MixAugmentationBaseV2):
- r"""Apply MixUp augmentation to a batch of tensor images.
+ r"""Apply MixUp augmentation to a batch of torch.tensor images.
.. image:: _static/img/RandomMixUpV2.png
Implementation for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION` :cite:`zhang2018mixup`.
- The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images
- while the labels is a :math:`(B, 3)` tensor that contains (label_batch, label_permuted_batch, lambda) for
+ The function returns (inputs, labels), in which the inputs is the torch.tensor that contains the mixup images
+ while the labels is a :math:`(B, 3)` torch.tensor that contains (label_batch, label_permuted_batch, lambda) for
each image.
The implementation is on top of the following repository:
@@ -68,7 +69,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
- Label: raw labels, shape of :math:`(B)`.
Returns:
- Tuple[Tensor, Tensor]:
+ Tuple[torch.Tensor, torch.Tensor]:
- Adjusted image, shape of :math:`(B, C, H, W)`.
- Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.
@@ -95,7 +96,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
def __init__(
self,
- lambda_val: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
@@ -105,8 +106,8 @@ class RandomMixUpV2(MixAugmentationBaseV2):
self._param_generator = rg.MixupGenerator(lambda_val, p=p)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(input.device)
@@ -114,24 +115,24 @@ class RandomMixUpV2(MixAugmentationBaseV2):
return inputs
def apply_non_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
- out_labels = stack(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
+ out_labels = torch.stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
- zeros((len(input),), device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ torch.zeros((len(input),), device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
],
-1,
)
return out_labels
def apply_transform_class(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
labels_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
- out_labels = stack(
+ out_labels = torch.stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
labels_permute.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 238e01264..270941679 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -18,11 +18,11 @@
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
+import torch.nn.functional as F
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, Resample
-from kornia.core import Tensor, as_tensor, concatenate, pad, zeros
from kornia.core.check import KORNIA_UNWRAP
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
@@ -46,7 +46,7 @@ class RandomMosaic(MixAugmentationBaseV2):
2. Crop out the outcome image according to the top-left corner and crop size.
Args:
- output_size: the output tensor width and height after mosaicing.
+ output_size: the output torch.tensor width and height after mosaicing.
start_ratio_range: top-left (x, y) position for cropping the mosaic images.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
@@ -60,7 +60,7 @@ class RandomMosaic(MixAugmentationBaseV2):
padding_mode: Type of padding. Should be: constant, reflect, replicate.
resample: the interpolation mode.
align_corners: interpolation flag.
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -106,17 +106,19 @@ class RandomMosaic(MixAugmentationBaseV2):
"cropping_mode": cropping_mode,
}
- def apply_transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_mask(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
@torch.no_grad()
- def apply_transform_boxes(self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Boxes:
+ def apply_transform_boxes(self, input: Boxes, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> Boxes:
to_apply = params["batch_prob"] > 0.5
- src_box = as_tensor(params["src"], device=input.device, dtype=input.dtype)
- dst_box = as_tensor(params["dst"], device=input.device, dtype=input.dtype)
+ src_box = torch.as_tensor(params["src"], device=input.device, dtype=input.dtype)
+ dst_box = torch.as_tensor(params["dst"], device=input.device, dtype=input.dtype)
# Boxes is BxNx4x2 only.
- batch_shapes = as_tensor(params["batch_shapes"], device=input.device, dtype=input.dtype)
- offset = zeros((len(to_apply), 2), device=input.device, dtype=input.dtype) # Bx2
+ batch_shapes = torch.as_tensor(params["batch_shapes"], device=input.device, dtype=input.dtype)
+ offset = torch.zeros((len(to_apply), 2), device=input.device, dtype=input.dtype) # Bx2
# NOTE: not a pretty good line I think.
offset_end = dst_box[0, 2].repeat(input.data.shape[0], 1)
idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[to_apply]
@@ -143,14 +145,20 @@ class RandomMosaic(MixAugmentationBaseV2):
out_boxes.filter_boxes_by_area(flags["min_bbox_size"], inplace=True)
return out_boxes
- def apply_transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_keypoint(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def apply_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_class(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise RuntimeError(f"{self.__class__.__name__} does not support `TAG` types.")
@torch.no_grad()
- def _compose_images(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def _compose_images(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
out = []
for i in range(flags["mosaic_grid"][0]):
out_row = []
@@ -158,26 +166,32 @@ class RandomMosaic(MixAugmentationBaseV2):
img_idx = flags["mosaic_grid"][1] * i + j
image = input[params["permutation"][:, img_idx]]
out_row.append(image)
- out.append(concatenate(out_row, -2))
- return concatenate(out, -1)
+ out.append(torch.cat(out_row, -2))
+ return torch.cat(out, -1)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
if flags["cropping_mode"] == "resample":
- transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
return transform
if flags["cropping_mode"] == "slice": # Skip the computation for slicing.
return eye_like(3, input)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def _crop_images(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
- # Fit the arg to F.pad
+ # Fit the arg to F.F.pad
if flags["padding_mode"] == "constant":
padding_mode = "zeros"
elif flags["padding_mode"] == "replicate":
@@ -196,15 +210,15 @@ class RandomMosaic(MixAugmentationBaseV2):
align_corners=flags["align_corners"],
)
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
- return crop_by_indices(input, params["src"], flags["output_size"], shape_compensation="pad")
+ return crop_by_indices(input, params["src"], flags["output_size"], shape_compensation="F.pad")
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
def apply_non_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if flags is not None and flags["output_size"] is not None:
output_size = KORNIA_UNWRAP(flags["output_size"], Tuple[int, int])
- return pad(input, [0, output_size[1] - input.shape[-1], 0, output_size[0] - input.shape[-2]])
+ return F.pad(input, [0, output_size[1] - input.shape[-1], 0, output_size[0] - input.shape[-2]])
# NOTE: resize is not suitable for being consistent with bounding boxes.
# return resize(
# input,
@@ -215,8 +229,8 @@ class RandomMosaic(MixAugmentationBaseV2):
return input
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
flags = KORNIA_UNWRAP(maybe_flags, Dict[str, Any])
output = self._compose_images(input, params, flags=flags)
transform = self.compute_transformation(output, params, flags=flags)
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index b895981e1..31938af8e 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -24,7 +24,6 @@ import torch
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.augmentation.utils import _validate_input_dtype
from kornia.constants import DataKey
-from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_CHECK
__all__ = ["RandomTransplantation"]
@@ -55,8 +54,9 @@ class RandomTransplantation(MixAugmentationBaseV2):
receive a transplant.
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wise.
- data_keys: the input type sequential for applying augmentations. There must be at least one "mask" tensor. If no
- data keys are given, the first tensor is assumed to be `DataKey.INPUT` and the second tensor `DataKey.MASK`.
+ data_keys: the input type sequential for applying augmentations. There must be at least one "mask" torch.tensor.
+ If no data keys are given, the first torch.tensor is assumed to be `DataKey.INPUT` and the second
+ torch.tensor `DataKey.MASK`.
Accepts "input", "mask".
Note:
@@ -68,16 +68,16 @@ class RandomTransplantation(MixAugmentationBaseV2):
:class:`kornia.augmentation.RandomTransplantation3D` for 3D images.
Inputs:
- - Segmentation mask tensor which is used to determine the objects for transplantation: :math:`(B, *)`.
- - (optional) Additional image or mask tensors where the features are transplanted based on the first
+ - Segmentation mask torch.tensor which is used to determine the objects for transplantation: :math:`(B, *)`.
+ - (optional) Additional image or mask tensors torch.where the features are transplanted based on the first
segmentation mask: :math:`(B, C, *)` (`DataKey.INPUT`) or :math:`(B, *)` (`DataKey.MASK`).
Returns:
- Tensor | list[Tensor]:
+ torch.Tensor | list[torch.Tensor]:
- Tensor:
+ torch.Tensor:
- Augmented mask tensors: :math:`(B, *)`.
- list[Tensor]:
+ list[torch.Tensor]:
- Augmented mask tensors: :math:`(B, *)`.
- Additional augmented image or mask tensors: :math:`(B, C, *)` (`DataKey.INPUT`) or :math:`(B, *)`
(`DataKey.MASK`).
@@ -166,7 +166,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
def __init__(
self,
- excluded_labels: Optional[Union[Sequence[int], Tensor]] = None,
+ excluded_labels: Optional[Union[Sequence[int], torch.Tensor]] = None,
p: float = 0.5,
p_batch: float = 1.0,
data_keys: Optional[list[str | int | DataKey]] = None,
@@ -175,9 +175,9 @@ class RandomTransplantation(MixAugmentationBaseV2):
if excluded_labels is None:
excluded_labels = []
- if not isinstance(excluded_labels, Tensor):
- excluded_labels = tensor(excluded_labels)
- self.excluded_labels: Tensor = excluded_labels
+ if not isinstance(excluded_labels, torch.Tensor):
+ excluded_labels = torch.tensor(excluded_labels)
+ self.excluded_labels: torch.Tensor = excluded_labels
KORNIA_CHECK(
self.excluded_labels.ndim == 1,
f"excluded_labels must be a 1-dimensional sequence, but got {self.excluded_labels.ndim} dimensions.",
@@ -188,26 +188,28 @@ class RandomTransplantation(MixAugmentationBaseV2):
self.data_keys = [DataKey.get(inp) for inp in data_keys]
self._channel_dim = 1
- def apply_non_transform_mask(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any]) -> Tensor:
+ def apply_non_transform_mask(
+ self, input: torch.Tensor, params: dict[str, torch.Tensor], flags: dict[str, Any]
+ ) -> torch.Tensor:
return input
- def transform_input(self, acceptor: Tensor, donor: Tensor, selection: Tensor) -> Tensor: # type: ignore[override]
+ def transform_input(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor: # type: ignore[override]
# Expand selection to the channel dimension
selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)
acceptor[selection] = donor[selection]
return acceptor
- def transform_mask(self, acceptor: Tensor, donor: Tensor, selection: Tensor) -> Tensor: # type: ignore[override]
+ def transform_mask(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor: # type: ignore[override]
acceptor[selection] = donor[selection]
return acceptor
def params_from_input(
self,
- *input: Tensor,
+ *input: torch.Tensor,
data_keys: list[DataKey],
- params: dict[str, Tensor],
+ params: dict[str, torch.Tensor],
extra_args: Optional[dict[DataKey, dict[str, Any]]] = None,
- ) -> dict[str, Tensor]:
+ ) -> dict[str, torch.Tensor]:
"""Compute parameters for the transformation which are based on one or more input tensors.
This function is, for example, called by :class:`kornia.augmentation.container.ops.AugmentationSequentialOps`
@@ -215,7 +217,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
Args:
*input: All input tensors passed to the augmentation pipeline.
- data_keys: Associated data key for every input tensor.
+ data_keys: Associated data key for every input torch.tensor.
params: Dictionary of parameters computed so far by the augmentation pipeline (e.g. including the
`batch_prob`).
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -231,7 +233,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
)
# The first mask key will be used for the transplantation
- mask: Tensor = input[data_keys.index(DataKey.MASK)]
+ mask: torch.Tensor = input[data_keys.index(DataKey.MASK)]
for _input, key in zip(input, data_keys):
if key == DataKey.INPUT:
KORNIA_CHECK(
@@ -255,7 +257,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
if self.excluded_labels.device != mask.device:
self.excluded_labels = self.excluded_labels.to(mask.device)
- donor_labels: list[Tensor] = []
+ donor_labels: list[torch.Tensor] = []
for d in range(len(params["donor_indices"])):
# Select a random label from the donor image
current_mask = mask[params["donor_indices"][d]]
@@ -274,14 +276,15 @@ class RandomTransplantation(MixAugmentationBaseV2):
selection = torch.zeros(
(len(params["acceptor_indices"]), *mask.shape[1:]), dtype=torch.bool, device=mask.device
)
- selected_labels: Tensor = params["selected_labels"]
+ selected_labels: torch.Tensor = params["selected_labels"]
KORNIA_CHECK(
selected_labels.ndim == 1,
- f"selected_labels must be a 1-dimensional tensor, but got {selected_labels.ndim} dimensions.",
+ f"selected_labels must be a 1-dimensional torch.tensor, but got {selected_labels.ndim} dimensions.",
)
KORNIA_CHECK(
len(selected_labels) <= len(params["acceptor_indices"]),
- f"There cannot be more selected labels ({len(selected_labels)}) than images where this augmentation "
+ f"There cannot be more selected labels ({len(selected_labels)}) than images "
+ f"torch.where this augmentation "
f"should be applied ({len(params['acceptor_indices'])}).",
)
@@ -295,11 +298,11 @@ class RandomTransplantation(MixAugmentationBaseV2):
def forward( # type: ignore[override]
self,
- *input: Tensor,
- params: Optional[dict[str, Tensor]] = None,
+ *input: torch.Tensor,
+ params: Optional[dict[str, torch.Tensor]] = None,
data_keys: Optional[list[str | int | DataKey]] = None,
**kwargs: dict[str, Any],
- ) -> Tensor | list[Tensor]:
+ ) -> torch.Tensor | list[torch.Tensor]:
keys: list[DataKey]
if data_keys is None:
keys = self.data_keys
@@ -307,7 +310,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
keys = [DataKey.get(inp) for inp in data_keys]
if params is None:
- mask: Tensor = input[keys.index(DataKey.MASK)]
+ mask: torch.Tensor = input[keys.index(DataKey.MASK)]
self._params = self.forward_parameters(mask.shape)
else:
self._params = params
@@ -315,12 +318,12 @@ class RandomTransplantation(MixAugmentationBaseV2):
if any(k not in self._params for k in ["acceptor_indices", "donor_indices", "selection"]):
self._params.update(self.params_from_input(*input, data_keys=keys, params=self._params))
- outputs: list[Tensor] = []
+ outputs: list[torch.Tensor] = []
for dcate, _input in zip(keys, input):
acceptor = _input[self._params["acceptor_indices"]].clone()
donor = _input[self._params["donor_indices"]]
- output: Tensor
+ output: torch.Tensor
if dcate == DataKey.INPUT:
_validate_input_dtype(_input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 4fefa116b..f3b311be2 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -17,12 +17,12 @@
from typing import Any, Dict, Optional
+import torch
from torch import float16, float32, float64
import kornia
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype
-from kornia.core import Tensor
from kornia.geometry.boxes import Boxes3D
from kornia.geometry.keypoints import Keypoints3D
@@ -39,13 +39,15 @@ class AugmentationBase3D(_AugmentationBase):
"""
- def validate_tensor(self, input: Tensor) -> None:
- """Check if the input tensor is formatted as expected."""
+ def validate_tensor(self, input: torch.Tensor) -> None:
+ """Check if the input torch.tensor is formatted as expected."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
if len(input.shape) != 5:
raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")
- def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
+ def transform_tensor(
+ self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True
+ ) -> torch.Tensor:
"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
if shape is None:
@@ -53,7 +55,7 @@ class AugmentationBase3D(_AugmentationBase):
else:
return _transform_input3d_by_shape(input, reference_shape=shape, match_channel=match_channel)
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return 4x4 identity matrix."""
return kornia.eye_like(4, input)
@@ -75,16 +77,20 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
"""
- _transform_matrix: Optional[Tensor]
+ _transform_matrix: Optional[torch.Tensor]
@property
- def transform_matrix(self) -> Optional[Tensor]:
+ def transform_matrix(self) -> Optional[torch.Tensor]:
return self._transform_matrix
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
raise NotImplementedError
- def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def generate_transformation_matrix(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
"""Generate transformation matrices with the given input and param settings."""
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
@@ -101,33 +107,53 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
return trans_matrix
def inverse_inputs(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def inverse_masks(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def inverse_boxes(
- self, input: Boxes3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Boxes3D,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Boxes3D:
raise NotImplementedError
def inverse_keypoints(
- self, input: Keypoints3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ self,
+ input: Keypoints3D,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints3D:
raise NotImplementedError
def inverse_classes(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
raise NotImplementedError
def apply_func(
- self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, in_tensor: torch.Tensor, params: Dict[str, torch.Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if flags is None:
flags = self.flags
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 7a774055c..0db1bc951 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
-from kornia.core import Tensor
-from kornia.geometry import deg2rad, get_affine_matrix3d, warp_affine3d
+from kornia.geometry.transform.imgwarp import get_affine_matrix3d, warp_affine3d
class RandomAffine3D(GeometricAugmentationBase3D):
- r"""Apply affine transformation 3D volumes (5D tensor).
+ r"""Apply affine transformation 3D volumes (5D torch.tensor).
The transformation is computed so that the center is kept invariant.
@@ -66,9 +67,9 @@ class RandomAffine3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -102,19 +103,21 @@ class RandomAffine3D(GeometricAugmentationBase3D):
def __init__(
self,
degrees: Union[
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float],
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
],
- translate: Optional[Union[Tensor, Tuple[float, float, float]]] = None,
+ translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
scale: Optional[
- Union[Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
+ Union[
+ torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
+ ]
] = None,
shears: Union[
None,
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float],
Tuple[float, float, float, float, float, float],
@@ -142,26 +145,32 @@ class RandomAffine3D(GeometricAugmentationBase3D):
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
self._param_generator = rg.AffineGenerator3D(degrees, translate, scale, shears)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- transform: Tensor = get_affine_matrix3d(
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ transform: torch.Tensor = get_affine_matrix3d(
params["translations"],
params["center"],
params["scale"],
params["angles"],
- deg2rad(params["sxy"]),
- deg2rad(params["sxz"]),
- deg2rad(params["syx"]),
- deg2rad(params["syz"]),
- deg2rad(params["szx"]),
- deg2rad(params["szy"]),
+ torch.deg2rad(params["sxy"]),
+ torch.deg2rad(params["sxz"]),
+ torch.deg2rad(params["syx"]),
+ torch.deg2rad(params["syz"]),
+ torch.deg2rad(params["szx"]),
+ torch.deg2rad(params["szy"]),
).to(input)
return transform
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
return warp_affine3d(
input,
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 1537126ef..6707b288f 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union, cast
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
class CenterCrop3D(GeometricAugmentationBase3D):
- r"""Apply center crop on 3D volumes (5D tensor).
+ r"""Apply center crop on 3D volumes (5D torch.tensor).
Args:
p: probability of applying the transformation for the whole batch.
@@ -42,9 +43,9 @@ class CenterCrop3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, out_d, out_h, out_w)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -85,7 +86,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):
keepdim: bool = False,
) -> None:
# same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1], size[2])
@@ -95,20 +96,26 @@ class CenterCrop3D(GeometricAugmentationBase3D):
raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")
self.flags = {"align_corners": align_corners, "resample": Resample.get(resample)}
- def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
return rg.center_crop_generator3d(
batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device
)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- transform: Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- transform = cast(Tensor, transform)
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
return crop_by_transform_mat3d(
input, transform, self.size, mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 818a5a0a7..aba88bfd4 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -17,15 +17,17 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+import torch.nn.functional as F
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
-from kornia.core import Tensor, pad
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
class RandomCrop3D(GeometricAugmentationBase3D):
- r"""Apply random crop on 3D volumes (5D tensor).
+ r"""Apply random crop on 3D volumes (5D torch.tensor).
Crops random sub-volumes on a given size.
@@ -34,11 +36,11 @@ class RandomCrop3D(GeometricAugmentationBase3D):
size: Desired output size (out_d, out_h, out_w) of the crop.
Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
padding: Optional padding on each border of the image.
- Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to pad
+ Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to F.pad
left, top, right, bottom, front, back borders respectively.
- If a sequence of length 3 is provided, it is used to pad left/right,
+ If a sequence of length 3 is provided, it is used to F.pad left/right,
top/bottom, front/back borders, respectively.
- pad_if_needed: It will pad the image if smaller than the
+ pad_if_needed: It will F.pad the image if smaller than the
desired size to avoid raising an exception. Since cropping is done
after padding, the padding seems to be done at a random offset.
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
@@ -56,9 +58,9 @@ class RandomCrop3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, , out_d, out_h, out_w)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -93,7 +95,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
p: float = 1.0,
keepdim: bool = False,
) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.flags = {
"size": size,
@@ -106,7 +108,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
}
self._param_generator = rg.CropGenerator3D(size, None)
- def precrop_padding(self, input: Tensor, flags: Optional[Dict[str, Any]] = None) -> Tensor:
+ def precrop_padding(self, input: torch.Tensor, flags: Optional[Dict[str, Any]] = None) -> torch.Tensor:
flags = self.flags if flags is None else flags
padding = flags["padding"]
if padding is not None:
@@ -118,38 +120,46 @@ class RandomCrop3D(GeometricAugmentationBase3D):
padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]]
else:
raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
- input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
if flags["pad_if_needed"] and input.shape[-3] < flags["size"][0]:
padding = [0, 0, 0, 0, flags["size"][0] - input.shape[-3], flags["size"][0] - input.shape[-3]]
- input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
if flags["pad_if_needed"] and input.shape[-2] < flags["size"][1]:
padding = [0, 0, (flags["size"][1] - input.shape[-2]), flags["size"][1] - input.shape[-2], 0, 0]
- input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
if flags["pad_if_needed"] and input.shape[-1] < flags["size"][2]:
padding = [flags["size"][2] - input.shape[-1], flags["size"][2] - input.shape[-1], 0, 0, 0, 0]
- input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
return input
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- transform: Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
return crop_by_transform_mat3d(
input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
+ def forward(
+ self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, **kwargs: Any
+ ) -> torch.Tensor:
# TODO: need to align 2D implementations
input = self.precrop_padding(input)
return super().forward(input, params)
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 50821127f..8b6ed4fab 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -44,7 +44,7 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
Examples:
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index 2498982ef..849fcf851 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -38,7 +38,7 @@ class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
Examples:
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index e46d08c08..4926bdd01 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry import get_perspective_transform3d, warp_perspective3d
class RandomPerspective3D(GeometricAugmentationBase3D):
- r"""Apply andom perspective transformation to 3D volumes (5D tensor).
+ r"""Apply andom perspective transformation to 3D volumes (5D torch.tensor).
Args:
p: probability of the image being perspectively transformed.
@@ -41,9 +42,9 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -83,7 +84,7 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
def __init__(
self,
- distortion_scale: Union[Tensor, float] = 0.5,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False,
@@ -94,14 +95,20 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
self._param_generator = rg.PerspectiveGenerator3D(distortion_scale)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
return warp_perspective3d(
input,
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 3f2633496..0e8617453 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -17,22 +17,23 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
import kornia
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
-from kornia.core import Tensor
from kornia.geometry import affine3d
from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
class RandomRotation3D(GeometricAugmentationBase3D):
- r"""Apply random rotations to 3D volumes (5D tensor).
+ r"""Apply random rotations to 3D volumes (5D torch.tensor).
- Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
+ Input should be a torch.tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
the corresponding transformation matrix that has been applied to them. In this case the module
- will rotate the tensors and concatenate the corresponding transformation matrix to the
+ will rotate the tensors and torch.cat the corresponding transformation matrix to the
previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
Args:
@@ -55,9 +56,9 @@ class RandomRotation3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -91,7 +92,7 @@ class RandomRotation3D(GeometricAugmentationBase3D):
def __init__(
self,
degrees: Union[
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
@@ -106,16 +107,18 @@ class RandomRotation3D(GeometricAugmentationBase3D):
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
self._param_generator = rg.RotationGenerator3D(degrees)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- yaw: Tensor = params["yaw"].to(input)
- pitch: Tensor = params["pitch"].to(input)
- roll: Tensor = params["roll"].to(input)
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
+ yaw: torch.Tensor = params["yaw"].to(input)
+ pitch: torch.Tensor = params["pitch"].to(input)
+ roll: torch.Tensor = params["roll"].to(input)
- center: Tensor = _compute_tensor_center3d(input)
- rotation_mat: Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
+ center: torch.Tensor = _compute_tensor_center3d(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
# rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix
- trans_mat: Tensor = kornia.eye_like(4, input)
+ trans_mat: torch.Tensor = kornia.eye_like(4, input)
trans_mat[:, 0] = rotation_mat[:, 0]
trans_mat[:, 1] = rotation_mat[:, 1]
trans_mat[:, 2] = rotation_mat[:, 2]
@@ -123,9 +126,13 @@ class RandomRotation3D(GeometricAugmentationBase3D):
return trans_mat
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
- if not isinstance(transform, Tensor):
- raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ if not isinstance(transform, torch.Tensor):
+ raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
return affine3d(input, transform[..., :3, :4], flags["resample"].name.lower(), "zeros", flags["align_corners"])
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index c952678df..0aaa8aa7b 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -44,7 +44,7 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
Examples:
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 52eb49321..9069e4eff 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -17,15 +17,16 @@
from typing import Any, Dict, Optional, Tuple, Union
+import torch
+
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D
from kornia.constants import BorderType, Resample
-from kornia.core import Tensor
from kornia.filters import motion_blur3d
class RandomMotionBlur3D(IntensityAugmentationBase3D):
- r"""Apply random motion blur on 3D volumes (5D tensor).
+ r"""Apply random motion blur on 3D volumes (5D torch.tensor).
Args:
p: probability of applying the transformation.
@@ -56,9 +57,9 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.tensor and returned.
Examples:
>>> import torch
@@ -96,12 +97,12 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
self,
kernel_size: Union[int, Tuple[int, int]],
angle: Union[
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
],
- direction: Union[Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
resample: Union[str, int, Resample] = Resample.NEAREST.name,
same_on_batch: bool = False,
@@ -112,12 +113,18 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)}
self._param_generator = rg.MotionBlurGenerator3D(kernel_size, angle, direction)
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def compute_transformation(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
+ ) -> torch.Tensor:
return self.identity_matrix(input)
def apply_transform(
- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
kernel_size = int(params["ksize_factor"].unique().item())
angle = params["angle_factor"]
direction = params["direction_factor"]
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index b2567183d..0d407689f 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -17,12 +17,13 @@
from typing import Iterator, List, Optional, Tuple, Union
+import torch
+from torch import nn
from torch.distributions import Categorical
from kornia.augmentation.auto.base import SUBPOLICY_CONFIG, PolicyAugmentBase
from kornia.augmentation.auto.operations.policy import PolicySequential
from kornia.augmentation.container.params import ParamItem
-from kornia.core import Module, tensor
from . import ops
@@ -151,13 +152,13 @@ class AutoAugment(PolicyAugmentBase):
raise NotImplementedError(f"Invalid policy `{policy}`.")
super().__init__(_policy, transformation_matrix_mode=transformation_matrix_mode)
- selection_weights = tensor([1.0 / len(self)] * len(self))
+ selection_weights = torch.tensor([1.0 / len(self)] * len(self))
self.rand_selector = Categorical(selection_weights)
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
return PolicySequential(*[getattr(ops, name)(prob, mag) for name, prob, mag in subpolicy])
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is None:
idx = self.rand_selector.sample((1,))
return self.get_children_by_indices(idx)
diff --git a/kornia/augmentation/auto/autoaugment/ops.py b/kornia/augmentation/auto/autoaugment/ops.py
index 87d4867e7..24ee74b1b 100644
--- a/kornia/augmentation/auto/autoaugment/ops.py
+++ b/kornia/augmentation/auto/autoaugment/ops.py
@@ -17,6 +17,8 @@
"""AutoAugment operation wrapper."""
+import torch
+
from kornia.augmentation.auto.operations import (
AutoContrast,
Brightness,
@@ -34,12 +36,11 @@ from kornia.augmentation.auto.operations import (
TranslateX,
TranslateY,
)
-from kornia.core import linspace
def shear_x(probability: float, magnitude: int) -> OperationBase:
"""Return ShearX op."""
- magnitudes = linspace(-0.3, 0.3, 11) * 180.0
+ magnitudes = torch.linspace(-0.3, 0.3, 11) * 180.0
return ShearX(
None,
probability,
@@ -50,7 +51,7 @@ def shear_x(probability: float, magnitude: int) -> OperationBase:
def shear_y(probability: float, magnitude: int) -> OperationBase:
"""Return ShearY op."""
- magnitudes = linspace(-0.3, 0.3, 11) * 180.0
+ magnitudes = torch.linspace(-0.3, 0.3, 11) * 180.0
return ShearY(
None,
probability,
@@ -61,7 +62,7 @@ def shear_y(probability: float, magnitude: int) -> OperationBase:
def translate_x(probability: float, magnitude: int) -> OperationBase:
"""Return TranslateX op."""
- magnitudes = linspace(-0.5, 0.5, 11)
+ magnitudes = torch.linspace(-0.5, 0.5, 11)
return TranslateX(
None,
probability,
@@ -72,7 +73,7 @@ def translate_x(probability: float, magnitude: int) -> OperationBase:
def translate_y(probability: float, magnitude: int) -> OperationBase:
"""Return TranslateY op."""
- magnitudes = linspace(-0.5, 0.5, 11)
+ magnitudes = torch.linspace(-0.5, 0.5, 11)
return TranslateY(
None,
probability,
@@ -83,7 +84,7 @@ def translate_y(probability: float, magnitude: int) -> OperationBase:
def rotate(probability: float, magnitude: int) -> OperationBase:
"""Return rotate op."""
- magnitudes = linspace(-30, 30, 11)
+ magnitudes = torch.linspace(-30, 30, 11)
return Rotate(
None,
probability,
@@ -109,13 +110,13 @@ def equalize(probability: float, _: int) -> OperationBase:
def solarize(probability: float, magnitude: int) -> OperationBase:
"""Return solarize op."""
- magnitudes = linspace(0, 255, 11) / 255.0
+ magnitudes = torch.linspace(0, 255, 11) / 255.0
return Solarize(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
def posterize(probability: float, magnitude: int) -> OperationBase:
"""Return posterize op."""
- magnitudes = linspace(4, 8, 11)
+ magnitudes = torch.linspace(4, 8, 11)
return Posterize(
None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
)
@@ -123,13 +124,13 @@ def posterize(probability: float, magnitude: int) -> OperationBase:
def contrast(probability: float, magnitude: int) -> OperationBase:
"""Return contrast op."""
- magnitudes = linspace(0.1, 1.9, 11)
+ magnitudes = torch.linspace(0.1, 1.9, 11)
return Contrast(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
def brightness(probability: float, magnitude: int) -> OperationBase:
"""Return brightness op."""
- magnitudes = linspace(0.1, 1.9, 11)
+ magnitudes = torch.linspace(0.1, 1.9, 11)
return Brightness(
None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
)
@@ -137,7 +138,7 @@ def brightness(probability: float, magnitude: int) -> OperationBase:
def sharpness(probability: float, magnitude: int) -> OperationBase:
"""Return sharpness op."""
- magnitudes = linspace(0.1, 1.9, 11)
+ magnitudes = torch.linspace(0.1, 1.9, 11)
return Sharpness(
None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
)
@@ -145,5 +146,5 @@ def sharpness(probability: float, magnitude: int) -> OperationBase:
def color(probability: float, magnitude: int) -> OperationBase:
"""Return color op."""
- magnitudes = linspace(0.1, 1.9, 11)
+ magnitudes = torch.linspace(0.1, 1.9, 11)
return Saturate(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index ee3b1f6be..520bf9847 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -18,13 +18,13 @@
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
+from torch import nn
from kornia.augmentation.auto.operations.base import OperationBase
from kornia.augmentation.auto.operations.policy import PolicySequential
from kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn
from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
-from kornia.core import Module, Tensor
from kornia.utils import eye_like
NUMBER = Union[float, int]
@@ -55,21 +55,21 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
raise NotImplementedError
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
return eye_like(3, input)
def get_transformation_matrix(
self,
- input: Tensor,
+ input: torch.Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
extra_args: Optional[Dict[str, Any]] = None,
- ) -> Optional[Tensor]:
+ ) -> Optional[torch.Tensor]:
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -78,10 +78,10 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
# Define as 1 for broadcasting
- res_mat: Optional[Tensor] = None
+ res_mat: Optional[torch.Tensor] = None
for (_, module), param in zip(named_modules, params if params is not None else []):
module = cast(PolicySequential, module)
mat = module.get_transformation_matrix(
@@ -91,7 +91,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return res_mat
def is_intensity_only(self, params: Optional[List[ParamItem]] = None) -> bool:
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
for _, module in named_modules:
module = cast(PolicySequential, module)
if not module.is_intensity_only():
@@ -99,10 +99,10 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return True
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
- mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
for name, module in named_modules:
module = cast(OperationBase, module)
mod_param = module.forward_parameters(batch_shape)
@@ -111,16 +111,16 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return params
def transform_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
self.clear_state()
if params is None:
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 3dbed537f..868d9d55e 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -23,12 +23,11 @@ from torch.distributions import Bernoulli, RelaxedBernoulli
from typing_extensions import Self
from kornia.augmentation.base import _AugmentationBase
-from kornia.core import Module, Tensor
T = TypeVar("T", bound="OperationBase")
-class OperationBase(Module):
+class OperationBase(nn.Module):
"""Base class of differentiable augmentation operations.
Args:
@@ -49,7 +48,7 @@ class OperationBase(Module):
initial_magnitude: Optional[List[Tuple[str, Optional[float]]]] = None,
temperature: float = 0.1,
is_batch_operation: bool = False,
- magnitude_fn: Optional[Callable[[Tensor], Tensor]] = None,
+ magnitude_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
symmetric_megnitude: bool = False,
) -> None:
super().__init__()
@@ -75,12 +74,14 @@ class OperationBase(Module):
self.symmetric_megnitude = symmetric_megnitude
self._magnitude_fn = self._init_magnitude_fn(magnitude_fn)
- def _init_magnitude_fn(self, magnitude_fn: Optional[Callable[[Tensor], Tensor]]) -> Callable[[Tensor], Tensor]:
- def _identity(x: Tensor) -> Tensor:
+ def _init_magnitude_fn(
+ self, magnitude_fn: Optional[Callable[[torch.Tensor], torch.Tensor]]
+ ) -> Callable[[torch.Tensor], torch.Tensor]:
+ def _identity(x: torch.Tensor) -> torch.Tensor:
return x
- def _random_flip(fn: Callable[[Tensor], Tensor]) -> Callable[[Tensor], Tensor]:
- def f(x: Tensor) -> Tensor:
+ def _random_flip(fn: Callable[[torch.Tensor], torch.Tensor]) -> Callable[[torch.Tensor], torch.Tensor]:
+ def f(x: torch.Tensor) -> torch.Tensor:
flip = torch.rand((x.shape[0],), device=x.device) > 0.5
return fn(x) * flip
@@ -135,7 +136,9 @@ class OperationBase(Module):
def eval(self) -> Self:
return self.train(False)
- def forward_parameters(self, batch_shape: torch.Size, mag: Optional[Tensor] = None) -> Dict[str, Tensor]:
+ def forward_parameters(
+ self, batch_shape: torch.Size, mag: Optional[torch.Tensor] = None
+ ) -> Dict[str, torch.Tensor]:
if mag is None:
mag = self.magnitude
# Need to setup the sampler again for each update.
@@ -154,7 +157,7 @@ class OperationBase(Module):
return params
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None) -> torch.Tensor:
if params is None:
params = self.forward_parameters(input.shape)
@@ -163,13 +166,13 @@ class OperationBase(Module):
return batch_prob * self.op(input, params=params) + (1 - batch_prob) * input
@property
- def transform_matrix(self) -> Optional[Tensor]:
+ def transform_matrix(self) -> Optional[torch.Tensor]:
if hasattr(self.op, "transform_matrix"):
return self.op.transform_matrix
return None
@property
- def magnitude(self) -> Optional[Tensor]:
+ def magnitude(self) -> Optional[torch.Tensor]:
if self._magnitude is None:
return None
mag = self._magnitude
@@ -178,6 +181,6 @@ class OperationBase(Module):
return mag
@property
- def probability(self) -> Tensor:
+ def probability(self) -> torch.Tensor:
p = self._probability.clamp(*self.probability_range)
return p
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index db26a2d57..ddcd16f3c 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -17,9 +17,10 @@
from typing import Optional, Tuple
+import torch
+
import kornia.augmentation as K
from kornia.augmentation.auto.operations.base import OperationBase
-from kornia.core import Tensor
__all__ = [
"AutoContrast",
@@ -257,7 +258,7 @@ class Posterize(OperationBase):
"""
@staticmethod
- def _process_magnitude(magnitude: Tensor) -> Tensor:
+ def _process_magnitude(magnitude: torch.Tensor) -> torch.Tensor:
return magnitude.long()
def __init__(
@@ -449,7 +450,7 @@ class ShearX(OperationBase):
"""
@staticmethod
- def _process_magnitude(magnitude: Tensor) -> Tensor:
+ def _process_magnitude(magnitude: torch.Tensor) -> torch.Tensor:
# make it sign-agnostic
return magnitude * 180
@@ -489,7 +490,7 @@ class ShearY(OperationBase):
"""
@staticmethod
- def _process_magnitude(magnitude: Tensor) -> Tensor:
+ def _process_magnitude(magnitude: torch.Tensor) -> torch.Tensor:
# make it sign-agnostic
return magnitude * 180
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 362622585..efacc5b9b 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -17,7 +17,8 @@
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
-from torch import Size
+import torch
+from torch import Size, nn
import kornia.augmentation as K
from kornia.augmentation.auto.operations import OperationBase
@@ -25,7 +26,6 @@ from kornia.augmentation.container.base import ImageSequentialBase, TransformMat
from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
from kornia.augmentation.utils import _transform_input, override_parameters
-from kornia.core import Module, Tensor, as_tensor
from kornia.utils import eye_like
@@ -42,7 +42,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
super().__init__(*operations)
self._valid_ops_for_transform_computation: Tuple[Any, ...] = (OperationBase,)
- def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ def _update_transform_matrix_for_valid_op(self, module: nn.Module) -> None:
self._transform_matrices.append(module.transform_matrix)
def clear_state(self) -> None:
@@ -57,21 +57,21 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
if len(invalid_ops) != 0:
raise ValueError(f"All operations must be Kornia Operations. Got {invalid_ops}.")
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
return eye_like(3, input)
def get_transformation_matrix(
self,
- input: Tensor,
+ input: torch.Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
extra_args: Optional[Dict[str, Any]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -80,10 +80,10 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
# Define as 1 for broadcasting
- res_mat: Tensor = self.identity_matrix(_transform_input(input))
+ res_mat: torch.Tensor = self.identity_matrix(_transform_input(input))
for (_, module), param in zip(named_modules, params if params is not None else []):
module = cast(OperationBase, module)
if isinstance(module.op, (K.GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
@@ -94,7 +94,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
flags = override_parameters(module.op.flags, extra_args, in_place=False)
mat = module.op.generate_transformation_matrix(input, param.data, flags)
elif module.op._transform_matrix is not None:
- mat = as_tensor(module.transform_matrix, device=input.device, dtype=input.dtype)
+ mat = torch.as_tensor(module.transform_matrix, device=input.device, dtype=input.dtype)
else:
raise RuntimeError(f"{module}.transform_matrix is None while `recompute=False`.")
res_mat = mat @ res_mat
@@ -110,16 +110,16 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
return False
return True
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is not None:
return super().get_children_by_params(params)
return self.named_children()
def forward_parameters(self, batch_shape: Size) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
- mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
for name, module in named_modules:
module = cast(OperationBase, module)
mod_param = module.op.forward_parameters(batch_shape)
@@ -128,8 +128,8 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
return params
def transform_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index ac96b559b..a8d7eda09 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -18,12 +18,12 @@
from typing import Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
+from torch import nn
from kornia.augmentation.auto.base import SUBPOLICY_CONFIG, PolicyAugmentBase
from kornia.augmentation.auto.operations import OperationBase
from kornia.augmentation.auto.operations.policy import PolicySequential
from kornia.augmentation.container.params import ParamItem
-from kornia.core import Module, Tensor
from . import ops
@@ -90,7 +90,7 @@ class RandAugment(PolicyAugmentBase):
self.n = n
self.m = m
- def rand_selector(self, n: int) -> Tensor:
+ def rand_selector(self, n: int) -> torch.Tensor:
perm = torch.randperm(len(self._modules))
idx = perm[:n]
return idx
@@ -101,7 +101,7 @@ class RandAugment(PolicyAugmentBase):
name, low, high = subpolicy[0]
return PolicySequential(*[getattr(ops, name)(low, high)])
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is None:
idx = self.rand_selector(
self.n,
@@ -111,9 +111,9 @@ class RandAugment(PolicyAugmentBase):
return self.get_children_by_params(params)
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
- mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
m = torch.tensor([self.m / 30] * batch_shape[0])
for name, module in named_modules:
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 109d86551..7e8cc4dec 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -18,13 +18,13 @@
from typing import Iterator, List, Optional, Tuple
import torch
+from torch import nn
from torch.distributions import Categorical
from kornia.augmentation.auto.base import SUBPOLICY_CONFIG, PolicyAugmentBase
from kornia.augmentation.auto.operations.policy import PolicySequential
from kornia.augmentation.auto.rand_augment import ops
from kornia.augmentation.container.params import ParamItem
-from kornia.core import Module
default_policy: List[SUBPOLICY_CONFIG] = [
# [("identity", 0, 1)],
@@ -84,7 +84,7 @@ class TrivialAugment(PolicyAugmentBase):
name, low, high = subpolicy[0]
return PolicySequential(*[getattr(ops, name)(low, high)])
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is None:
idx = self.rand_selector.sample((1,))
return self.get_children_by_indices(idx)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 34bb67f4e..bdf15e6db 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -19,6 +19,7 @@ from enum import Enum
from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
+from torch import nn
from torch.distributions import Bernoulli, Distribution, RelaxedBernoulli
from kornia.augmentation.random_generator import RandomGeneratorBase
@@ -28,28 +29,26 @@ from kornia.augmentation.utils import (
_transform_output_shape,
override_parameters,
)
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, tensor, zeros
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.utils import is_autocast_enabled
-TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]
+TensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
# Trick mypy into not applying contravariance rules to inputs by defining
# forward as a value, rather than a function. See also
# https://github.com/python/mypy/issues/8795
# Based on the trick that torch.nn.Module does for the forward method
-def _apply_transform_unimplemented(self: Module, *input: Any) -> Tensor:
+def _apply_transform_unimplemented(self: nn.Module, *input: Any) -> torch.Tensor:
r"""Define the computation performed at every call.
Should be overridden by all subclasses.
"""
- raise NotImplementedError(f'Module [{type(self).__name__}] is missing the required "apply_tranform" function')
+ raise NotImplementedError(f'nn.Module [{type(self).__name__}] is missing the required "apply_tranform" function')
-class _BasicAugmentationBase(Module):
+class _BasicAugmentationBase(nn.Module):
r"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
@@ -87,7 +86,7 @@ class _BasicAugmentationBase(Module):
self.p_batch = p_batch
self.same_on_batch = same_on_batch
self.keepdim = keepdim
- self._params: Dict[str, Tensor] = {}
+ self._params: Dict[str, torch.Tensor] = {}
self._p_gen: Distribution
self._p_batch_gen: Distribution
if p != 0.0 or p != 1.0:
@@ -98,7 +97,7 @@ class _BasicAugmentationBase(Module):
self.flags: Dict[str, Any] = {}
self.set_rng_device_and_dtype(torch.device("cpu"), torch.get_default_dtype())
- apply_transform: Callable[..., Tensor] = _apply_transform_unimplemented
+ apply_transform: Callable[..., torch.Tensor] = _apply_transform_unimplemented
def to(self, *args: Any, **kwargs: Any) -> "_BasicAugmentationBase":
r"""Set the device and dtype for the random number generator."""
@@ -117,28 +116,28 @@ class _BasicAugmentationBase(Module):
txt += f", {k}={v}"
return f"{self.__class__.__name__}({txt})"
- def __unpack_input__(self, input: Tensor) -> Tensor:
+ def __unpack_input__(self, input: torch.Tensor) -> torch.Tensor:
return input
def transform_tensor(
self,
- input: Tensor,
+ input: torch.Tensor,
*,
- shape: Optional[Tensor] = None,
+ shape: Optional[torch.Tensor] = None,
match_channel: bool = True,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Standardize input tensors."""
raise NotImplementedError
- def validate_tensor(self, input: Tensor) -> None:
- """Check if the input tensor is formatted as expected."""
+ def validate_tensor(self, input: torch.Tensor) -> None:
+ """Check if the input torch.tensor is formatted as expected."""
raise NotImplementedError
- def transform_output_tensor(self, output: Tensor, output_shape: Tuple[int, ...]) -> Tensor:
+ def transform_output_tensor(self, output: torch.Tensor, output_shape: Tuple[int, ...]) -> torch.Tensor:
"""Standardize output tensors."""
return _transform_output_shape(output, output_shape) if self.keepdim else output
- def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
if self._param_generator is not None:
return self._param_generator(batch_shape, self.same_on_batch)
return {}
@@ -161,12 +160,12 @@ class _BasicAugmentationBase(Module):
p: float,
p_batch: float,
same_on_batch: bool,
- ) -> Tensor:
- batch_prob: Tensor
+ ) -> torch.Tensor:
+ batch_prob: torch.Tensor
if p_batch == 1:
- batch_prob = zeros(1) + 1
+ batch_prob = torch.zeros(1) + 1
elif p_batch == 0:
- batch_prob = zeros(1)
+ batch_prob = torch.zeros(1)
elif isinstance(self._p_batch_gen, (RelaxedBernoulli,)):
# NOTE: there is no simple way to know if the sampler has `rsample` or not
batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch)
@@ -174,11 +173,11 @@ class _BasicAugmentationBase(Module):
batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch)
if batch_prob.sum() == 1:
- elem_prob: Tensor
+ elem_prob: torch.Tensor
if p == 1:
- elem_prob = zeros(batch_shape[0]) + 1
+ elem_prob = torch.zeros(batch_shape[0]) + 1
elif p == 0:
- elem_prob = zeros(batch_shape[0])
+ elem_prob = torch.zeros(batch_shape[0])
elif isinstance(self._p_gen, (RelaxedBernoulli,)):
elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch)
else:
@@ -192,10 +191,10 @@ class _BasicAugmentationBase(Module):
def _process_kwargs_to_params_and_flags(
self,
- params: Optional[Dict[str, Tensor]] = None,
+ params: Optional[Dict[str, torch.Tensor]] = None,
flags: Optional[Dict[str, Any]] = None,
**kwargs: Any,
- ) -> Tuple[Dict[str, Tensor], Dict[str, Any]]:
+ ) -> Tuple[Dict[str, torch.Tensor], Dict[str, Any]]:
# NOTE: determine how to save self._params
save_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False
@@ -212,7 +211,7 @@ class _BasicAugmentationBase(Module):
flags = override_parameters(flags, kwargs, in_place=False)
return params, flags
- def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
+ def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
batch_prob = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
to_apply = batch_prob > 0.5
_params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
@@ -221,18 +220,20 @@ class _BasicAugmentationBase(Module):
_params["batch_prob"] = batch_prob
# Added another input_size parameter for geometric transformations
# This might be needed for correctly inversing.
- input_size = tensor(batch_shape, dtype=torch.long)
+ input_size = torch.tensor(batch_shape, dtype=torch.long)
_params.update({"forward_input_shape": input_size})
return _params
- def apply_func(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_func(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:
return self.apply_transform(input, params, flags)
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
+ def forward(
+ self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, **kwargs: Any
+ ) -> torch.Tensor:
"""Perform forward operations.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: the corresponding parameters for an operation.
If None, a new parameter suite will be generated.
**kwargs: key-value pairs to override the parameters and flags.
@@ -251,7 +252,7 @@ class _BasicAugmentationBase(Module):
params = self.forward_parameters(batch_shape)
if "batch_prob" not in params:
- params["batch_prob"] = tensor([True] * batch_shape[0])
+ params["batch_prob"] = torch.tensor([True] * batch_shape[0])
params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)
@@ -277,33 +278,33 @@ class _AugmentationBase(_BasicAugmentationBase):
def apply_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
- # apply transform for the input image tensor
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ # apply transform for the input image torch.tensor
raise NotImplementedError
def apply_non_transform(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
# apply additional transform for the images that are skipped from transformation
- # where batch_prob == False.
+ # torch.where batch_prob == False.
return input
def transform_inputs(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
)
@@ -318,7 +319,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
- else: # If any tensor needs to be transformed.
+ else: # If any torch.tensor needs to be transformed.
output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
applied = self.apply_transform(
in_tensor[to_apply],
@@ -340,12 +341,12 @@ class _AugmentationBase(_BasicAugmentationBase):
def transform_masks(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
)
@@ -362,7 +363,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
- else: # If any tensor needs to be transformed.
+ else: # If any torch.tensor needs to be transformed.
output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
applied = self.apply_transform_mask(
in_tensor[to_apply],
@@ -377,9 +378,9 @@ class _AugmentationBase(_BasicAugmentationBase):
def transform_boxes(
self,
input: Boxes,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Boxes:
if not isinstance(input, Boxes):
@@ -396,7 +397,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_box(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_box(input, params, flags, transform=transform)
- else: # If any tensor needs to be transformed.
+ else: # If any torch.tensor needs to be transformed.
output = self.apply_non_transform_box(input, params, flags, transform=transform)
applied = self.apply_transform_box(
input[to_apply],
@@ -414,9 +415,9 @@ class _AugmentationBase(_BasicAugmentationBase):
def transform_keypoints(
self,
input: Keypoints,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> Keypoints:
if not isinstance(input, Keypoints):
@@ -432,7 +433,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_keypoint(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
- else: # If any tensor needs to be transformed.
+ else: # If any torch.tensor needs to be transformed.
output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
applied = self.apply_transform_keypoint(
input[to_apply],
@@ -448,12 +449,12 @@ class _AugmentationBase(_BasicAugmentationBase):
def transform_classes(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
**kwargs: Any,
- ) -> Tensor:
+ ) -> torch.Tensor:
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
)
@@ -464,7 +465,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_class(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_class(input, params, flags, transform=transform)
- else: # If any tensor needs to be transformed.
+ else: # If any torch.tensor needs to be transformed.
output = self.apply_non_transform_class(input, params, flags, transform=transform)
applied = self.apply_transform_class(
input[to_apply],
@@ -477,30 +478,30 @@ class _AugmentationBase(_BasicAugmentationBase):
def apply_non_transform_mask(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process masks corresponding to the inputs that are no transformation applied."""
raise NotImplementedError
def apply_transform_mask(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process masks corresponding to the inputs that are transformed."""
raise NotImplementedError
def apply_non_transform_box(
self,
input: Boxes,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process boxes corresponding to the inputs that are no transformation applied."""
return input
@@ -508,9 +509,9 @@ class _AugmentationBase(_BasicAugmentationBase):
def apply_transform_box(
self,
input: Boxes,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
) -> Boxes:
"""Process boxes corresponding to the inputs that are transformed."""
raise NotImplementedError
@@ -518,9 +519,9 @@ class _AugmentationBase(_BasicAugmentationBase):
def apply_non_transform_keypoint(
self,
input: Keypoints,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
"""Process keypoints corresponding to the inputs that are no transformation applied."""
return input
@@ -528,39 +529,39 @@ class _AugmentationBase(_BasicAugmentationBase):
def apply_transform_keypoint(
self,
input: Keypoints,
- params: Dict[str, Tensor],
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
+ transform: Optional[torch.Tensor] = None,
) -> Keypoints:
"""Process keypoints corresponding to the inputs that are transformed."""
raise NotImplementedError
def apply_non_transform_class(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process class tags corresponding to the inputs that are no transformation applied."""
return input
def apply_transform_class(
self,
- input: Tensor,
- params: Dict[str, Tensor],
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Dict[str, Any],
- transform: Optional[Tensor] = None,
- ) -> Tensor:
+ transform: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Process class tags corresponding to the inputs that are transformed."""
raise NotImplementedError
def apply_func(
self,
- in_tensor: Tensor,
- params: Dict[str, Tensor],
+ in_tensor: torch.Tensor,
+ params: Dict[str, torch.Tensor],
flags: Optional[Dict[str, Any]] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
if flags is None:
flags = self.flags
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 3e10fb0fa..8366f326a 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -19,12 +19,12 @@ import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
import torch
+from torch import nn
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey, Resample
-from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
from kornia.utils import eye_like, is_autocast_enabled
@@ -44,7 +44,7 @@ _IMG_OPTIONS = {DataKey.INPUT, DataKey.IMAGE}
_MSK_OPTIONS = {DataKey.MASK}
_CLS_OPTIONS = {DataKey.CLASS, DataKey.LABEL}
-MaskDataType = Union[Tensor, List[Tensor]]
+MaskDataType = Union[torch.Tensor, List[torch.Tensor]]
class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
@@ -234,8 +234,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
transformation_matrix_mode: str = "silent",
extra_args: Optional[Dict[DataKey, Dict[str, Any]]] = None,
) -> None:
- self._transform_matrix: Optional[Tensor]
- self._transform_matrices: List[Optional[Tensor]] = []
+ self._transform_matrix: Optional[torch.Tensor]
+ self._transform_matrices: List[Optional[torch.Tensor]] = []
super().__init__(
*args,
@@ -287,10 +287,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self._reset_transform_matrix_state()
return super().clear_state()
- def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ def _update_transform_matrix_for_valid_op(self, module: nn.Module) -> None:
self._transform_matrices.append(module.transform_matrix)
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
if self.contains_3d_augmentation:
return eye_like(4, input)
@@ -364,15 +364,15 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
inp: List[DataType] = []
for arg, dcate in zip(args, data_keys):
if DataKey.get(dcate) in _IMG_OPTIONS:
- arg = cast(Tensor, arg)
+ arg = cast(torch.Tensor, arg)
self.input_dtype = arg.dtype
inp.append(arg)
elif DataKey.get(dcate) in _MSK_OPTIONS:
if isinstance(inp, list):
- arg = cast(List[Tensor], arg)
+ arg = cast(List[torch.Tensor], arg)
self.mask_dtype = arg[0].dtype
else:
- arg = cast(Tensor, arg)
+ arg = cast(torch.Tensor, arg)
self.mask_dtype = arg.dtype
inp.append(self._preproc_mask(arg))
elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:
@@ -391,7 +391,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
out: List[DataType] = []
for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys):
if DataKey.get(dcate) in _IMG_OPTIONS:
- # It is tensor type already.
+ # It is torch.tensor type already.
out.append(out_arg)
# TODO: may add the float to integer (for masks), etc.
elif DataKey.get(dcate) in _MSK_OPTIONS:
@@ -400,7 +400,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:
_out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)
- if is_autocast_enabled() and isinstance(in_arg, (Tensor, Keypoints)):
+ if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Keypoints)):
if isinstance(_out_k, list):
_out_k = [i.type(in_arg.dtype) for i in _out_k]
else:
@@ -409,7 +409,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
elif DataKey.get(dcate) in _BOXES_OPTIONS:
_out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)
- if is_autocast_enabled() and isinstance(in_arg, (Tensor, Boxes)):
+ if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Boxes)):
if isinstance(_out_b, list):
_out_b = [i.type(in_arg.dtype) for i in _out_b]
else:
@@ -448,8 +448,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# image data must exist if params is not provided.
if DataKey.INPUT in self.transform_op.data_keys:
inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
- if not isinstance(inp, (Tensor,)):
- raise ValueError(f"`INPUT` should be a tensor but `{type(inp)}` received.")
+ if not isinstance(inp, (torch.Tensor,)):
+ raise ValueError(f"`INPUT` should be a torch.tensor but `{type(inp)}` received.")
# A video input shall be BCDHW while an image input shall be BCHW
if self.contains_video_sequential or self.contains_3d_augmentation:
_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
@@ -459,7 +459,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
else:
raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
- outputs: Union[Tensor, List[DataType]] = in_args
+ outputs: Union[torch.Tensor, List[DataType]] = in_args
for param in params:
module = self.get_submodule(param.name)
outputs = self.transform_op.transform( # type: ignore
@@ -491,7 +491,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self,
*inputs: Any,
input_names_to_handle: Optional[List[Any]] = None,
- output_type: str = "tensor",
+ output_type: str = "torch.tensor",
**kwargs: Any,
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
@@ -499,7 +499,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('torch.tensor', 'numpy', or 'pil').
kwargs: Additional arguments.
Returns:
@@ -525,7 +525,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if len(data_keys) > 1 and DataKey.INPUT in data_keys:
# NOTE: we may update it later for more supports of drawing boxes, etc.
idx = data_keys.index(DataKey.INPUT)
- if output_type == "tensor":
+ if output_type == "torch.tensor":
self._output_image = _output_image
if isinstance(_output_image, dict):
self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
@@ -619,15 +619,17 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if isinstance(arg, (Boxes,)):
return arg
elif self.contains_video_sequential:
- arg = cast(Tensor, arg)
+ arg = cast(torch.Tensor, arg)
return VideoBoxes.from_tensor(arg)
elif self.contains_3d_augmentation:
raise NotImplementedError("3D box handlers are not yet supported.")
else:
- arg = cast(Tensor, arg)
+ arg = cast(torch.Tensor, arg)
return Boxes.from_tensor(arg, mode=mode)
- def _postproc_boxes(self, in_arg: DataType, out_arg: Boxes, dcate: DataKey) -> Union[Tensor, List[Tensor], Boxes]:
+ def _postproc_boxes(
+ self, in_arg: DataType, out_arg: Boxes, dcate: DataKey
+ ) -> Union[torch.Tensor, List[torch.Tensor], Boxes]:
if DataKey.get(dcate) in [DataKey.BBOX]:
mode = "vertices_plus"
elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]:
@@ -647,7 +649,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
dtype = None
if self.contains_video_sequential:
- arg = cast(Union[Tensor, List[Tensor]], arg)
+ arg = cast(Union[torch.Tensor, List[torch.Tensor]], arg)
if isinstance(arg, list):
if not torch.is_floating_point(arg[0]):
dtype = arg[0].dtype
@@ -662,17 +664,17 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
elif isinstance(arg, (Keypoints,)):
return arg
else:
- arg = cast(Tensor, arg)
+ arg = cast(torch.Tensor, arg)
if not torch.is_floating_point(arg):
dtype = arg.dtype
arg = arg.float()
- # TODO: Add List[Tensor] in the future.
+ # TODO: Add List[torch.Tensor] in the future.
result = Keypoints.from_tensor(arg)
return result.type(dtype) if dtype else result
def _postproc_keypoint(
self, in_arg: DataType, out_arg: Keypoints, dcate: DataKey
- ) -> Union[Tensor, List[Tensor], Keypoints]:
+ ) -> Union[torch.Tensor, List[torch.Tensor], Keypoints]:
if isinstance(in_arg, (Keypoints,)):
return out_arg
else:
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 43595827a..751f76b78 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -24,7 +24,6 @@ from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -42,17 +41,17 @@ class BasicSequentialBase(nn.Sequential):
"""
- def __init__(self, *args: Module) -> None:
+ def __init__(self, *args: nn.Module) -> None:
# To name the modules properly
_args = OrderedDict()
for idx, mod in enumerate(args):
- if not isinstance(mod, Module):
- raise NotImplementedError(f"Only Module are supported at this moment. Got {mod}.")
+ if not isinstance(mod, nn.Module):
+ raise NotImplementedError(f"Only nn.Module are supported at this moment. Got {mod}.")
_args.update({f"{mod.__class__.__name__}_{idx}": mod})
super().__init__(_args)
self._params: Optional[List[ParamItem]] = None
- def get_submodule(self, target: str) -> Module:
+ def get_submodule(self, target: str) -> nn.Module:
"""Get submodule.
This code is taken from torch 1.9.0 since it is not introduced
@@ -65,12 +64,12 @@ class BasicSequentialBase(nn.Sequential):
fully-qualified string.)
Returns:
- Module: The submodule referenced by ``target``
+ nn.Module: The submodule referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not an
- ``Module``
+ ``nn.Module``
"""
if len(target) == 0:
@@ -85,8 +84,8 @@ class BasicSequentialBase(nn.Sequential):
mod = getattr(mod, item)
- if not isinstance(mod, Module):
- raise AttributeError("`" + item + "` is not an Module")
+ if not isinstance(mod, nn.Module):
+ raise AttributeError("`" + item + "` is not an nn.Module")
return mod
@@ -98,18 +97,18 @@ class BasicSequentialBase(nn.Sequential):
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
raise NotImplementedError
- def get_children_by_indices(self, indices: Tensor) -> Iterator[Tuple[str, Module]]:
+ def get_children_by_indices(self, indices: torch.Tensor) -> Iterator[Tuple[str, nn.Module]]:
modules = list(self.named_children())
for idx in indices:
yield modules[idx]
- def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, Module]]:
+ def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, nn.Module]]:
modules = list(self.named_children())
# TODO: Wrong params passed here when nested ImageSequential
for param in params:
yield modules[list(dict(self.named_children()).keys()).index(param.name)]
- def get_params_by_module(self, named_modules: Iterator[Tuple[str, Module]]) -> Iterator[ParamItem]:
+ def get_params_by_module(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> Iterator[ParamItem]:
# This will not take module._params
for name, _ in named_modules:
yield ParamItem(name, None)
@@ -129,7 +128,7 @@ class SequentialBase(BasicSequentialBase):
"""
- def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:
+ def __init__(self, *args: nn.Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:
# To name the modules properly
super().__init__(*args)
self._same_on_batch = same_on_batch
@@ -170,10 +169,10 @@ class SequentialBase(BasicSequentialBase):
self._keepdim = keepdim
self.update_attribute(keepdim=keepdim)
- def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
- """Fill tensor dim to the upper bound of dim_range.
+ def autofill_dim(self, input: torch.Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
+ """Fill torch.tensor dim to the upper bound of dim_range.
- If input tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.
+ If input torch.tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.
"""
ori_shape = input.shape
if len(ori_shape) < dim_range[0] or len(ori_shape) > dim_range[1]:
@@ -184,21 +183,21 @@ class SequentialBase(BasicSequentialBase):
class ImageSequentialBase(SequentialBase):
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
raise NotImplementedError
def get_transformation_matrix(
self,
- input: Tensor,
+ input: torch.Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
extra_args: Optional[Dict[str, Any]] = None,
- ) -> Optional[Tensor]:
+ ) -> Optional[torch.Tensor]:
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -209,36 +208,36 @@ class ImageSequentialBase(SequentialBase):
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
raise NotImplementedError
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
"""Get module sequence by input params."""
raise NotImplementedError
def transform_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
def inverse_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
def transform_masks(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for param in params:
module = self.get_submodule(param.name)
input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
def inverse_masks(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
@@ -274,11 +273,11 @@ class ImageSequentialBase(SequentialBase):
return input
def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if params is None:
@@ -294,8 +293,8 @@ class ImageSequentialBase(SequentialBase):
return input
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
self.clear_state()
if params is None:
@@ -317,8 +316,8 @@ class TransformMatrixMinIn:
def __init__(self, *args, **kwargs) -> None: # type:ignore
super().__init__(*args, **kwargs)
- self._transform_matrix: Optional[Tensor] = None
- self._transform_matrices: List[Optional[Tensor]] = []
+ self._transform_matrix: Optional[torch.Tensor] = None
+ self._transform_matrices: List[Optional[torch.Tensor]] = []
def _parse_transformation_matrix_mode(self, transformation_matrix_mode: str) -> None:
_valid_transformation_matrix_args = {"silence", "silent", "rigid", "skip"}
@@ -330,7 +329,7 @@ class TransformMatrixMinIn:
self._transformation_matrix_arg = transformation_matrix_mode
@property
- def transform_matrix(self) -> Optional[Tensor]:
+ def transform_matrix(self) -> Optional[torch.Tensor]:
# In AugmentationSequential, the parent class is accessed first.
# So that it was None in the beginning. We hereby use lazy computation here.
if self._transform_matrix is None and len(self._transform_matrices) != 0:
@@ -339,10 +338,10 @@ class TransformMatrixMinIn:
self._update_transform_matrix(mat)
return self._transform_matrix
- def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ def _update_transform_matrix_for_valid_op(self, module: nn.Module) -> None:
raise NotImplementedError(module)
- def _update_transform_matrix_by_module(self, module: Module) -> None:
+ def _update_transform_matrix_by_module(self, module: nn.Module) -> None:
if self._transformation_matrix_arg == "skip":
return
if isinstance(module, self._valid_ops_for_transform_computation):
@@ -353,7 +352,7 @@ class TransformMatrixMinIn:
"Please either update the module or change the `transformation_matrix` argument."
)
- def _update_transform_matrix(self, transform_matrix: Optional[Tensor]) -> None:
+ def _update_transform_matrix(self, transform_matrix: Optional[torch.Tensor]) -> None:
if self._transform_matrix is None:
self._transform_matrix = transform_matrix
else:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 525ba9cb2..6054548b0 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -18,11 +18,12 @@
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
+from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import override_parameters
-from kornia.core import ImageModule, Module, Tensor, as_tensor
+from kornia.core import ImageModule
from kornia.core.module import ImageModuleMixIn
from kornia.utils import eye_like
@@ -43,14 +44,14 @@ class ImageModuleForSequentialMixIn(ImageModuleMixIn):
def disable_features(self, value: bool = True) -> None:
self._disable_features = value
- def disable_item_features(self, *args: Module) -> None:
+ def disable_item_features(self, *args: nn.Module) -> None:
for arg in args:
- if isinstance(arg, (ImageModule,)):
+ if isinstance(arg, ImageModule):
arg.disable_features = True
class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
- r"""Sequential for creating kornia image processing pipeline.
+ r"""nn.Sequential for creating kornia image processing pipeline.
Args:
*args : a list of kornia augmentation and image operation modules.
@@ -115,7 +116,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
def __init__(
self,
- *args: Module,
+ *args: nn.Module,
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
@@ -136,40 +137,40 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
"The length of `random_apply_weights` must be as same as the number of operations."
f"Got {len(random_apply_weights)} and {len(self)}."
)
- self.random_apply_weights = as_tensor(random_apply_weights or torch.ones((len(self),)))
+ self.random_apply_weights = torch.as_tensor(random_apply_weights or torch.ones((len(self),)))
self.if_unsupported_ops = if_unsupported_ops
def _read_random_apply(
self, random_apply: Union[int, bool, Tuple[int, int]], max_length: int
) -> Union[Tuple[int, int], bool]:
"""Process the scenarios for random apply."""
- if isinstance(random_apply, (bool,)) and random_apply is False:
+ if isinstance(random_apply, bool) and random_apply is False:
random_apply = False
- elif isinstance(random_apply, (bool,)) and random_apply is True:
+ elif isinstance(random_apply, bool) and random_apply is True:
random_apply = (max_length, max_length + 1)
- elif isinstance(random_apply, (int,)):
+ elif isinstance(random_apply, int):
random_apply = (random_apply, random_apply + 1)
elif (
- isinstance(random_apply, (tuple,))
+ isinstance(random_apply, tuple)
and len(random_apply) == 2
- and isinstance(random_apply[0], (int,))
- and isinstance(random_apply[1], (int,))
+ and isinstance(random_apply[0], int)
+ and isinstance(random_apply[1], int)
):
random_apply = (random_apply[0], random_apply[1] + 1)
- elif isinstance(random_apply, (tuple,)) and len(random_apply) == 1 and isinstance(random_apply[0], (int,)):
+ elif isinstance(random_apply, tuple) and len(random_apply) == 1 and isinstance(random_apply[0], int):
random_apply = (random_apply[0], max_length + 1)
else:
raise ValueError(f"Non-readable random_apply. Got {random_apply}.")
if random_apply is not False and not (
- isinstance(random_apply, (tuple,))
+ isinstance(random_apply, tuple)
and len(random_apply) == 2
- and isinstance(random_apply[0], (int,))
- and isinstance(random_apply[0], (int,))
+ and isinstance(random_apply[0], int)
+ and isinstance(random_apply[1], int)
):
raise AssertionError(f"Expect a tuple of (int, int). Got {random_apply}.")
return random_apply
- def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, Module]], bool]:
+ def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:
"""Get a forward sequence when random apply is in need.
Args:
@@ -206,7 +207,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
return self.get_children_by_indices(indices), mix_added
- def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, Module]]) -> List[int]:
+ def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> List[int]:
"""Get all the mix augmentations since they are label-involved.
Special operations needed for label-involved augmentations.
@@ -214,7 +215,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
# NOTE: MixV2 will not be a special op in the future.
return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, K.MixAugmentationBaseV2)]
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is None:
# Mix augmentation can only be applied once per forward
mix_indices = self.get_mix_augmentation_indices(self.named_children())
@@ -233,12 +234,12 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
return self.get_children_by_params(params)
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
- mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
for name, module in named_modules:
- if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2, ImageSequentialBase)):
+ if isinstance(module, (_AugmentationBase | K.MixAugmentationBaseV2 | ImageSequentialBase)):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
else:
@@ -247,21 +248,21 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
params.append(param)
return params
- def identity_matrix(self, input: Tensor) -> Tensor:
+ def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
return eye_like(3, input)
def get_transformation_matrix(
self,
- input: Tensor,
+ input: torch.Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
extra_args: Optional[Dict[str, Any]] = None,
- ) -> Optional[Tensor]:
+ ) -> Optional[torch.Tensor]:
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input tensor.
+ input: the input torch.tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -271,12 +272,12 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
raise NotImplementedError("requires params to be provided.")
if extra_args is None:
extra_args = {}
- named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
# Define as 1 for broadcasting
- res_mat: Optional[Tensor] = None
+ res_mat: Optional[torch.Tensor] = None
for (_, module), param in zip(named_modules, params if params is not None else []):
- if isinstance(module, (K.GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
+ if isinstance(module, K.GeometricAugmentationBase2D) and isinstance(param.data, dict):
ori_shape = input.shape
try:
input = module.transform_tensor(input)
@@ -288,17 +289,17 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
flags = override_parameters(module.flags, extra_args, in_place=False)
mat = module.generate_transformation_matrix(input, param.data, flags)
elif module._transform_matrix is not None:
- mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ mat = torch.as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
else:
raise RuntimeError(f"{module}._transform_matrix is None while `recompute=False`.")
res_mat = mat if res_mat is None else mat @ res_mat
input = module.transform_output_tensor(input, ori_shape)
if module.keepdim and ori_shape != input.shape:
res_mat = res_mat.squeeze()
- elif isinstance(module, (ImageSequentialBase,)):
+ elif isinstance(module, ImageSequentialBase):
# If not augmentationSequential
- if isinstance(module, (K.AugmentationSequential,)) and not recompute:
- mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ if isinstance(module, K.AugmentationSequential) and not recompute:
+ mat = torch.as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
else:
maybe_param_data = cast(Optional[List[ParamItem]], param.data)
_mat = module.get_transformation_matrix(
@@ -321,9 +322,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
"""
for arg in self.children():
- if isinstance(arg, (ImageSequential,)) and not arg.is_intensity_only(strict):
+ if isinstance(arg, ImageSequential) and not arg.is_intensity_only(strict):
return False
- elif isinstance(arg, (ImageSequential,)):
+ elif isinstance(arg, ImageSequential):
pass
elif isinstance(arg, K.IntensityAugmentationBase2D):
pass
@@ -384,9 +385,9 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
batch_shape = _get_new_batch_shape(p, batch_shape)
return batch_shape
- # Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element tensor
+ # Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.tensor
if "output_size" in data:
- # Inline check for common PyTorch float tensor case
+ # Inline check for common PyTorch float torch.tensor case
batch_prob = data.get("batch_prob", None)
if batch_prob is not None:
# Avoid repeated indexing, always fetch scalar efficiently
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 4fb2b52ab..ce9eb231a 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -19,21 +19,22 @@ import copy
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union
+import torch
+from torch import nn
from typing_extensions import ParamSpec
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey
-from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from .params import ParamItem
-DataType = Union[Tensor, List[Tensor], Boxes, Keypoints]
+DataType = Union[torch.Tensor, List[torch.Tensor], Boxes, Keypoints]
# NOTE: shouldn't this SequenceDataType alias be equals to List[DataType]?
-SequenceDataType = Union[List[Tensor], List[List[Tensor]], List[Boxes], List[Keypoints]]
+SequenceDataType = Union[List[torch.Tensor], List[List[torch.Tensor]], List[Boxes], List[Keypoints]]
T = TypeVar("T")
@@ -42,7 +43,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
"""Abstract interface for applying and inversing transformations."""
@classmethod
- def get_instance_module_param(cls, param: ParamItem) -> Dict[str, Tensor]:
+ def get_instance_module_param(cls, param: ParamItem) -> Dict[str, torch.Tensor]:
if isinstance(param, ParamItem) and isinstance(param.data, dict):
_params = param.data
else:
@@ -59,12 +60,12 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
@abstractmethod
- def transform(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
+ def transform(cls, input: T, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
"""Apply a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -73,12 +74,12 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
@abstractmethod
- def inverse(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
+ def inverse(cls, input: T, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -105,7 +106,7 @@ class AugmentationSequentialOps:
if data_keys is None:
if isinstance(self.data_keys, list):
return self.data_keys
- raise ValueError("Sequential ops needs data keys to be able to process.")
+ raise ValueError("nn.Sequential ops needs data keys to be able to process.")
else:
return [DataKey.get(inp) for inp in data_keys]
@@ -126,7 +127,7 @@ class AugmentationSequentialOps:
def transform(
self,
*arg: DataType,
- module: Module,
+ module: nn.Module,
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
@@ -160,7 +161,7 @@ class AugmentationSequentialOps:
def inverse(
self,
*arg: DataType,
- module: Module,
+ module: nn.Module,
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
@@ -179,10 +180,10 @@ class AugmentationSequentialOps:
P = ParamSpec("P")
-def make_input_only_sequential(module: "K.container.ImageSequentialBase") -> Callable[P, Tensor]:
+def make_input_only_sequential(module: "K.container.ImageSequentialBase") -> Callable[P, torch.Tensor]:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
- def f(*args: P.args, **kwargs: P.kwargs) -> Tensor:
+ def f(*args: P.args, **kwargs: P.kwargs) -> torch.Tensor:
return module(*args, **kwargs)
return f
@@ -199,11 +200,11 @@ def get_geometric_only_param(module: "K.container.ImageSequentialBase", param: L
return res
-class InputSequentialOps(SequentialOpsInterface[Tensor]):
+class InputSequentialOps(SequentialOpsInterface[torch.Tensor]):
@classmethod
def transform(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if extra_args is None:
extra_args = {}
if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
@@ -220,8 +221,8 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def inverse(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if extra_args is None:
extra_args = {}
if isinstance(module, K.GeometricAugmentationBase2D):
@@ -239,13 +240,13 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):
return input
-class ClassSequentialOps(SequentialOpsInterface[Tensor]):
+class ClassSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""Apply and inverse transformations for class labels if needed."""
@classmethod
def transform(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if isinstance(module, K.MixAugmentationBaseV2):
raise NotImplementedError(
"The support for class labels for mix augmentations that change the class label is not yet supported."
@@ -254,23 +255,23 @@ class ClassSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def inverse(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
return input
-class MaskSequentialOps(SequentialOpsInterface[Tensor]):
+class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""Apply and inverse transformations for mask tensors."""
@classmethod
def transform(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
"""Apply a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -313,13 +314,13 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def transform_list(
- cls, input: List[Tensor], module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> List[Tensor]:
+ cls, input: List[torch.Tensor], module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> List[torch.Tensor]:
"""Apply a transformation with respect to the parameters.
Args:
input: list of input tensors.
- module: any torch Module but only kornia augmentation modules will count
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -378,13 +379,13 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def inverse(
- cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -426,13 +427,13 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
@classmethod
def transform(
- cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ cls, input: Boxes, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
"""Apply a transformation with respect to the parameters.
Args:
- input: the input tensor, (B, N, 4, 2) or (B, 4, 2).
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor, (B, N, 4, 2) or (B, 4, 2).
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -472,13 +473,13 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
@classmethod
def inverse(
- cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ cls, input: Boxes, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -523,13 +524,13 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
@classmethod
def transform(
- cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ cls, input: Keypoints, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
"""Apply a transformation with respect to the parameters.
Args:
- input: the input tensor, (B, N, 4, 2) or (B, 4, 2).
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor, (B, N, 4, 2) or (B, 4, 2).
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -570,13 +571,13 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
@classmethod
def inverse(
- cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ cls, input: Keypoints, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
+ input: the input torch.tensor.
+ module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
diff --git a/kornia/augmentation/container/params.py b/kornia/augmentation/container/params.py
index bd0aa042d..50d4e72d8 100644
--- a/kornia/augmentation/container/params.py
+++ b/kornia/augmentation/container/params.py
@@ -17,14 +17,14 @@
from typing import Dict, List, NamedTuple, Optional, Union
-from kornia.core import Tensor
+import torch
__all__ = ["ParamItem", "PatchParamItem"]
class ParamItem(NamedTuple):
name: str
- data: Optional[Union[Dict[str, Tensor], List["ParamItem"]]]
+ data: Optional[Union[Dict[str, torch.Tensor], List["ParamItem"]]]
class PatchParamItem(NamedTuple):
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index b0b8d8c48..821fd6052 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -19,12 +19,12 @@ from itertools import cycle, islice
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import torch
+import torch.nn.functional as F
+from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.contrib.extract_patches import extract_tensor_patches
-from kornia.core import Module, Tensor, concatenate
-from kornia.core import pad as fpad
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -50,8 +50,8 @@ class PatchSequential(ImageSequential):
Args:
*args: a list of processing modules.
grid_size: controls the grid board separation.
- padding: same or valid padding. If same padding, it will pad to include all pixels if the input
- tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed.
+ padding: same or valid padding. If same padding, it will F.pad to include all pixels if the input
+ torch.tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -129,7 +129,7 @@ class PatchSequential(ImageSequential):
def __init__(
self,
- *args: Module,
+ *args: nn.Module,
grid_size: Tuple[int, int] = (4, 4),
padding: str = "same",
same_on_batch: Optional[bool] = None,
@@ -170,7 +170,7 @@ class PatchSequential(ImageSequential):
self._params: Optional[List[PatchParamItem]] # type: ignore[assignment]
def compute_padding(
- self, input: Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
+ self, input: torch.Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
) -> Tuple[int, int, int, int]:
if grid_size is None:
grid_size = self.grid_size
@@ -185,11 +185,11 @@ class PatchSequential(ImageSequential):
def extract_patches(
self,
- input: Tensor,
+ input: torch.Tensor,
grid_size: Optional[Tuple[int, int]] = None,
pad: Optional[Tuple[int, int, int, int]] = None,
- ) -> Tensor:
- """Extract patches from tensor.
+ ) -> torch.Tensor:
+ """Extract patches from torch.tensor.
Example:
>>> import kornia.augmentation as K
@@ -223,7 +223,7 @@ class PatchSequential(ImageSequential):
"""
if pad is not None:
- input = fpad(input, list(pad))
+ input = F.pad(input, list(pad))
if grid_size is None:
grid_size = self.grid_size
window_size = (input.size(-2) // grid_size[-2], input.size(-1) // grid_size[-1])
@@ -231,8 +231,11 @@ class PatchSequential(ImageSequential):
return extract_tensor_patches(input, window_size, stride)
def restore_from_patches(
- self, patches: Tensor, grid_size: Tuple[int, int] = (4, 4), pad: Optional[Tuple[int, int, int, int]] = None
- ) -> Tensor:
+ self,
+ patches: torch.Tensor,
+ grid_size: Tuple[int, int] = (4, 4),
+ pad: Optional[Tuple[int, int, int, int]] = None,
+ ) -> torch.Tensor:
"""Restore input from patches.
Example:
@@ -249,11 +252,11 @@ class PatchSequential(ImageSequential):
if grid_size is None:
grid_size = self.grid_size
patches_tensor = patches.view(-1, grid_size[0], grid_size[1], *patches.shape[-3:])
- restored_tensor = concatenate(torch.chunk(patches_tensor, grid_size[0], 1), -2).squeeze(1)
- restored_tensor = concatenate(torch.chunk(restored_tensor, grid_size[1], 1), -1).squeeze(1)
+ restored_tensor = torch.cat(torch.chunk(patches_tensor, grid_size[0], 1), -2).squeeze(1)
+ restored_tensor = torch.cat(torch.chunk(restored_tensor, grid_size[1], 1), -1).squeeze(1)
if pad is not None:
- restored_tensor = fpad(restored_tensor, [-i for i in pad])
+ restored_tensor = F.pad(restored_tensor, [-i for i in pad])
return restored_tensor
def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override]
@@ -318,7 +321,7 @@ class PatchSequential(ImageSequential):
else:
yield ParamItem(s[0], None), i
- def forward_by_params(self, input: Tensor, params: List[PatchParamItem]) -> Tensor:
+ def forward_by_params(self, input: torch.Tensor, params: List[PatchParamItem]) -> torch.Tensor:
in_shape = input.shape
input = input.reshape(-1, *in_shape[-3:])
@@ -332,8 +335,8 @@ class PatchSequential(ImageSequential):
return input.reshape(in_shape)
def transform_inputs( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
pad = self.compute_padding(input, self.padding)
input = self.extract_patches(input, self.grid_size, pad)
input = self.forward_by_params(input, params)
@@ -342,24 +345,24 @@ class PatchSequential(ImageSequential):
return input
def inverse_inputs( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if self.is_intensity_only():
return input
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def transform_masks( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if self.is_intensity_only():
return input
raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
def inverse_masks( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
if self.is_intensity_only():
return input
@@ -398,11 +401,14 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def inverse( # type: ignore[override]
- self, input: Tensor, params: Optional[List[PatchParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self,
+ input: torch.Tensor,
+ params: Optional[List[PatchParamItem]] = None,
+ extra_args: Optional[Dict[str, Any]] = None,
+ ) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if self.is_intensity_only():
@@ -410,7 +416,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def forward(self, input: Tensor, params: Optional[List[PatchParamItem]] = None) -> Tensor: # type: ignore[override]
+ def forward(self, input: torch.Tensor, params: Optional[List[PatchParamItem]] = None) -> torch.Tensor: # type: ignore[override]
"""Input transformation will be returned if input is a tuple."""
# BCHW -> B(patch)CHW
if isinstance(input, (tuple,)):
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 387e363d5..6f3822a9c 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -18,12 +18,12 @@
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import torch
+from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.image import ImageSequential, _get_new_batch_shape
-from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -118,7 +118,7 @@ class VideoSequential(ImageSequential):
def __init__(
self,
- *args: Module,
+ *args: nn.Module,
data_format: str = "BTCHW",
same_on_frame: bool = True,
random_apply: Union[int, bool, Tuple[int, int]] = False,
@@ -145,7 +145,7 @@ class VideoSequential(ImageSequential):
# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")
return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :])
- def __repeat_param_across_channels__(self, param: Tensor, frame_num: int) -> Tensor:
+ def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:
"""Repeat parameters across channels.
The input is shaped as (B, ...), while to output (B * same_on_frame, ...), which
@@ -158,8 +158,8 @@ class VideoSequential(ImageSequential):
return repeated.reshape(-1, *list(param.shape[1:]))
def __broadcast_param__(
- self, v: Tensor, batch_shape: torch.Size, frame_num: int, same_on_frame: bool, same_on_batch: bool
- ) -> Tensor:
+ self, v: torch.Tensor, batch_shape: torch.Size, frame_num: int, same_on_frame: bool, same_on_batch: bool
+ ) -> torch.Tensor:
if not v.numel():
return v
@@ -171,7 +171,7 @@ class VideoSequential(ImageSequential):
return v.unsqueeze(1).repeat(1, batch_shape[0], *([1] * (v.ndim - 1))).reshape(-1, *v.shape[1:])
return v
- def _input_shape_convert_in(self, input: Tensor, frame_num: int) -> Tensor:
+ def _input_shape_convert_in(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:
# Convert any shape to (B, T, C, H, W)
if self.data_format == "BCTHW":
# Convert (B, C, T, H, W) to (B, T, C, H, W)
@@ -182,7 +182,7 @@ class VideoSequential(ImageSequential):
input = input.reshape(-1, *input.shape[2:])
return input
- def _input_shape_convert_back(self, input: Tensor, frame_num: int) -> Tensor:
+ def _input_shape_convert_back(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:
input = input.view(-1, frame_num, *input.shape[1:])
if self.data_format == "BCTHW":
input = input.transpose(1, 2)
@@ -230,7 +230,7 @@ class VideoSequential(ImageSequential):
elif isinstance(module, (SequentialBase,)):
seq_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
- raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
+ raise ValueError("nn.Sequential is currently unsupported for ``same_on_frame``.")
param = ParamItem(name, seq_param)
else:
@@ -242,8 +242,8 @@ class VideoSequential(ImageSequential):
return params
def transform_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -253,8 +253,8 @@ class VideoSequential(ImageSequential):
return input
def inverse_inputs(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -264,8 +264,8 @@ class VideoSequential(ImageSequential):
return input
def transform_masks(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -275,8 +275,8 @@ class VideoSequential(ImageSequential):
return input
def inverse_masks(
- self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -286,17 +286,17 @@ class VideoSequential(ImageSequential):
return input
def transform_boxes( # type: ignore[override]
- self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Union[Tensor, Boxes]:
+ self, input: Union[torch.Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Union[torch.Tensor, Boxes]:
"""Transform bounding boxes.
Args:
- input: tensor with shape :math:`(B, T, N, 4, 2)`.
+ input: torch.tensor with shape :math:`(B, T, N, 4, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
"""
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
batchsize, frame_num = input.size(0), input.size(1)
input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus")
input = super().transform_boxes(input, params, extra_args=extra_args)
@@ -306,17 +306,17 @@ class VideoSequential(ImageSequential):
return input
def inverse_boxes( # type: ignore[override]
- self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Union[Tensor, Boxes]:
+ self, input: Union[torch.Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Union[torch.Tensor, Boxes]:
"""Transform bounding boxes.
Args:
- input: tensor with shape :math:`(B, T, N, 4, 2)`.
+ input: torch.tensor with shape :math:`(B, T, N, 4, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
"""
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
batchsize, frame_num = input.size(0), input.size(1)
input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus")
input = super().inverse_boxes(input, params, extra_args=extra_args)
@@ -326,17 +326,20 @@ class VideoSequential(ImageSequential):
return input
def transform_keypoints( # type: ignore[override]
- self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Union[Tensor, Keypoints]:
+ self,
+ input: Union[torch.Tensor, Keypoints],
+ params: List[ParamItem],
+ extra_args: Optional[Dict[str, Any]] = None,
+ ) -> Union[torch.Tensor, Keypoints]:
"""Transform bounding boxes.
Args:
- input: tensor with shape :math:`(B, T, N, 2)`.
+ input: torch.tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
"""
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
batchsize, frame_num = input.size(0), input.size(1)
input = Keypoints(input.view(-1, input.size(2), input.size(3)))
input = super().transform_keypoints(input, params, extra_args=extra_args)
@@ -346,17 +349,20 @@ class VideoSequential(ImageSequential):
return input
def inverse_keypoints( # type: ignore[override]
- self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
- ) -> Union[Tensor, Keypoints]:
+ self,
+ input: Union[torch.Tensor, Keypoints],
+ params: List[ParamItem],
+ extra_args: Optional[Dict[str, Any]] = None,
+ ) -> Union[torch.Tensor, Keypoints]:
"""Transform bounding boxes.
Args:
- input: tensor with shape :math:`(B, T, N, 2)`.
+ input: torch.tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
"""
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
frame_num, batchsize = input.size(0), input.size(1)
input = Keypoints(input.view(-1, input.size(2), input.size(3)))
input = super().inverse_keypoints(input, params, extra_args=extra_args)
@@ -366,11 +372,11 @@ class VideoSequential(ImageSequential):
return input
def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if params is None:
@@ -382,11 +388,11 @@ class VideoSequential(ImageSequential):
return self.inverse_inputs(input, params, extra_args=extra_args)
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
- ) -> Tensor:
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
"""Define the video computation performed."""
if len(input.shape) != 5:
- raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")
+ raise AssertionError(f"Input must be a 5-dim torch.tensor. Got {input.shape}.")
if params is None:
self._params = self.forward_parameters(input.shape)
diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.py
index c5890757e..e9ac0644d 100644
--- a/kornia/augmentation/presets/ada.py
+++ b/kornia/augmentation/presets/ada.py
@@ -20,7 +20,6 @@ from typing import Any, Dict, List, Optional, Tuple, Union, cast
import torch
-from ...core import Device, Tensor # noqa: TID252
from .. import ( # noqa: TID252
AugmentationSequential,
ColorJitter,
@@ -35,7 +34,7 @@ from ..base import _AugmentationBase # noqa: TID252
from ..container.params import ParamItem # noqa: TID252
_data_keys_type = List[str]
-_inputs_type = Union[Tensor, Dict[str, Tensor]]
+_inputs_type = Union[torch.Tensor, Dict[str, torch.Tensor]]
class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
@@ -109,8 +108,8 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
target_real_acc: float = 0.85,
ema_lambda: float = 0.99,
update_every: int = 5,
- erasing_scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
- erasing_ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3),
+ erasing_scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ erasing_ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
erasing_fill_value: float = 0.0,
data_keys: Optional[_data_keys_type] = None,
same_on_batch: Optional[bool] = False,
@@ -165,7 +164,10 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
self._num_calls = 0 # -update_every # to avoid updating in the first `update_every` steps
def default_ada_transfroms(
- self, scale: Union[Tensor, Tuple[float, float]], ratio: Union[Tensor, Tuple[float, float]], value: float
+ self,
+ scale: Union[torch.Tensor, Tuple[float, float]],
+ ratio: Union[torch.Tensor, Tuple[float, float]],
+ value: float,
) -> Tuple[Union[_AugmentationBase, ImageSequential], ...]:
# if changed in the future, please change the expected transforms list in test_presets.py
return (
@@ -199,7 +201,9 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
else:
self.p = min(self.p + self.adjustment_speed, self.max_p)
- def _get_inputs_metadata(self, inputs: _inputs_type, data_keys: _data_keys_type) -> Tuple[int, Device]:
+ def _get_inputs_metadata(
+ self, inputs: _inputs_type, data_keys: _data_keys_type
+ ) -> Tuple[int, Optional[Union[str, torch.device]]]:
if isinstance(inputs, dict):
key = data_keys[0]
batch_size = inputs[key].size(0)
@@ -210,7 +214,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
return batch_size, device
- def _sample_inputs(self, inputs: _inputs_type, data_keys: _data_keys_type, p_tensor: Tensor) -> _inputs_type:
+ def _sample_inputs(self, inputs: _inputs_type, data_keys: _data_keys_type, p_tensor: torch.Tensor) -> _inputs_type:
if isinstance(inputs, dict):
return {key: inputs[key][p_tensor] for key in data_keys}
else:
@@ -220,7 +224,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
self,
original: _inputs_type,
augmented: _inputs_type,
- p_tensor: Tensor,
+ p_tensor: torch.Tensor,
) -> _inputs_type:
merged: _inputs_type
if isinstance(original, dict) and isinstance(augmented, dict):
@@ -229,7 +233,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
merged_tensor = original[key].clone()
merged_tensor[p_tensor] = augmented[key]
merged[key] = merged_tensor
- elif isinstance(original, Tensor) and isinstance(augmented, Tensor):
+ elif isinstance(original, torch.Tensor) and isinstance(augmented, torch.Tensor):
merged = original.clone()
merged[p_tensor] = augmented
else:
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 9d06ad3d4..baf5f60a3 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.core import Tensor, as_tensor, concatenate, stack, tensor, zeros
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["AffineGenerator"]
@@ -43,17 +42,18 @@ class AffineGenerator(RandomGeneratorBase):
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
- If tensor, shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
+ If torch.tensor, shear is a 2x2 torch.tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
+ y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
Returns:
A dict of parameters to be passed for transformation.
- - translations (Tensor): element-wise translations with a shape of (B, 2).
- - center (Tensor): element-wise center with a shape of (B, 2).
- - scale (Tensor): element-wise scales with a shape of (B, 2).
- - angle (Tensor): element-wise rotation angles with a shape of (B,).
- - shear_x (Tensor): element-wise x-axis shears with a shape of (B,).
- - shear_y (Tensor): element-wise y-axis shears with a shape of (B,).
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
+ - center (torch.Tensor): element-wise center with a shape of (B, 2).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
+ - shear_x (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - shear_y (torch.Tensor): element-wise y-axis shears with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -64,10 +64,10 @@ class AffineGenerator(RandomGeneratorBase):
def __init__(
self,
- degrees: Union[Tensor, float, Tuple[float, float]],
- translate: Optional[Union[Tensor, Tuple[float, float]]] = None,
- scale: Optional[Union[Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
- shear: Optional[Union[Tensor, float, Tuple[float, float]]] = None,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
) -> None:
super().__init__()
self.degrees = degrees
@@ -88,14 +88,14 @@ class AffineGenerator(RandomGeneratorBase):
device=device, dtype=dtype
)
)
- _scale: Optional[Tensor] = None
+ _scale: Optional[torch.Tensor] = None
if self.scale is not None:
if len(self.scale) == 2:
_scale = _range_bound(self.scale[:2], "scale", bounds=(0, float("inf")), check="singular").to(
device=device, dtype=dtype
)
elif len(self.scale) == 4:
- _scale = concatenate(
+ _scale = torch.cat(
[
_range_bound(self.scale[:2], "scale_x", bounds=(0, float("inf")), check="singular"),
_range_bound(self.scale[-2:], "scale_y", bounds=(0, float("inf")), check="singular"),
@@ -103,17 +103,17 @@ class AffineGenerator(RandomGeneratorBase):
).to(device=device, dtype=dtype)
else:
raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
- _shear: Optional[Tensor] = None
+ _shear: Optional[torch.Tensor] = None
if self.shear is not None:
- shear = as_tensor(self.shear, device=device, dtype=dtype)
+ shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
if shear.shape == torch.Size([2, 2]):
_shear = shear
else:
- _shear = stack(
+ _shear = torch.stack(
[
_range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),
(
- tensor([0, 0], device=device, dtype=dtype)
+ torch.tensor([0, 0], device=device, dtype=dtype)
if shear.dim() == 0 or len(shear) == 2
else _range_bound(shear[2:], "shear-y", 0, (-360, 360))
),
@@ -152,7 +152,7 @@ class AffineGenerator(RandomGeneratorBase):
self.shear_x_sampler = shear_x_sampler
self.shear_y_sampler = shear_y_sampler
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -164,7 +164,7 @@ class AffineGenerator(RandomGeneratorBase):
angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- # compute tensor ranges
+ # compute torch.tensor ranges
if self.scale_2_sampler is not None:
_scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)
if self.scale_4_sampler is not None:
@@ -174,7 +174,7 @@ class AffineGenerator(RandomGeneratorBase):
_scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
if self.translate_x_sampler is not None and self.translate_y_sampler is not None:
- translations = stack(
+ translations = torch.stack(
[
_adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,
_adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,
@@ -183,9 +183,9 @@ class AffineGenerator(RandomGeneratorBase):
)
translations = translations.to(device=_device, dtype=_dtype)
else:
- translations = zeros((batch_size, 2), device=_device, dtype=_dtype)
+ translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
- center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
center = center.expand(batch_size, -1)
if self.shear_x_sampler is not None and self.shear_y_sampler is not None:
@@ -194,8 +194,8 @@ class AffineGenerator(RandomGeneratorBase):
sx = sx.to(device=_device, dtype=_dtype)
sy = sy.to(device=_device, dtype=_dtype)
else:
- sx = tensor([0] * batch_size, device=_device, dtype=_dtype)
- sy = tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sx = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
return {
"translations": translations,
diff --git a/kornia/augmentation/random_generator/_2d/channel_dropout.py b/kornia/augmentation/random_generator/_2d/channel_dropout.py
index 5b7d0ae56..27cf406c8 100644
--- a/kornia/augmentation/random_generator/_2d/channel_dropout.py
+++ b/kornia/augmentation/random_generator/_2d/channel_dropout.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor
class ChannelDropoutGenerator(RandomGeneratorBase):
@@ -59,7 +58,7 @@ class ChannelDropoutGenerator(RandomGeneratorBase):
drop = _range_bound((0.0, 1.0), "drop", device=device, dtype=dtype)
self.drop_sampler = UniformDistribution(drop[0], drop[1], validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate a mask for dropout channels."""
batch_size, channels, _, _ = batch_shape
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 701fa8438..1b975f5e2 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -22,7 +22,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["ColorJiggleGenerator"]
@@ -56,10 +55,10 @@ class ColorJiggleGenerator(RandomGeneratorBase):
def __init__(
self,
- brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
) -> None:
super().__init__()
self.brightness = brightness
@@ -72,9 +71,9 @@ class ColorJiggleGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
brightness = _range_bound(self.brightness, "brightness", center=1.0, bounds=(0, 2), device=device, dtype=dtype)
- contrast: Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
- saturation: Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
- hue: Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
+ contrast: torch.Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
+ saturation: torch.Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
+ hue: torch.Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
_joint_range_check(brightness, "brightness", (0, 2))
_joint_range_check(contrast, "contrast", (0, float("inf")))
@@ -87,7 +86,7 @@ class ColorJiggleGenerator(RandomGeneratorBase):
self.saturation_sampler = UniformDistribution(saturation[0], saturation[1], validate_args=False)
self.randperm = partial(torch.randperm, device=device, dtype=dtype)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index a86fd4fa1..48c046e4c 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -28,7 +28,6 @@ from kornia.augmentation.utils import (
_joint_range_check,
_range_bound,
)
-from kornia.core import Tensor
__all__ = ["ColorJitterGenerator"]
@@ -65,10 +64,10 @@ class ColorJitterGenerator(RandomGeneratorBase):
def __init__(
self,
- brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
) -> None:
super().__init__()
self.brightness = brightness
@@ -80,10 +79,10 @@ class ColorJitterGenerator(RandomGeneratorBase):
return f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness: Tensor = _range_bound(self.brightness, "brightness", center=1.0, device=device, dtype=dtype)
- contrast: Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
- saturation: Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
- hue: Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
+ brightness: torch.Tensor = _range_bound(self.brightness, "brightness", center=1.0, device=device, dtype=dtype)
+ contrast: torch.Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
+ saturation: torch.Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
+ hue: torch.Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
_joint_range_check(brightness, "brightness", (0, float("inf")))
_joint_range_check(contrast, "contrast", (0, float("inf")))
@@ -95,7 +94,7 @@ class ColorJitterGenerator(RandomGeneratorBase):
self.hue_sampler = UniformDistribution(hue[0], hue[1], validate_args=False)
self.saturation_sampler = UniformDistribution(saturation[0], saturation[1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
brightness_factor = _adapted_rsampling((batch_size,), self.brightness_sampler, same_on_batch)
contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 1f89e4d45..b7e59e03f 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -22,7 +22,6 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
-from kornia.core import Device, Tensor, tensor, where, zeros
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
@@ -34,13 +33,13 @@ class CropGenerator(RandomGeneratorBase):
Args:
size (tuple): Desired size of the crop operation, like (h, w).
- If tensor, it must be (B, 2).
+ If torch.tensor, it must be (B, 2).
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -49,7 +48,7 @@ class CropGenerator(RandomGeneratorBase):
"""
- def __init__(self, size: Union[Tuple[int, int], Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
+ def __init__(self, size: Union[Tuple[int, int], torch.Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
super().__init__()
self.size = size
self.resize_to = resize_to
@@ -61,27 +60,29 @@ class CropGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
if batch_size == 0:
return {
- "src": zeros([0, 4, 2], device=_device, dtype=_dtype),
- "dst": zeros([0, 4, 2], device=_device, dtype=_dtype),
+ "src": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ "dst": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
}
input_size = (batch_shape[-2], batch_shape[-1])
- if not isinstance(self.size, Tensor):
- size = tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 2]):
raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 2). "
+ "If `size` is a torch.tensor, it must be shaped as (B, 2). "
f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
)
if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
@@ -109,14 +110,14 @@ class CropGenerator(RandomGeneratorBase):
crop_src = bbox_generator(
x_start.view(-1).to(device=_device, dtype=_dtype),
y_start.view(-1).to(device=_device, dtype=_dtype),
- where(size[:, 1] == 0, tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- where(size[:, 0] == 0, tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
)
if self.resize_to is None:
crop_dst = bbox_generator(
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 1],
size[:, 0],
)
@@ -130,7 +131,7 @@ class CropGenerator(RandomGeneratorBase):
and self.resize_to[1] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
- crop_dst = tensor(
+ crop_dst = torch.tensor(
[
[
[0, 0],
@@ -142,9 +143,9 @@ class CropGenerator(RandomGeneratorBase):
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
- _output_size = tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = torch.tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)
- _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
return {"src": crop_src, "dst": crop_dst, "input_size": _input_size, "output_size": _output_size}
@@ -154,12 +155,12 @@ class ResizedCropGenerator(CropGenerator):
Args:
output_size (Tuple[int, int]): expected output size of each edge.
- scale (Tensor): range of size of the origin size cropped with (2,) shape.
- ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+ scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - size (Tensor): element-wise cropping sizes with a shape of (B, 2).
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -188,8 +189,8 @@ class ResizedCropGenerator(CropGenerator):
def __init__(
self,
output_size: Tuple[int, int],
- scale: Union[Tensor, Tuple[float, float]],
- ratio: Union[Tensor, Tuple[float, float]],
+ scale: Union[torch.Tensor, Tuple[float, float]],
+ ratio: Union[torch.Tensor, Tuple[float, float]],
) -> None:
if not (
len(output_size) == 2
@@ -213,23 +214,28 @@ class ResizedCropGenerator(CropGenerator):
ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
- self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
size = (batch_shape[-2], batch_shape[-1])
_device, _dtype = _extract_device_dtype([self.scale, self.ratio])
if batch_size == 0:
return {
- "src": zeros([0, 4, 2], device=_device, dtype=_dtype),
- "dst": zeros([0, 4, 2], device=_device, dtype=_dtype),
- "size": zeros([0, 2], device=_device, dtype=_dtype),
+ "src": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ "dst": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ "size": torch.zeros([0, 2], device=_device, dtype=_dtype),
}
- rand = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- area = (rand * (self.scale[1] - self.scale[0]) + self.scale[0]) * size[0] * size[1]
+ rand_tensor = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+ scale_tensor = torch.as_tensor(self.scale, device=_device, dtype=_dtype)
+ area = (rand_tensor * (scale_tensor[1] - scale_tensor[0]) + scale_tensor[0]) * size[0] * size[1]
log_ratio = _adapted_rsampling((batch_size, 10), self.log_ratio_sampler, same_on_batch).to(
device=_device, dtype=_dtype
)
@@ -238,32 +244,36 @@ class ResizedCropGenerator(CropGenerator):
w = torch.sqrt(area * aspect_ratio).round().floor()
h = torch.sqrt(area / aspect_ratio).round().floor()
# Element-wise w, h condition
- cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
+ cond = ((0 < w) * (w < size[1]) * (0 < h) * (h < size[0])).int()
# torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
# Here, we will select the first occurrence of the duplicated elements.
cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
- h_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
- w_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+ h_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+ w_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
if not cond_bool.all():
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
- _min = float(self.ratio.min()) if isinstance(self.ratio, Tensor) else min(self.ratio)
+ _min = float(self.ratio.min()) if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
if in_ratio < _min:
- h_ct = tensor(size[0], device=_device, dtype=_dtype)
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
w_ct = torch.round(h_ct / _min)
elif in_ratio > _min:
- w_ct = tensor(size[1], device=_device, dtype=_dtype)
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
h_ct = torch.round(w_ct * _min)
else: # whole image
- h_ct = tensor(size[0], device=_device, dtype=_dtype)
- w_ct = tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
h_ct = h_ct.floor()
w_ct = w_ct.floor()
- h_out = h_out.where(cond_bool, h_ct)
- w_out = w_out.where(cond_bool, w_ct)
+ h_out = torch.where(cond_bool, h_out, h_ct)
+ w_out = torch.where(cond_bool, w_out, w_ct)
+
+ # Clamp crop size to input size to prevent out-of-bounds crops
+ h_out = torch.clamp(h_out, min=1, max=size[0])
+ w_out = torch.clamp(w_out, min=1, max=size[1])
# Update the crop size.
self.size = torch.stack([h_out, w_out], dim=1)
@@ -271,21 +281,25 @@ class ResizedCropGenerator(CropGenerator):
def center_crop_generator(
- batch_size: int, height: int, width: int, size: Tuple[int, int], device: Optional[Device] = None
-) -> Dict[str, Tensor]:
+ batch_size: int,
+ height: int,
+ width: int,
+ size: Tuple[int, int],
+ device: Optional[Union[str, torch.device, None]] = None,
+) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
Args:
- batch_size (int): the tensor batch size.
+ batch_size (int): the torch.tensor batch size.
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (h, w).
- device (Device): the device on which the random numbers will be generated. Default: cpu.
+ device (Union[str, torch.device, None]): the device on which the random numbers will be generated. Default: cpu.
Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
Note:
No random number will be generated.
@@ -319,17 +333,17 @@ def center_crop_generator(
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: Tensor = tensor(
+ points_src: torch.Tensor = torch.tensor(
[[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]], device=device, dtype=torch.long
).expand(batch_size, -1, -1)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: Tensor = tensor(
+ points_dst: torch.Tensor = torch.tensor(
[[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=device, dtype=torch.long
).expand(batch_size, -1, -1)
- _input_size = tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
- _output_size = tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = torch.tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)
return {"src": points_src, "dst": points_dst, "input_size": _input_size, "output_size": _output_size}
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 980ff7cf8..94cd79578 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -22,7 +22,6 @@ from torch.distributions import Bernoulli, Beta, Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
-from kornia.core import as_tensor, tensor, zeros
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
@@ -74,23 +73,27 @@ class CutmixGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
if self.beta is None:
- self._beta = tensor(1.0, device=device, dtype=dtype)
+ self._beta = torch.tensor(1.0, device=device, dtype=dtype)
else:
- self._beta = as_tensor(self.beta, device=device, dtype=dtype)
+ self._beta = torch.as_tensor(self.beta, device=device, dtype=dtype)
if self.cut_size is None:
- self._cut_size = tensor([0.0, 1.0], device=device, dtype=dtype)
+ self._cut_size = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
else:
- self._cut_size = as_tensor(self.cut_size, device=device, dtype=dtype)
+ self._cut_size = torch.as_tensor(self.cut_size, device=device, dtype=dtype)
_joint_range_check(self._cut_size, "cut_size", bounds=(0, 1))
self.beta_sampler = Beta(self._beta, self._beta)
- self.prob_sampler = Bernoulli(tensor(float(self.p), device=device, dtype=dtype))
+ self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
self.rand_sampler = Uniform(
- tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.tensor(1.0, device=device, dtype=dtype),
+ validate_args=False,
)
self.pair_sampler = Uniform(
- tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.tensor(1.0, device=device, dtype=dtype),
+ validate_args=False,
)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
@@ -105,8 +108,8 @@ class CutmixGenerator(RandomGeneratorBase):
if batch_size == 0:
return {
- "mix_pairs": zeros([0, 3], device=_device, dtype=torch.long),
- "crop_src": zeros([0, 4, 2], device=_device, dtype=_dtype),
+ "mix_pairs": torch.zeros([0, 3], device=_device, dtype=torch.long),
+ "crop_src": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
}
with torch.no_grad():
@@ -121,8 +124,8 @@ class CutmixGenerator(RandomGeneratorBase):
cutmix_betas: torch.Tensor = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, same_on_batch)
- # Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
- # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
+ # Note: torch.clamp does not accept torch.tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
+ # Argument 1 to "clamp" of "_TensorBase" has incompatible type "torch.Tensor"; expected "float"
cutmix_betas = torch.min(torch.max(cutmix_betas, self._cut_size[0]), self._cut_size[1])
cutmix_rate = torch.sqrt(1.0 - cutmix_betas) * batch_probs
@@ -153,5 +156,5 @@ class CutmixGenerator(RandomGeneratorBase):
return {
"mix_pairs": mix_pairs.to(device=_device, dtype=torch.long),
"crop_src": crop_src.floor().to(device=_device, dtype=_dtype),
- "image_shape": as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),
+ "image_shape": torch.as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),
}
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
index 9af4e1dd4..610382f67 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
@@ -28,7 +28,6 @@ from kornia.augmentation.utils import (
_common_param_check,
_range_bound,
)
-from kornia.core import Tensor
from kornia.enhance import normalize_min_max
from kornia.filters.kernels import gaussian
@@ -97,7 +96,7 @@ class GaussianIlluminationGenerator(RandomGeneratorBase):
)
self.sign_sampler = UniformDistribution(sign[0], sign[1], validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate random 2D Gaussian illumination patterns."""
batch_size, channels, height, width = batch_shape
diff --git a/kornia/augmentation/random_generator/_2d/jpeg.py b/kornia/augmentation/random_generator/_2d/jpeg.py
index f879d9eb9..30ad9b0fb 100644
--- a/kornia/augmentation/random_generator/_2d/jpeg.py
+++ b/kornia/augmentation/random_generator/_2d/jpeg.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["JPEGGenerator"]
@@ -46,10 +45,10 @@ class JPEGGenerator(RandomGeneratorBase):
def __init__(
self,
- jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0,
+ jpeg_quality: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 50.0,
) -> None:
super().__init__()
- self.jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = jpeg_quality
+ self.jpeg_quality: Union[torch.Tensor, float, Tuple[float, float], List[float]] = jpeg_quality
def __repr__(self) -> str:
return f"RandomJPEG quality={self.jpeg_quality}"
@@ -63,7 +62,7 @@ class JPEGGenerator(RandomGeneratorBase):
self.jpeg_quality_sampler = UniformDistribution(jpeg_quality[0], jpeg_quality[1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.jpeg_quality])
diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.py
index a8fd0f2e9..d657cccca 100644
--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor
from kornia.enhance.normalize import normalize_min_max
from kornia.utils import _extract_device_dtype
@@ -71,7 +70,7 @@ class LinearIlluminationGenerator(RandomGeneratorBase):
self.directions_sampler = UniformDistribution(0, 4, validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate random 2D Gaussian illumination patterns."""
batch_size, channels, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
@@ -162,7 +161,7 @@ class LinearCornerIlluminationGenerator(RandomGeneratorBase):
self.directions_sampler = UniformDistribution(0, 4, validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate random 2D Gaussian illumination patterns."""
batch_size, channels, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index 4a56a5c3f..b66918351 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -22,7 +22,6 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.core import Tensor
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
@@ -33,17 +32,17 @@ class MosaicGenerator(RandomGeneratorBase):
r"""Generate mixup indexes and lambdas for a batch of inputs.
Args:
- output_size: the output tensor width and height after mosaicing.
+ output_size: the output torch.tensor width and height after mosaicing.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
start_ratio_range: top-left (x, y) position for cropping the mosaic images.
Returns:
A dict of parameters to be passed for transformation.
- - mosaic_ids (Tensor): a shape of (B, N) tensor, where n is the number of mosaic images.
- - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
- - batch_shapes (Tensor): image shapes in the batch with a shape of (B, 3).
+ - mosaic_ids (torch.Tensor): a shape of (B, N) torch.tensor, torch.where n is the number of mosaic images.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ - batch_shapes (torch.Tensor): image shapes in the batch with a shape of (B, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -110,10 +109,10 @@ class MosaicGenerator(RandomGeneratorBase):
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
- # NOTE: In case we support a list of tensor images later. For a better consistency.
+ # NOTE: In case we support a list of torch.tensor images later. For a better consistency.
# B x 3
- batch_shapes: Tensor
+ batch_shapes: torch.Tensor
if batch_size == 0:
batch_shapes = torch.zeros([0, 3], device=_device, dtype=torch.long)
else:
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index f10ebccab..6e1fd0712 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["MotionBlurGenerator"]
@@ -45,9 +44,9 @@ class MotionBlurGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (Tensor): element-wise direction factors with a shape of (B,).
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -59,8 +58,8 @@ class MotionBlurGenerator(RandomGeneratorBase):
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]],
- angle: Union[Tensor, float, Tuple[float, float]],
- direction: Union[Tensor, float, Tuple[float, float]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
) -> None:
super().__init__()
self.kernel_size = kernel_size
@@ -91,7 +90,7 @@ class MotionBlurGenerator(RandomGeneratorBase):
self.angle_sampler = UniformDistribution(angle[0], angle[1], validate_args=False)
self.direction_sampler = UniformDistribution(direction[0], direction[1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
# self.ksize_factor.expand((batch_size, -1))
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index 33cb803c8..0f402229d 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -22,7 +22,6 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.core import Tensor, tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["PerspectiveGenerator"]
@@ -40,8 +39,8 @@ class PerspectiveGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - start_points (Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
- - end_points (Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+ - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -50,7 +49,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
"""
- def __init__(self, distortion_scale: Union[Tensor, float] = 0.5, sampling_method: str = "basic") -> None:
+ def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5, sampling_method: str = "basic") -> None:
super().__init__()
if sampling_method not in ("basic", "area_preserving"):
raise NotImplementedError(f"Sampling method {sampling_method} not yet implemented.")
@@ -66,10 +65,12 @@ class PerspectiveGenerator(RandomGeneratorBase):
if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}.")
self.rand_val_sampler = Uniform(
- tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -79,7 +80,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
- start_points: Tensor = tensor(
+ start_points: torch.Tensor = torch.tensor(
[[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]], device=_device, dtype=_dtype
).expand(batch_size, -1, -1)
@@ -90,11 +91,11 @@ class PerspectiveGenerator(RandomGeneratorBase):
factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
# TODO: This line somehow breaks the gradcheck
- rand_val: Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(
+ rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(
device=_device, dtype=_dtype
)
if self.sampling_method == "basic":
- pts_norm = tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)
+ pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)
offset = factor * rand_val * pts_norm
elif self.sampling_method == "area_preserving":
offset = 2 * factor * (rand_val - 0.5)
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index a8c0fe9d0..2240daada 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -22,7 +22,6 @@ from torch.distributions import Distribution
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor, as_tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["ParameterBound", "PlainUniformGenerator"]
@@ -36,7 +35,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
Args:
*samplers: a list of tuple in a pattern of ``(factor, name, center, range)``, in which
- the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch tensor. The name
+ the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch torch.tensor. The name
will be the corresponding key of the returning dict. The center and range must be
both provided worked as a validator to the given factor.
@@ -70,7 +69,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
names.append(name)
if isinstance(factor, torch.nn.Parameter):
self.register_parameter(name, factor)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
self.register_buffer(name, factor)
else:
factor = _range_bound(factor, name, center=center, bounds=bound)
@@ -84,14 +83,14 @@ class PlainUniformGenerator(RandomGeneratorBase):
self.sampler_dict: Dict[str, Distribution] = {}
for factor, name, center, bound in self.samplers:
if center is None and bound is None:
- factor = as_tensor(factor, device=device, dtype=dtype)
+ factor = torch.as_tensor(factor, device=device, dtype=dtype)
elif center is None or bound is None:
raise ValueError(f"`center` and `bound` should be both None or provided. Got {center} and {bound}.")
else:
factor = _range_bound(factor, name, center=center, bounds=bound, device=device, dtype=dtype)
self.sampler_dict.update({name: UniformDistribution(factor[0], factor[1], validate_args=False)})
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index d3104cc04..7669984f9 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
-from kornia.core import Tensor, as_tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["PosterizeGenerator"]
@@ -37,7 +36,7 @@ class PosterizeGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - bits_factor (Tensor): element-wise bit factors with a shape of (B,).
+ - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -46,7 +45,7 @@ class PosterizeGenerator(RandomGeneratorBase):
"""
- def __init__(self, bits: Union[float, Tuple[float, float], Tensor]) -> None:
+ def __init__(self, bits: Union[float, Tuple[float, float], torch.Tensor]) -> None:
super().__init__()
self.bits_factor = bits
@@ -55,18 +54,18 @@ class PosterizeGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- bits = as_tensor(self.bits_factor, device=device, dtype=dtype)
+ bits = torch.as_tensor(self.bits_factor, device=device, dtype=dtype)
if len(bits.size()) == 0:
bits = bits.repeat(2)
bits[1] = 8
elif not (len(bits.size()) == 1 and bits.size(0) == 2):
- raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
+ raise ValueError(f"'bits' shall be either a scalar or a length 2 torch.tensor. Got {bits}.")
_joint_range_check(bits, "bits", (0, 8))
self.bit_sampler = UniformDistribution(bits[0], bits[1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
- _device, _ = _extract_device_dtype([self.bits_factor if isinstance(self.bits_factor, Tensor) else None])
+ _device, _ = _extract_device_dtype([self.bits_factor if isinstance(self.bits_factor, torch.Tensor) else None])
bits_factor = _adapted_rsampling((batch_size,), self.bit_sampler, same_on_batch)
return {"bits_factor": bits_factor.round().to(device=_device, dtype=torch.int32)}
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index f41088ab7..079fe643b 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -22,7 +22,6 @@ from torch.distributions import Bernoulli
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_sampling, _common_param_check
-from kornia.core import Tensor, tensor
__all__ = ["ProbabilityGenerator"]
@@ -35,7 +34,7 @@ class ProbabilityGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - probs (Tensor): element-wise probabilities with a shape of (B,).
+ - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -56,9 +55,9 @@ class ProbabilityGenerator(RandomGeneratorBase):
p = torch.tensor(float(self.p), device=device, dtype=dtype)
self.sampler = Bernoulli(p)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
- probs_mask: Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
return {"probs": probs_mask}
@@ -68,7 +67,7 @@ def random_prob_generator(
same_on_batch: bool = False,
device: Optional[torch.device] = None,
dtype: torch.dtype = torch.float32,
-) -> Tensor:
+) -> torch.Tensor:
r"""Generate random probabilities for a batch of inputs.
Args:
@@ -79,8 +78,8 @@ def random_prob_generator(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- Tensor: parameters to be passed for transformation.
- - probs (Tensor): element-wise probabilities with a shape of (B,).
+ torch.Tensor: parameters to be passed for transformation.
+ - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -92,7 +91,7 @@ def random_prob_generator(
if not isinstance(p, (int, float)) or p > 1 or p < 0:
raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
- _bernoulli = Bernoulli(tensor(float(p), device=device, dtype=dtype))
- probs_mask: Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
+ _bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
return probs_mask
diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.py
index 92cd1ea67..a4dedae3e 100644
--- a/kornia/augmentation/random_generator/_2d/random_rain.py
+++ b/kornia/augmentation/random_generator/_2d/random_rain.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor
from kornia.utils import _extract_device_dtype
@@ -66,7 +65,7 @@ class RainGenerator(RandomGeneratorBase):
self.drop_width_sampler = UniformDistribution(drop_width[0], drop_width[1], validate_args=False)
self.coordinates_sampler = UniformDistribution(drop_coordinates[0], drop_coordinates[1], validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.drop_width, self.drop_height, self.number_of_drops])
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index a484ccc5d..32855fc3f 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
-from kornia.core import Tensor, as_tensor, tensor, where
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["RectangleEraseGenerator"]
@@ -31,17 +30,17 @@ class RectangleEraseGenerator(RandomGeneratorBase):
r"""Get parameters for ```erasing``` transformation for erasing transform.
Args:
- scale (Tensor): range of size of the origin size cropped. Shape (2).
- ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
value (float): value to be filled in the erased area.
Returns:
A dict of parameters to be passed for transformation.
- - widths (Tensor): element-wise erasing widths with a shape of (B,).
- - heights (Tensor): element-wise erasing heights with a shape of (B,).
- - xs (Tensor): element-wise erasing x coordinates with a shape of (B,).
- - ys (Tensor): element-wise erasing y coordinates with a shape of (B,).
- - values (Tensor): element-wise filling values with a shape of (B,).
+ - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (torch.Tensor): element-wise filling values with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -52,8 +51,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
def __init__(
self,
- scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3),
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
value: float = 0.0,
) -> None:
super().__init__()
@@ -66,8 +65,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- scale = as_tensor(self.scale, device=device, dtype=dtype)
- ratio = as_tensor(self.ratio, device=device, dtype=dtype)
+ scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
@@ -80,15 +79,19 @@ class RectangleEraseGenerator(RandomGeneratorBase):
self.ratio_sampler1 = UniformDistribution(ratio[0], 1, validate_args=False)
self.ratio_sampler2 = UniformDistribution(1, ratio[1], validate_args=False)
self.index_sampler = UniformDistribution(
- tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
)
else:
self.ratio_sampler = UniformDistribution(ratio[0], ratio[1], validate_args=False)
self.uniform_sampler = UniformDistribution(
- tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -112,7 +115,7 @@ class RectangleEraseGenerator(RandomGeneratorBase):
)
else:
rand_idxs = torch.round(_adapted_rsampling((batch_size,), self.index_sampler, same_on_batch)).bool()
- aspect_ratios = where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
aspect_ratios = _adapted_rsampling((batch_size,), self.ratio_sampler, same_on_batch)
@@ -121,16 +124,16 @@ class RectangleEraseGenerator(RandomGeneratorBase):
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
torch.max(
- torch.round((target_areas * aspect_ratios) ** (1 / 2)), tensor(1.0, device=_device, dtype=_dtype)
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
),
- tensor(height, device=_device, dtype=_dtype),
+ torch.tensor(height, device=_device, dtype=_dtype),
)
widths = torch.min(
torch.max(
- torch.round((target_areas / aspect_ratios) ** (1 / 2)), tensor(1.0, device=_device, dtype=_dtype)
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
),
- tensor(width, device=_device, dtype=_dtype),
+ torch.tensor(width, device=_device, dtype=_dtype),
)
xs_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(
@@ -148,5 +151,5 @@ class RectangleEraseGenerator(RandomGeneratorBase):
"heights": heights.floor(),
"xs": xs.floor(),
"ys": ys.floor(),
- "values": tensor([self.value] * batch_size, device=_device, dtype=_dtype),
+ "values": torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),
}
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index 3c8bfbbce..ef8dad706 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _common_param_check
-from kornia.core import Device, Tensor, tensor
from kornia.geometry.bbox import bbox_generator
from kornia.geometry.transform.affwarp import _side_to_image_size
@@ -37,9 +36,9 @@ class ResizeGenerator(RandomGeneratorBase):
Returns:
parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
- - input_size (Tensor): (h, w) from batch input.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ - input_size (torch.Tensor): (h, w) from batch input.
- resize_to (tuple): new (h, w) for batch input.
Note:
@@ -58,12 +57,12 @@ class ResizeGenerator(RandomGeneratorBase):
repr = f"output_size={self.output_size}"
return repr
- def make_samplers(self, device: Device, dtype: torch.dtype) -> None:
+ def make_samplers(self, device: Union[str, torch.device, None], dtype: torch.dtype) -> None:
self.device = device
self.dtype = dtype
pass
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device = self.device
@@ -78,10 +77,10 @@ class ResizeGenerator(RandomGeneratorBase):
input_size = h, w = (batch_shape[-2], batch_shape[-1])
src = bbox_generator(
- tensor(0, device=_device, dtype=_dtype),
- tensor(0, device=_device, dtype=_dtype),
- tensor(input_size[1], device=_device, dtype=_dtype),
- tensor(input_size[0], device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(input_size[1], device=_device, dtype=_dtype),
+ torch.tensor(input_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
if isinstance(self.output_size, int):
@@ -100,13 +99,13 @@ class ResizeGenerator(RandomGeneratorBase):
raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {output_size}.")
dst = bbox_generator(
- tensor(0, device=_device, dtype=_dtype),
- tensor(0, device=_device, dtype=_dtype),
- tensor(output_size[1], device=_device, dtype=_dtype),
- tensor(output_size[0], device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(0, device=_device, dtype=_dtype),
+ torch.tensor(output_size[1], device=_device, dtype=_dtype),
+ torch.tensor(output_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
- _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
- _output_size = tensor(output_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = torch.tensor(output_size, device=_device, dtype=torch.long).expand(batch_size, -1)
return {"src": src, "dst": dst, "input_size": _input_size, "output_size": _output_size}
diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
index 7e3ec8f1c..1d61b68a6 100644
--- a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _range_bound
-from kornia.core import Tensor
from kornia.utils import _extract_device_dtype
@@ -75,7 +74,7 @@ class SaltAndPepperGenerator(RandomGeneratorBase):
self.amount_sampler = UniformDistribution(amount[0], amount[1], validate_args=False)
self.salt_and_pepper_sampler = UniformDistribution(salt_and_pepper[0], salt_and_pepper[1], validate_args=False)
- def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate Salt and Pepper noise masks for a batch of images."""
batch_size, C, H, W = batch_shape
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index ec21971c2..9f5d151ae 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.core import Tensor, as_tensor, stack, tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["ShearGenerator"]
@@ -36,13 +35,14 @@ class ShearGenerator(RandomGeneratorBase):
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
- If tensor, shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
+ If torch.tensor, shear is a 2x2 torch.tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
+ y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
Returns:
A dict of parameters to be passed for transformation.
- - shear_x (Tensor): element-wise x-axis shears with a shape of (B,).
- - shear_y (Tensor): element-wise y-axis shears with a shape of (B,).
+ - shear_x (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - shear_y (torch.Tensor): element-wise y-axis shears with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -51,7 +51,9 @@ class ShearGenerator(RandomGeneratorBase):
"""
- def __init__(self, shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]]) -> None:
+ def __init__(
+ self, shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float]]
+ ) -> None:
super().__init__()
self.shear = shear
@@ -60,15 +62,15 @@ class ShearGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- shear = as_tensor(self.shear, device=device, dtype=dtype)
+ shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
if shear.shape == torch.Size([2, 2]):
_shear = shear
else:
- _shear = stack(
+ _shear = torch.stack(
[
_range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),
(
- tensor([0, 0], device=device, dtype=dtype)
+ torch.tensor([0, 0], device=device, dtype=dtype)
if shear.dim() == 0 or len(shear) == 2
else _range_bound(shear[2:], "shear-y", 0, (-360, 360))
),
@@ -86,7 +88,7 @@ class ShearGenerator(RandomGeneratorBase):
self.shear_x_sampler = shear_x_sampler
self.shear_y_sampler = shear_y_sampler
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -96,7 +98,7 @@ class ShearGenerator(RandomGeneratorBase):
if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
- center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
center = center.expand(batch_size, -1)
sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index 416e20661..837d575ee 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
__all__ = ["TranslateGenerator"]
@@ -38,7 +37,7 @@ class TranslateGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - translations (Tensor): element-wise translations with a shape of (B, 2).
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -49,8 +48,8 @@ class TranslateGenerator(RandomGeneratorBase):
def __init__(
self,
- translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None,
- translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ translate_x: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ translate_y: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
) -> None:
super().__init__()
self.translate_x = translate_x
@@ -82,7 +81,7 @@ class TranslateGenerator(RandomGeneratorBase):
_translate_y[..., 0], _translate_y[..., 1], validate_args=False
)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index d3b901f30..56b43413e 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -22,7 +22,6 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.core import Device, Tensor, tensor, zeros
from kornia.geometry.bbox import bbox_generator3d
from kornia.utils.helpers import _extract_device_dtype
@@ -32,13 +31,13 @@ class CropGenerator3D(RandomGeneratorBase):
Args:
size (tuple): Desired size of the crop operation, like (d, h, w).
- If tensor, it must be (B, 3).
+ If torch.tensor, it must be (B, 3).
resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
Returns:
A dict of parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -48,7 +47,7 @@ class CropGenerator3D(RandomGeneratorBase):
"""
def __init__(
- self, size: Union[Tuple[int, int, int], Tensor], resize_to: Optional[Tuple[int, int, int]] = None
+ self, size: Union[Tuple[int, int, int], torch.Tensor], resize_to: Optional[Tuple[int, int, int]] = None
) -> None:
super().__init__()
self.size = size
@@ -61,20 +60,22 @@ class CropGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size, _, depth, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
- if not isinstance(self.size, Tensor):
- size = tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 3]):
raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 3). "
+ "If `size` is a torch.tensor, it must be shaped as (B, 3). "
f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
)
if not (
@@ -98,8 +99,8 @@ class CropGenerator3D(RandomGeneratorBase):
if batch_size == 0:
return {
- "src": zeros([0, 8, 3], device=_device, dtype=_dtype),
- "dst": zeros([0, 8, 3], device=_device, dtype=_dtype),
+ "src": torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ "dst": torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
}
x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
@@ -116,9 +117,9 @@ class CropGenerator3D(RandomGeneratorBase):
if self.resize_to is None:
crop_dst = bbox_generator3d(
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 2] - 1,
size[:, 1] - 1,
size[:, 0] - 1,
@@ -134,7 +135,7 @@ class CropGenerator3D(RandomGeneratorBase):
and self.resize_to[2] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")
- crop_dst = tensor(
+ crop_dst = torch.tensor(
[
[
[0, 0, 0],
@@ -160,22 +161,22 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: Optional[Device] = None,
-) -> Dict[str, Tensor]:
+ device: Optional[Union[str, torch.device, None]] = None,
+) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
Args:
- batch_size (int): the tensor batch size.
+ batch_size (int): the torch.tensor batch size.
depth (int) : depth of the image.
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (d, h, w).
- device (Device): the device on which the random numbers will be generated. Default: cpu.
+ device (Union[str, torch.device, None]): the device on which the random numbers will be generated. Default: cpu.
Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
Note:
No random number will be generated.
@@ -198,7 +199,7 @@ def center_crop_generator3d(
raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
if batch_size == 0:
- return {"src": zeros([0, 8, 3]), "dst": zeros([0, 8, 3])}
+ return {"src": torch.zeros([0, 8, 3]), "dst": torch.zeros([0, 8, 3])}
# unpack input sizes
dst_d, dst_h, dst_w = size
src_d, src_h, src_w = (depth, height, width)
@@ -223,7 +224,7 @@ def center_crop_generator3d(
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
# Note: DeprecationWarning: an integer is required (got type float).
# Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
- points_src: Tensor = tensor(
+ points_src: torch.Tensor = torch.tensor(
[
[
[int(start_x), int(start_y), int(start_z)],
@@ -243,7 +244,7 @@ def center_crop_generator3d(
# [x, y, z] destination
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_dst: Tensor = tensor(
+ points_dst: torch.Tensor = torch.tensor(
[
[
[0, 0, 0],
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index 5c0b16207..fc3f10063 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound, _tuple_range_reader
-from kornia.core import Tensor, stack
from kornia.utils.helpers import _extract_device_dtype
@@ -43,9 +42,9 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (Tensor): element-wise direction factors with a shape of (B,).
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -58,12 +57,12 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
self,
kernel_size: Union[int, Tuple[int, int]],
angle: Union[
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
],
- direction: Union[Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
) -> None:
super().__init__()
self.kernel_size = kernel_size
@@ -75,7 +74,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- angle: Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
+ angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
direction = _range_bound(self.direction, "direction", center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
if isinstance(self.kernel_size, int):
if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
@@ -96,7 +95,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
self.roll_sampler = UniformDistribution(angle[2][0], angle[2][1], validate_args=False)
self.direction_sampler = UniformDistribution(direction[0], direction[1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
# self.ksize_factor.expand((batch_size, -1))
@@ -104,7 +103,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
yaw_factor = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
pitch_factor = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
roll_factor = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
- angle_factor = stack([yaw_factor, pitch_factor, roll_factor], 1)
+ angle_factor = torch.stack([yaw_factor, pitch_factor, roll_factor], 1)
direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index f24d8ce15..03645c396 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -22,7 +22,6 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.core import Tensor, as_tensor, stack, tensor
from kornia.utils.helpers import _extract_device_dtype
@@ -34,8 +33,8 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - src (Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+ - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -44,7 +43,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
"""
- def __init__(self, distortion_scale: Union[Tensor, float] = 0.5) -> None:
+ def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
super().__init__()
self.distortion_scale = distortion_scale
@@ -53,14 +52,16 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self._distortion_scale = as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}")
self.rand_sampler = Uniform(
- tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
depth = batch_shape[-3]
height = batch_shape[-2]
@@ -69,7 +70,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.distortion_scale])
- start_points: Tensor = tensor(
+ start_points: torch.Tensor = torch.tensor(
[
[
[0.0, 0, 0],
@@ -91,13 +92,13 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
fy = self._distortion_scale * height / 2
fz = self._distortion_scale * depth / 2
- factor = stack([fx, fy, fz], 0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
+ factor = torch.stack([fx, fy, fz], 0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
- rand_val: Tensor = _adapted_rsampling(start_points.shape, self.rand_sampler, same_on_batch).to(
+ rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_sampler, same_on_batch).to(
device=_device, dtype=_dtype
)
- pts_norm = tensor(
+ pts_norm = torch.tensor(
[[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
device=_device,
dtype=_dtype,
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index c5b84e3e9..e9152b8c6 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _tuple_range_reader
-from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
@@ -40,9 +39,9 @@ class RotationGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - yaw (Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (Tensor): element-wise rotation rolls with a shape of (B,).
+ - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -54,7 +53,7 @@ class RotationGenerator3D(RandomGeneratorBase):
def __init__(
self,
degrees: Union[
- Tensor,
+ torch.Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
@@ -73,7 +72,7 @@ class RotationGenerator3D(RandomGeneratorBase):
self.pitch_sampler = UniformDistribution(degrees[1][0], degrees[1][1], validate_args=False)
self.roll_sampler = UniformDistribution(degrees[2][0], degrees[2][1], validate_args=False)
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.degrees])
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 299f3c06f..df4b2fc44 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -15,13 +15,13 @@
# limitations under the License.
#
-from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar
+from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union
import torch
+from torch import nn
from torch.distributions import Distribution, Uniform
from kornia.augmentation.utils.helpers import MultiprocessWrapper
-from kornia.core import Device, Module, Tensor
T = TypeVar("T")
@@ -35,10 +35,10 @@ class _PostInitInjectionMetaClass(type):
return obj
-class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
+class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
"""Base class for generating random augmentation parameters."""
- device: Optional[Device] = None
+ device: Optional[Union[str, torch.device, None]] = None
dtype: torch.dtype
def __init__(self) -> None:
@@ -74,7 +74,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
raise NotImplementedError
- def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
raise NotImplementedError
@@ -104,23 +104,23 @@ class DistributionWithMapper(Distribution):
"""
- def __init__(self, dist: Distribution, map_fn: Optional[Callable[[Tensor], Tensor]] = None) -> None:
+ def __init__(self, dist: Distribution, map_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None) -> None:
self.dist = dist
self.map_fn = map_fn
- def rsample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override]
+ def rsample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
out = self.dist.rsample(torch.Size(sample_shape))
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override]
+ def sample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
out = self.dist.sample(torch.Size(sample_shape))
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample_n(self, n: int) -> Tensor:
+ def sample_n(self, n: int) -> torch.Tensor:
out = self.dist.sample_n(n)
if self.map_fn is not None:
out = self.map_fn(out)
diff --git a/kornia/augmentation/random_generator/utils.py b/kornia/augmentation/random_generator/utils.py
index 2e3582d06..eb67e97ae 100644
--- a/kornia/augmentation/random_generator/utils.py
+++ b/kornia/augmentation/random_generator/utils.py
@@ -19,10 +19,8 @@ from typing import Any
import torch
-from kornia.core import Tensor
-
-def randperm(n: int, ensure_perm: bool = True, **kwargs: Any) -> Tensor:
+def randperm(n: int, ensure_perm: bool = True, **kwargs: Any) -> torch.Tensor:
"""`randomperm` with the ability to ensure the different arrangement generated."""
perm = torch.randperm(n, **kwargs)
if ensure_perm:
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 1507532b5..11c541d35 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -21,7 +21,6 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
from torch.distributions import Beta, Uniform
-from kornia.core import Tensor, as_tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.utils import _extract_device_dtype
@@ -31,7 +30,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 2D input of the wrapped function.
Args:
- f: a function that takes the first argument as tensor.
+ f: a function that takes the first argument as torch.tensor.
Returns:
the wrapped function after input is validated.
@@ -39,9 +38,9 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
"""
@wraps(f)
- def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(input: torch.Tensor, *args: Any, **kwargs: Any) -> Any:
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
_validate_shape(input.shape, required_shapes=("BCHW",))
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -55,7 +54,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 3D input of the wrapped function.
Args:
- f: a function that takes the first argument as tensor.
+ f: a function that takes the first argument as torch.tensor.
Returns:
the wrapped function after input is validated.
@@ -63,9 +62,9 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
"""
@wraps(f)
- def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(input: torch.Tensor, *args: Any, **kwargs: Any) -> Any:
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
input_shape = len(input.shape)
if input_shape != 5:
@@ -77,35 +76,37 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
return wrapper
-def _infer_batch_shape(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size:
+def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape.
- Input may be either (tensor,) or (tensor, transform_matrix)
+ Input may be either (torch.tensor,) or (torch.tensor, transform_matrix)
"""
if isinstance(input, tuple):
- tensor = _transform_input(input[0])
+ tensor_var = _transform_input(input[0])
else:
- tensor = _transform_input(input)
- return tensor.shape
+ tensor_var = _transform_input(input)
+ return tensor_var.shape
-def _infer_batch_shape3d(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size:
+def _infer_batch_shape3d(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape.
- Input may be either (tensor,) or (tensor, transform_matrix)
+ Input may be either (torch.tensor,) or (torch.tensor, transform_matrix)
"""
if isinstance(input, tuple):
- tensor = _transform_input3d(input[0])
+ tensor_var = _transform_input3d(input[0])
else:
- tensor = _transform_input3d(input)
- return tensor.shape
+ tensor_var = _transform_input3d(input)
+ return tensor_var.shape
-def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
- """Reshape an input tensor to have the same dimensions as the reference_shape.
+def _transform_input_by_shape(
+ input: torch.Tensor, reference_shape: torch.Tensor, match_channel: bool = True
+) -> torch.Tensor:
+ """Reshape an input torch.tensor to have the same dimensions as the reference_shape.
Arguments:
- input: tensor to be transformed
+ input: torch.tensor to be transformed
reference_shape: shape used as reference
match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
@@ -123,18 +124,20 @@ def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_chan
if match_channel and C:
if not input.shape[-3] == C:
- raise ValueError("The C dimension of tensor did not match with the reference tensor.")
+ raise ValueError("The C dimension of torch.tensor did not match with the reference torch.tensor.")
elif match_channel and C is None:
- raise ValueError("The reference tensor do not have a C dimension!")
+ raise ValueError("The reference torch.tensor do not have a C dimension!")
return input
-def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
- """Reshape an input tensor to have the same dimensions as the reference_shape.
+def _transform_input3d_by_shape(
+ input: torch.Tensor, reference_shape: torch.Tensor, match_channel: bool = True
+) -> torch.Tensor:
+ """Reshape an input torch.tensor to have the same dimensions as the reference_shape.
Arguments:
- input: tensor to be transformed
+ input: torch.tensor to be transformed
reference_shape: shape used as reference
match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
@@ -152,25 +155,25 @@ def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_ch
if match_channel and C:
if not input.shape[-4] == C:
- raise ValueError("The C dimension of tensor did not match with the reference tensor.")
+ raise ValueError("The C dimension of torch.tensor did not match with the reference torch.tensor.")
elif match_channel and C is None:
- raise ValueError("The reference tensor do not have a C dimension!")
+ raise ValueError("The reference torch.tensor do not have a C dimension!")
return input
-def _transform_input(input: Tensor) -> Tensor:
- r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
+def _transform_input(input: torch.Tensor) -> torch.Tensor:
+ r"""Reshape an input torch.tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
Args:
- input: Tensor
+ input: torch.Tensor
Returns:
- Tensor
+ torch.Tensor
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) not in [2, 3, 4]:
raise ValueError(f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")
@@ -184,18 +187,18 @@ def _transform_input(input: Tensor) -> Tensor:
return input
-def _transform_input3d(input: Tensor) -> Tensor:
- r"""Reshape an input tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).
+def _transform_input3d(input: torch.Tensor) -> torch.Tensor:
+ r"""Reshape an input torch.tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).
Args:
- input: Tensor
+ input: torch.Tensor
Returns:
- Tensor
+ torch.Tensor
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) not in [3, 4, 5]:
raise ValueError(
@@ -211,11 +214,11 @@ def _transform_input3d(input: Tensor) -> Tensor:
return input
-def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) -> None:
- r"""Check if the dtype of the input tensor is in the range of accepted_dtypes.
+def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List[torch.dtype]) -> None:
+ r"""Check if the dtype of the input torch.tensor is in the range of accepted_dtypes.
Args:
- input: Tensor
+ input: torch.Tensor
accepted_dtypes: List. e.g. [torch.float32, torch.float64]
"""
if input.dtype not in accepted_dtypes:
@@ -223,17 +226,17 @@ def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) ->
def _transform_output_shape(
- output: Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[Tensor] = None
-) -> Tensor:
- r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
+ output: torch.Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[torch.Tensor] = None
+) -> torch.Tensor:
+ r"""Collapse the broadcasted batch dimensions an input torch.tensor to be the specified shape.
Args:
- output: Tensor
+ output: torch.Tensor
shape: List/tuple of int
- reference_shape: Tensor representation of shape to control which dimensions are collapsed.
+ reference_shape: torch.Tensor representation of shape to control which dimensions are collapsed.
Returns:
- Tensor
+ torch.Tensor
"""
out_tensor = output.clone()
@@ -250,10 +253,10 @@ def _transform_output_shape(
def _validate_shape(shape: Union[Tuple[int, ...], torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
- r"""Check if the dtype of the input tensor is in the range of accepted_dtypes.
+ r"""Check if the dtype of the input torch.tensor is in the range of accepted_dtypes.
Args:
- shape: tensor shape
+ shape: torch.tensor shape
required_shapes: List. e.g. ["BCHW", "BCDHW"]
"""
passed = False
@@ -265,7 +268,7 @@ def _validate_shape(shape: Union[Tuple[int, ...], torch.Size], required_shapes:
raise TypeError(f"Expected input shape in {required_shape}. Got {shape}.")
-def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> bool:
+def _validate_input_shape(input: torch.Tensor, channel_index: int, number: int) -> bool:
r"""Validate if an input has the right shape.
e.g. to check if an input is channel first.
@@ -273,7 +276,7 @@ def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> boo
_validate_input_shape(input, 1, 3)
Args:
- input: Tensor
+ input: torch.Tensor
channel_index: int
number: int
Returns:
@@ -287,7 +290,7 @@ def _adapted_rsampling(
shape: Union[Tuple[int, ...], torch.Size],
dist: torch.distributions.Distribution,
same_on_batch: Optional[bool] = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Sample from a uniform reparameterized sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
@@ -307,7 +310,7 @@ def _adapted_sampling(
shape: Union[Tuple[int, ...], torch.Size],
dist: torch.distributions.Distribution,
same_on_batch: Optional[bool] = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Sample from a uniform sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
@@ -323,23 +326,23 @@ def _adapted_sampling(
def _adapted_uniform(
shape: Union[Tuple[int, ...], torch.Size],
- low: Union[float, Tensor],
- high: Union[float, Tensor],
+ low: Union[float, torch.Tensor],
+ high: Union[float, torch.Tensor],
same_on_batch: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Sample from a uniform sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
same_on_batch is set to False.
- By default, sampling happens on the default device and dtype. If low/high is a tensor, sampling will happen in the
- same device/dtype as low/high tensor.
+ By default, sampling happens on the default device and dtype. If low/high is a torch.tensor,
+ sampling will happen in the same device/dtype as low/high torch.tensor.
"""
device, dtype = _extract_device_dtype(
- [low if isinstance(low, Tensor) else None, high if isinstance(high, Tensor) else None]
+ [low if isinstance(low, torch.Tensor) else None, high if isinstance(high, torch.Tensor) else None]
)
- low = as_tensor(low, device=device, dtype=dtype)
- high = as_tensor(high, device=device, dtype=dtype)
+ low = torch.as_tensor(low, device=device, dtype=dtype)
+ high = torch.as_tensor(high, device=device, dtype=dtype)
# validate_args=False to fix pytorch 1.7.1 error:
# ValueError: Uniform is not defined when low>= high.
dist = Uniform(low, high, validate_args=False)
@@ -348,26 +351,28 @@ def _adapted_uniform(
def _adapted_beta(
shape: Union[Tuple[int, ...], torch.Size],
- a: Union[float, Tensor],
- b: Union[float, Tensor],
+ a: Union[float, torch.Tensor],
+ b: Union[float, torch.Tensor],
same_on_batch: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Sample from a beta sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
same_on_batch is set to False.
- By default, sampling happens on the default device and dtype. If a/b is a tensor, sampling will happen in the same
- device/dtype as a/b tensor.
+ By default, sampling happens on the default device and dtype. If a/b is a torch.tensor,
+ sampling will happen in the same device/dtype as a/b torch.tensor.
"""
- device, dtype = _extract_device_dtype([a if isinstance(a, Tensor) else None, b if isinstance(b, Tensor) else None])
- a = as_tensor(a, device=device, dtype=dtype)
- b = as_tensor(b, device=device, dtype=dtype)
+ device, dtype = _extract_device_dtype(
+ [a if isinstance(a, torch.Tensor) else None, b if isinstance(b, torch.Tensor) else None]
+ )
+ a = torch.as_tensor(a, device=device, dtype=dtype)
+ b = torch.as_tensor(b, device=device, dtype=dtype)
dist = Beta(a, b, validate_args=False)
return _adapted_rsampling(shape, dist, same_on_batch)
-def _shape_validation(param: Tensor, shape: Union[Tuple[int, ...], List[int]], name: str) -> None:
+def _shape_validation(param: torch.Tensor, shape: Union[Tuple[int, ...], List[int]], name: str) -> None:
if param.shape != torch.Size(shape):
raise AssertionError(f"Invalid shape for {name}. Expected {shape}. Got {param.shape}")
@@ -375,12 +380,12 @@ def _shape_validation(param: Tensor, shape: Union[Tuple[int, ...], List[int]], n
def deepcopy_dict(params: Dict[str, Any]) -> Dict[str, Any]:
"""Perform deep copy on any dict.
- Support tensor copying here.
+ Support torch.tensor copying here.
"""
out = {}
for k, v in params.items():
# NOTE: Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol
- if isinstance(v, Tensor):
+ if isinstance(v, torch.Tensor):
out.update({k: v.clone()})
else:
out.update({k: v})
@@ -418,7 +423,7 @@ def override_parameters(
return out
-def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -> Boxes:
+def preprocess_boxes(input: Union[torch.Tensor, Boxes], mode: str = "vertices_plus") -> Boxes:
r"""Preprocess input boxes.
Args:
@@ -426,24 +431,26 @@ def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -
See below for more details.
mode: The format in which the boxes are provided.
- * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin``
+ * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` torch.where
+ ``width = xmax - xmin``
and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
- * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as
+ * 'xyxy_plus': similar to 'xyxy' mode but torch.where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.
With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
- * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where
+ * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` torch.where
``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
* 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:
*top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,
box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.
With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
- * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
+ * 'vertices_plus': similar to 'vertices' mode but torch.where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
Note:
- **2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2``
- where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by it's 4 vertices
+ **2D boxes format** is defined as a floating data type torch.tensor of shape ``Nx4x2`` or ``BxNx4x2``
+ torch.where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by
+ it's 4 vertices
coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of a box is defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of
`quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
@@ -451,28 +458,28 @@ def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -
"""
# TODO: We may allow list here.
# input is BxNx4x2 or Boxes.
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
- raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx4x2 torch.tensor is supported. Got {input.shape}.")
input = Boxes.from_tensor(input, mode=mode)
if not isinstance(input, Boxes):
raise RuntimeError(f"Expect `Boxes` type. Got {type(input)}.")
return input
-def preprocess_keypoints(input: Union[Tensor, Keypoints]) -> Keypoints:
+def preprocess_keypoints(input: Union[torch.Tensor, Keypoints]) -> Keypoints:
"""Preprocess input keypoints."""
# TODO: We may allow list here.
- if isinstance(input, Tensor):
+ if isinstance(input, torch.Tensor):
if not (len(input.shape) == 3 and input.shape[1:] == torch.Size([2])):
- raise RuntimeError(f"Only BxNx2 tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx2 torch.tensor is supported. Got {input.shape}.")
input = Keypoints(input, False)
if isinstance(input, Keypoints):
raise RuntimeError(f"Expect `Keypoints` type. Got {type(input)}.")
return input
-def preprocess_classes(input: Tensor) -> Tensor:
+def preprocess_classes(input: torch.Tensor) -> torch.Tensor:
"""Preprocess input class tags."""
# TODO: We may allow list here.
return input
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 0a2e74021..c81a28461 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -19,8 +19,6 @@ from typing import Any, List, Optional, Tuple, Union
import torch
-from kornia.core import Tensor, as_tensor, tensor
-
def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -> None:
"""Check valid batch_size and same_on_batch params."""
@@ -31,22 +29,22 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -
def _range_bound(
- factor: Union[Tensor, float, Tuple[float, float], List[float]],
+ factor: Union[torch.Tensor, float, Tuple[float, float], List[float]],
name: str,
center: Optional[float] = 0.0,
bounds: Optional[Tuple[float, float]] = (0, float("inf")),
check: Optional[str] = "joint",
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
r"""Check inputs and compute the corresponding factor bounds."""
if device is None:
device = torch.device("cpu")
if dtype is None:
dtype = torch.get_default_dtype()
- if not isinstance(factor, (Tensor)):
- factor = tensor(factor, device=device, dtype=dtype)
- factor_bound: Tensor
+ if not isinstance(factor, (torch.Tensor)):
+ factor = torch.tensor(factor, device=device, dtype=dtype)
+ factor_bound: torch.Tensor
if factor.dim() == 0:
if factor < 0:
@@ -56,10 +54,10 @@ def _range_bound(
# Should be something other than clamp
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
- factor_bound = factor.repeat(2) * tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
+ factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
factor_bound = factor_bound.clamp(bounds[0], bounds[1]).to(device=device, dtype=dtype)
else:
- factor_bound = as_tensor(factor, device=device, dtype=dtype)
+ factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
if check is not None:
if check == "joint":
@@ -72,7 +70,7 @@ def _range_bound(
return factor_bound
-def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
+def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
"""Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]."""
if bounds is None:
bounds = (float("-inf"), float("inf"))
@@ -83,11 +81,13 @@ def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[
if not bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]:
raise ValueError(f"{name}[0] should be smaller than {name}[1] got {ranged_factor}")
else:
- raise TypeError(f"{name} should be a tensor with length 2 whose values between {bounds}. Got {ranged_factor}.")
+ raise TypeError(
+ f"{name} should be a torch.tensor with length 2 whose values between {bounds}. Got {ranged_factor}."
+ )
def _singular_range_check(
- ranged_factor: Tensor,
+ ranged_factor: torch.Tensor,
name: str,
bounds: Optional[Tuple[float, float]] = None,
skip_none: bool = False,
@@ -117,15 +117,17 @@ def _singular_range_check(
def _tuple_range_reader(
- input_range: Union[Tensor, float, Tuple[Any, ...]],
+ input_range: Union[torch.Tensor, float, Tuple[Any, ...]],
target_size: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
- """Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.
+) -> torch.Tensor:
+ """Given target_size, it will generate the corresponding (target_size, 2) range torch.tensor.
+
+ This is for element-wise params.
Example:
- >>> degree = tensor([0.2, 0.3])
+ >>> degree = torch.tensor([0.2, 0.3])
>>> _tuple_range_reader(degree, 3) # read degree for yaw, pitch and roll.
tensor([[0.2000, 0.3000],
[0.2000, 0.3000],
@@ -134,11 +136,11 @@ def _tuple_range_reader(
"""
target_shape = torch.Size([target_size, 2])
- if isinstance(input_range, Tensor):
+ if isinstance(input_range, torch.Tensor):
if (len(input_range.shape) == 0) or (len(input_range.shape) == 1 and len(input_range) == 1):
if input_range < 0:
raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
- input_range_tmp = input_range.repeat(2).to(device=device, dtype=dtype) * tensor(
+ input_range_tmp = input_range.repeat(2).to(device=device, dtype=dtype) * torch.tensor(
[-1, 1], device=device, dtype=dtype
)
input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)
@@ -147,7 +149,7 @@ def _tuple_range_reader(
input_range_tmp = input_range.repeat(target_shape[0], 1).to(device=device, dtype=dtype)
elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]:
- input_range_tmp = input_range.unsqueeze(1).repeat(1, 2).to(device=device, dtype=dtype) * tensor(
+ input_range_tmp = input_range.unsqueeze(1).repeat(1, 2).to(device=device, dtype=dtype) * torch.tensor(
[-1, 1], device=device, dtype=dtype
)
@@ -156,13 +158,15 @@ def _tuple_range_reader(
else:
raise ValueError(
- f"Degrees must be a {list(target_shape)} tensor for the degree range for independent operation."
+ f"Degrees must be a {list(target_shape)} torch.tensor for the degree range for independent operation."
f"Got {input_range}"
)
elif isinstance(input_range, (float, int)):
if input_range < 0:
raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
- input_range_tmp = tensor([-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1)
+ input_range_tmp = torch.tensor([-input_range, input_range], device=device, dtype=dtype).repeat(
+ target_shape[0], 1
+ )
elif (
isinstance(input_range, (tuple, list))
@@ -170,25 +174,25 @@ def _tuple_range_reader(
and isinstance(input_range[0], (float, int))
and isinstance(input_range[1], (float, int))
):
- input_range_tmp = tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
+ input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
elif (
isinstance(input_range, (tuple, list))
and len(input_range) == target_shape[0]
and all(isinstance(x, (float, int)) for x in input_range)
):
- input_range_tmp = tensor([(-s, s) for s in input_range], device=device, dtype=dtype)
+ input_range_tmp = torch.tensor([(-s, s) for s in input_range], device=device, dtype=dtype)
elif (
isinstance(input_range, (tuple, list))
and len(input_range) == target_shape[0]
and all(isinstance(x, (tuple, list)) for x in input_range)
):
- input_range_tmp = tensor(input_range, device=device, dtype=dtype)
+ input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype)
else:
raise TypeError(
- "If not pass a tensor, it must be float, (float, float) for isotropic operation or a tuple of "
+ "If not pass a torch.tensor, it must be float, (float, float) for isotropic operation or a tuple of "
f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}."
)
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index c12955386..eca2845fd 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -20,7 +20,7 @@
This subpackage provides modules for color transformations, colormaps, and conversions.
"""
-from .colormap import AUTUMN, ApplyColorMap, ColorMap, ColorMapType, RGBColor, apply_colormap
+from .colormap import ApplyColorMap, ColorMap, ColorMapType, RGBColor, apply_colormap
from .gray import BgrToGrayscale, GrayscaleToRgb, RgbToGrayscale, bgr_to_grayscale, grayscale_to_rgb, rgb_to_grayscale
from .hls import HlsToRgb, RgbToHls, hls_to_rgb, rgb_to_hls
from .hsv import HsvToRgb, RgbToHsv, hsv_to_rgb, rgb_to_hsv
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index b1635b601..04bf65a6f 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -21,13 +21,12 @@ from enum import Enum
from typing import Optional, Union
import torch
+from torch import nn
from torch.nn.functional import interpolate
import kornia.color._colormap_data as cm_data
from kornia.color._colormap_data import RGBColor
-from kornia.core import Module, Tensor, tensor
from kornia.core.check import KORNIA_CHECK
-from kornia.utils.helpers import deprecated
class ColorMapType(Enum):
@@ -158,18 +157,18 @@ class ColorMap:
self.colors = self._generate_color_map(base_colormap_data, num_colors)
- def _generate_color_map(self, base_colormap: list[RGBColor], num_colors: int) -> Tensor:
- r"""Generate a colormap tensor using interpolation.
+ def _generate_color_map(self, base_colormap: list[RGBColor], num_colors: int) -> torch.Tensor:
+ r"""Generate a colormap torch.tensor using interpolation.
Args:
base_colormap: A list of RGB colors defining the colormap.
num_colors: Number of colors in the colormap.
Returns:
- A tensor representing the colormap.
+ A torch.tensor representing the colormap.
"""
- tensor_colors = tensor(list(base_colormap), dtype=self._dtype, device=self._device).T
+ tensor_colors = torch.tensor(list(base_colormap), dtype=self._dtype, device=self._device).T
return interpolate(tensor_colors[None, ...], size=num_colors, mode="linear")[0, ...]
def __len__(self) -> int:
@@ -182,23 +181,23 @@ class ColorMap:
return self.colors.shape[-1]
-def apply_colormap(input_tensor: Tensor, colormap: ColorMap) -> Tensor:
- r"""Apply to a gray tensor a colormap.
+def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tensor:
+ r"""Apply to a gray torch.tensor a colormap.
.. image:: _static/img/apply_colormap.png
Args:
- input_tensor: the input tensor of image.
- colormap: the colormap desired to be applied to the input tensor.
+ input_tensor: the input torch.tensor of image.
+ colormap: the colormap desired to be applied to the input torch.tensor.
Returns:
- A RGB tensor with the applied color map into the input_tensor.
+ A RGB torch.tensor with the applied color map into the input_tensor.
Raises:
ValueError: If `colormap` is not a ColorMap object.
.. note::
- The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Example:
>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])
@@ -217,12 +216,14 @@ def apply_colormap(input_tensor: Tensor, colormap: ColorMap) -> Tensor:
[0.0000, 0.0000, 0.0000]]]])
"""
- KORNIA_CHECK(isinstance(input_tensor, Tensor), f"`input_tensor` must be a Tensor. Got: {type(input_tensor)}")
+ KORNIA_CHECK(
+ isinstance(input_tensor, torch.Tensor), f"`input_tensor` must be a torch.Tensor. Got: {type(input_tensor)}"
+ )
valid_types = [torch.half, torch.float, torch.double, torch.uint8, torch.int, torch.long, torch.short]
KORNIA_CHECK(
input_tensor.dtype in valid_types, f"`input_tensor` must be a {valid_types}. Got: {input_tensor.dtype}"
)
- KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input tensor dimension.")
+ KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input torch.tensor dimension.")
if len(input_tensor.shape) == 3:
input_tensor = input_tensor.unsqueeze_(0)
@@ -243,7 +244,7 @@ def apply_colormap(input_tensor: Tensor, colormap: ColorMap) -> Tensor:
return output
-class ApplyColorMap(Module):
+class ApplyColorMap(nn.Module):
r"""Class for applying a colormap to images.
.. image:: _static/img/ApplyColorMap.png
@@ -255,13 +256,13 @@ class ApplyColorMap(Module):
dtype: The data type of the generated colormap.
Returns:
- A RGB tensor with the applied color map into the input_tensor
+ A RGB torch.tensor with the applied color map into the input_tensor
Raises:
ValueError: If `colormap` is not a ColorMap object.
.. note::
- The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Example:
>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])
@@ -288,35 +289,17 @@ class ApplyColorMap(Module):
super().__init__()
self.colormap = colormap
- def forward(self, input_tensor: Tensor) -> Tensor:
- r"""Apply the colormap to the input tensor.
+ def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
+ r"""Apply the colormap to the input torch.tensor.
Args:
- input_tensor: The input tensor representing the grayscale image.
+ input_tensor: The input torch.tensor representing the grayscale image.
.. note::
- The input tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Returns:
- The output tensor representing the image with the applied colormap.
+ The output torch.tensor representing the image with the applied colormap.
"""
return apply_colormap(input_tensor, self.colormap)
-
-
-# Generate complete color map
-@deprecated(
- "0.7.2",
- extra_reason="The `AUTUMN()` class is deprecated and will be removed in next kornia versions (0.8.0 - dec 2024).\
- In favor of using `ColorMap(base='autumn')` instead.",
-)
-class AUTUMN(ColorMap):
- r"""The GNU Octave colormap `autumn`.
-
- .. image:: _static/img/AUTUMN.png
- """
-
- def __init__(
- self, num_colors: int = 64, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
- ) -> None:
- super().__init__(base=ColorMapType.autumn, num_colors=num_colors, device=device, dtype=dtype)
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 32ee31c8d..8c5f7331b 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -20,14 +20,13 @@ from __future__ import annotations
from typing import ClassVar, Optional
import torch
+from torch import nn
from kornia.color.rgb import bgr_to_rgb
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_IS_TENSOR
-def grayscale_to_rgb(image: Tensor) -> Tensor:
+def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert a grayscale image to RGB version of image.
.. image:: _static/img/grayscale_to_rgb.png
@@ -35,7 +34,7 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
The image data is assumed to be in the range of (0, 1).
Args:
- image: grayscale image tensor to be converted to RGB with shape :math:`(*,1,H,W)`.
+ image: grayscale image torch.tensor to be converted to RGB with shape :math:`(*,1,H,W)`.
Returns:
RGB version of the image with shape :math:`(*,3,H,W)`.
@@ -56,7 +55,7 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
return image.expand(*shape)
-def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Tensor:
+def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Convert a RGB image to grayscale version of image.
.. image:: _static/img/rgb_to_grayscale.png
@@ -94,19 +93,19 @@ def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Ten
else:
raise TypeError(f"Unknown data type: {image.dtype}")
else:
- # is tensor that we make sure is in the same device/dtype
+ # is torch.tensor that we make sure is in the same device/dtype
rgb_weights = rgb_weights.to(image)
# unpack the color image channels with RGB order
- r: Tensor = image[..., 0:1, :, :]
- g: Tensor = image[..., 1:2, :, :]
- b: Tensor = image[..., 2:3, :, :]
+ r: torch.Tensor = image[..., 0:1, :, :]
+ g: torch.Tensor = image[..., 1:2, :, :]
+ b: torch.Tensor = image[..., 2:3, :, :]
w_r, w_g, w_b = rgb_weights.unbind()
return w_r * r + w_g * g + w_b * b
-def bgr_to_grayscale(image: Tensor) -> Tensor:
+def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:
r"""Convert a BGR image to grayscale.
The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.
@@ -127,12 +126,12 @@ def bgr_to_grayscale(image: Tensor) -> Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- image_rgb: Tensor = bgr_to_rgb(image)
+ image_rgb: torch.Tensor = bgr_to_rgb(image)
return rgb_to_grayscale(image_rgb)
-class GrayscaleToRgb(Module):
- r"""Module to convert a grayscale image to RGB version of image.
+class GrayscaleToRgb(nn.Module):
+ r"""nn.Module to convert a grayscale image to RGB version of image.
The image data is assumed to be in the range of (0, 1).
@@ -153,12 +152,12 @@ class GrayscaleToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return grayscale_to_rgb(image)
-class RgbToGrayscale(Module):
- r"""Module to convert a RGB image to grayscale version of image.
+class RgbToGrayscale(nn.Module):
+ r"""nn.Module to convert a RGB image to grayscale version of image.
The image data is assumed to be in the range of (0, 1).
@@ -179,18 +178,18 @@ class RgbToGrayscale(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]
- def __init__(self, rgb_weights: Optional[Tensor] = None) -> None:
+ def __init__(self, rgb_weights: Optional[torch.Tensor] = None) -> None:
super().__init__()
if rgb_weights is None:
- rgb_weights = Tensor([0.299, 0.587, 0.114])
+ rgb_weights = torch.Tensor([0.299, 0.587, 0.114])
self.rgb_weights = rgb_weights
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_grayscale(image, rgb_weights=self.rgb_weights)
-class BgrToGrayscale(Module):
- r"""Module to convert a BGR image to grayscale version of image.
+class BgrToGrayscale(nn.Module):
+ r"""nn.Module to convert a BGR image to grayscale version of image.
The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.
@@ -211,5 +210,5 @@ class BgrToGrayscale(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return bgr_to_grayscale(image)
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 8e9f449cb..109086fd2 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -21,12 +21,10 @@ import math
from typing import ClassVar
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, stack, tensor, where
-
-def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:
+def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert an RGB image to HLS.
.. image:: _static/img/rgb_to_hls.png
@@ -47,30 +45,30 @@ def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:
>>> output = rgb_to_hls(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- _RGB2HSL_IDX = tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+ _RGB2HSL_IDX = torch.tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1
- _img_max: tuple[Tensor, Tensor] = image.max(-3)
+ _img_max: tuple[torch.Tensor, torch.Tensor] = image.max(-3)
maxc = _img_max[0]
imax = _img_max[1]
- minc: Tensor = image.min(-3)[0]
+ minc: torch.Tensor = image.min(-3)[0]
if image.requires_grad:
l_ = maxc + minc
s = maxc - minc
# weird behaviour with undefined vars in JIT...
# scripting requires image_hls be defined even if it is not used :S
- h = l_ # assign to any tensor...
- image_hls = l_ # assign to any tensor...
+ h = l_ # assign to any torch.tensor...
+ image_hls = l_ # assign to any torch.tensor...
else:
# define the resulting image to avoid the torch.stack([h, l, s])
# so, h, l and s require inplace operations
- # NOTE: stack() increases in a 10% the cost in colab
+ # NOTE: torch.stack() increases in a 10% the cost in colab
image_hls = torch.empty_like(image)
h, l_, s = (
image_hls[..., 0, :, :],
@@ -84,7 +82,7 @@ def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:
im = image / (s + eps).unsqueeze(-3)
# epsilon cannot be inside the torch.where to avoid precision issues
- s /= where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation
+ s /= torch.where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation
l_ /= 2 # luminance
# note that r,g and b were previously div by (max - min)
@@ -104,11 +102,11 @@ def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:
h *= math.pi / 3.0 # hue [0, 2*pi]
if image.requires_grad:
- return stack([h, l_, s], -3)
+ return torch.stack([h, l_, s], -3)
return image_hls
-def hls_to_rgb(image: Tensor) -> Tensor:
+def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert a HLS image to RGB.
The image data is assumed to be in the range of (0, 1).
@@ -124,32 +122,32 @@ def hls_to_rgb(image: Tensor) -> Tensor:
>>> output = hls_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- _HLS2RGB = tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+ _HLS2RGB = torch.tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1
- im: Tensor = image.unsqueeze(-4)
- h_ch: Tensor = im[..., 0, :, :]
- l_ch: Tensor = im[..., 1, :, :]
- s_ch: Tensor = im[..., 2, :, :]
+ im: torch.Tensor = image.unsqueeze(-4)
+ h_ch: torch.Tensor = im[..., 0, :, :]
+ l_ch: torch.Tensor = im[..., 1, :, :]
+ s_ch: torch.Tensor = im[..., 2, :, :]
h_ch = h_ch * (6 / math.pi) # h * 360 / (2 * math.pi) / 30
a = s_ch * torch.min(l_ch, 1.0 - l_ch)
# kr = (0 + h) % 12
# kg = (8 + h) % 12
# kb = (4 + h) % 12
- k: Tensor = (h_ch + _HLS2RGB) % 12
+ k: torch.Tensor = (h_ch + _HLS2RGB) % 12
# l - a * max(min(min(k - 3.0, 9.0 - k), 1), -1)
mink = torch.min(k - 3.0, 9.0 - k)
return torch.addcmul(l_ch, a, mink.clamp_(min=-1.0, max=1.0), value=-1)
-class RgbToHls(Module):
+class RgbToHls(nn.Module):
r"""Convert an image from RGB to HLS.
The image data is assumed to be in the range of (0, 1).
@@ -171,11 +169,11 @@ class RgbToHls(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_hls(image)
-class HlsToRgb(Module):
+class HlsToRgb(nn.Module):
r"""Convert an image from HLS to RGB.
The image data is assumed to be in the range of (0, 1).
@@ -200,5 +198,5 @@ class HlsToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return hls_to_rgb(image)
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index 25f4a0cd0..8809efbf8 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -21,8 +21,7 @@ import math
from typing import ClassVar
import torch
-
-from kornia.core import ImageModule as Module
+from torch import nn
def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
@@ -116,7 +115,7 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
return out
-class RgbToHsv(Module):
+class RgbToHsv(nn.Module):
r"""Convert an image from RGB to HSV.
The image data is assumed to be in the range of (0, 1).
@@ -149,7 +148,7 @@ class RgbToHsv(Module):
return rgb_to_hsv(image, self.eps)
-class HsvToRgb(Module):
+class HsvToRgb(nn.Module):
r"""Convert an image from HSV to RGB.
H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.
diff --git a/kornia/color/lab.py b/kornia/color/lab.py
index 7f66c2f95..6a46fe8cc 100644
--- a/kornia/color/lab.py
+++ b/kornia/color/lab.py
@@ -25,8 +25,7 @@ from __future__ import annotations
from typing import ClassVar
import torch
-
-from kornia.core import ImageModule as Module
+from torch import nn
from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb
from .xyz import rgb_to_xyz, xyz_to_rgb
@@ -63,7 +62,7 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
xyz_im: torch.Tensor = rgb_to_xyz(lin_rgb)
- # normalize for D65 white point
+ # F.normalize for D65 white point
xyz_ref_white = torch.tensor([0.95047, 1.0, 1.08883], device=xyz_im.device, dtype=xyz_im.dtype)[..., :, None, None]
xyz_normalized = torch.div(xyz_im, xyz_ref_white)
@@ -147,7 +146,7 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
return rgb_im
-class RgbToLab(Module):
+class RgbToLab(nn.Module):
r"""Convert an image from RGB to Lab.
The image data is assumed to be in the range of :math:`[0, 1]`. Lab
@@ -181,7 +180,7 @@ class RgbToLab(Module):
return rgb_to_lab(image)
-class LabToRgb(Module):
+class LabToRgb(nn.Module):
r"""Convert an image from Lab to RGB.
Returns:
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index 79d120d3b..073712cdf 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -25,8 +25,7 @@ from __future__ import annotations
from typing import ClassVar
import torch
-
-from kornia.core import ImageModule as Module
+from torch import nn
from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb
from .xyz import rgb_to_xyz, xyz_to_rgb
@@ -140,7 +139,7 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
return rgb_im
-class RgbToLuv(Module):
+class RgbToLuv(nn.Module):
r"""Convert an image from RGB to Luv.
The image data is assumed to be in the range of :math:`[0, 1]`. Luv
@@ -174,7 +173,7 @@ class RgbToLuv(Module):
return rgb_to_luv(image)
-class LuvToRgb(Module):
+class LuvToRgb(nn.Module):
r"""Convert an image from Luv to RGB.
Returns:
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index a38ee1f3d..f8766d4d7 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -21,9 +21,9 @@ from enum import Enum
from typing import ClassVar
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, concatenate
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
@@ -36,7 +36,7 @@ class CFA(Enum):
On top of this care is taken to make it reversible going raw -> rgb -> raw. the raw samples remain intact
during conversion and only unknown samples are interpolated.
- The names are based on the OpenCV convention where the BG indicates pixel 1,1 (counting from 0,0) is
+ The names are based on the OpenCV convention torch.where the BG indicates pixel 1,1 (counting from 0,0) is
blue and its neighbour to the right is green. In that case the top left pixel is red. Other options are GB, RG and
GR
@@ -110,14 +110,14 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
raise ValueError(f"Unsupported CFA Got {cfa}.")
# upscaling r and b with bi-linear gives reasonable quality
- # Note that depending on where these are sampled we need to pad appropriately
+ # Note that depending on torch.where these are sampled we need to F.pad appropriately
# the bilinear filter will pretty much be based on for example this layout (RG)
# (which needs to be padded bottom right)
# +-+-+
# |B| |
# | | |
# +-+-+
- # While in this layout we need to pad with additional B samples top left to
+ # While in this layout we need to F.pad with additional B samples top left to
# make sure we interpolate from the correct position
# +-+-+
# | | |
@@ -142,22 +142,18 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
# evenly spaced between them while the B/R samples will be missing in the corners were they are assumed to exist
# Further we need to do align_corners to start the interpolation from the middle of the samples in the corners, that
# way we get to keep the known blue samples across the whole image
- rpadded = torch.nn.functional.pad(r, list(rpad), "replicate")
- bpadded = torch.nn.functional.pad(b, list(bpad), "replicate")
+ rpadded = F.pad(r, list(rpad), "replicate")
+ bpadded = F.pad(b, list(bpad), "replicate")
# use explicit padding instead of conv2d padding to be able to use reflect which mirror the correct colors
# for a 2x2 bayer filter
- gpadded = torch.nn.functional.pad(image, [1, 1, 1, 1], "reflect")
+ gpadded = F.pad(image, [1, 1, 1, 1], "reflect")
- r_up = torch.nn.functional.interpolate(
- rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True
- )
- b_up = torch.nn.functional.interpolate(
- bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True
- )
+ r_up = F.interpolate(rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True)
+ b_up = F.interpolate(bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True)
# remove the extra padding
- r_up = torch.nn.functional.pad(r_up, [-x for x in rpad])
- b_up = torch.nn.functional.pad(b_up, [-x for x in bpad])
+ r_up = F.pad(r_up, [-x for x in rpad])
+ b_up = F.pad(b_up, [-x for x in bpad])
# all unknown pixels are the average of the nearby green samples
kernel = torch.tensor(
@@ -165,7 +161,7 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
)
# This is done on all samples but result for the known green samples is then overwritten by the input
- g_up = torch.nn.functional.conv2d(gpadded, kernel)
+ g_up = F.conv2d(gpadded, kernel)
# overwrite the already known samples which otherwise have values from r/b
# this depends on the CFA configuration
@@ -216,7 +212,7 @@ def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- # pick the tensor with green pixels
+ # pick the torch.tensor with green pixels
# clone to make sure grad works
output: torch.Tensor = image[..., 1:2, :, :].clone()
@@ -237,7 +233,7 @@ def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
return output
-def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor:
+def raw_to_rgb_2x2_downscaled(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
r"""Convert the raw bayer image to RGB version of it and resize width and height by half.
This is done efficiently by converting each superpixel of bayer image to the corresponding rgb triplet.
@@ -260,7 +256,7 @@ def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor:
>>> rgb = raw_to_rgb_2x2_downscaled(rawinput, CFA.RG) # 2x3x2x3
"""
- KORNIA_CHECK(isinstance(image, Tensor), "Input type is not a torch.Tensor")
+ KORNIA_CHECK(isinstance(image, torch.Tensor), "Input type is not a torch.Tensor")
KORNIA_CHECK_SHAPE(image, ["*", "1", "H", "W"])
@@ -292,13 +288,13 @@ def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor:
else:
raise ValueError(f"Unsupported CFA Got {cfa}.")
- rgb: Tensor = concatenate([r, (g1 + g2) / 2, b], dim=-3)
+ rgb: torch.Tensor = torch.cat([r, (g1 + g2) / 2, b], dim=-3)
return rgb
-class RawToRgb(Module):
- r"""Module to convert a bayer raw image to RGB version of image.
+class RawToRgb(nn.Module):
+ r"""nn.Module to convert a bayer raw image to RGB version of image.
The image data is assumed to be in the range of (0, 1).
@@ -324,8 +320,8 @@ class RawToRgb(Module):
return raw_to_rgb(image, cfa=self.cfa)
-class RgbToRaw(Module):
- r"""Module to convert a RGB image to bayer raw version of image.
+class RgbToRaw(nn.Module):
+ r"""nn.Module to convert a RGB image to bayer raw version of image.
The image data is assumed to be in the range of (0, 1).
@@ -354,8 +350,8 @@ class RgbToRaw(Module):
return rgb_to_raw(image, cfa=self.cfa)
-class RawToRgb2x2Downscaled(Module):
- r"""Module version of the :func:`raw_to_rgb_2x2_downscaled()` function.
+class RawToRgb2x2Downscaled(nn.Module):
+ r"""nn.Module version of the :func:`raw_to_rgb_2x2_downscaled()` function.
The image width and height have to be divisible by two. The image
data is assumed to be in the range of (0, 1).
@@ -375,5 +371,5 @@ class RawToRgb2x2Downscaled(Module):
super().__init__()
self.cfa = cfa
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return raw_to_rgb_2x2_downscaled(image, cfa=self.cfa)
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 010a4a835..7eba91a36 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -20,13 +20,13 @@ from __future__ import annotations
from typing import ClassVar, Optional, Union, cast
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, as_tensor, normalize
from kornia.core.check import KORNIA_CHECK_IS_COLOR
-def rgb_to_bgr(image: Tensor) -> Tensor:
+def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
r"""Convert a RGB image to BGR.
.. image:: _static/img/rgb_to_bgr.png
@@ -42,8 +42,8 @@ def rgb_to_bgr(image: Tensor) -> Tensor:
>>> output = rgb_to_bgr(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
@@ -51,7 +51,7 @@ def rgb_to_bgr(image: Tensor) -> Tensor:
return bgr_to_rgb(image)
-def bgr_to_rgb(image: Tensor) -> Tensor:
+def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert a BGR image to RGB.
Args:
@@ -65,23 +65,23 @@ def bgr_to_rgb(image: Tensor) -> Tensor:
>>> output = bgr_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
# flip image channels
- out: Tensor = image.flip(-3)
+ out: torch.Tensor = image.flip(-3)
return out
-def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
+def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Convert an image from RGB to RGBA.
Args:
image: RGB Image to be converted to RGBA of shape :math:`(*,3,H,W)`.
- alpha_val (float, Tensor): A float number for the alpha value or a tensor
+ alpha_val (float, torch.Tensor): A float number for the alpha value or a torch.tensor
of shape :math:`(*,1,H,W)`.
Returns:
@@ -94,19 +94,19 @@ def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
>>> output = rgb_to_rgba(input, 1.) # 2x4x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
- if not isinstance(alpha_val, (float, Tensor)):
- raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}")
+ if not isinstance(alpha_val, (float, torch.Tensor)):
+ raise TypeError(f"alpha_val type is not a float or torch.Tensor. Got {type(alpha_val)}")
# add one channel
r, g, b = torch.chunk(image, image.shape[-3], dim=-3)
- a: Tensor = cast(Tensor, alpha_val)
+ a: torch.Tensor = cast(torch.Tensor, alpha_val)
if isinstance(alpha_val, float):
a = torch.full_like(r, fill_value=float(alpha_val))
@@ -114,12 +114,12 @@ def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
return torch.cat([r, g, b, a], dim=-3)
-def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
+def bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Convert an image from BGR to RGBA.
Args:
image: BGR Image to be converted to RGBA of shape :math:`(*,3,H,W)`.
- alpha_val: A float number for the alpha value or a tensor
+ alpha_val: A float number for the alpha value or a torch.tensor
of shape :math:`(*,1,H,W)`.
Returns:
@@ -132,21 +132,21 @@ def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
>>> output = bgr_to_rgba(input, 1.) # 2x4x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
- if not isinstance(alpha_val, (float, Tensor)):
- raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}")
+ if not isinstance(alpha_val, (float, torch.Tensor)):
+ raise TypeError(f"alpha_val type is not a float or torch.Tensor. Got {type(alpha_val)}")
# convert first to RGB, then add alpha channel
- x_rgb: Tensor = bgr_to_rgb(image)
+ x_rgb: torch.Tensor = bgr_to_rgb(image)
return rgb_to_rgba(x_rgb, alpha_val)
-def rgba_to_rgb(image: Tensor, background_color: Optional[Tensor] = None) -> Tensor:
+def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Convert an image from RGBA to RGB using alpha compositing.
The function composites the input RGBA image over a background color. If no
@@ -155,8 +155,8 @@ def rgba_to_rgb(image: Tensor, background_color: Optional[Tensor] = None) -> Ten
Args:
image: The RGBA image to be converted, with shape :math:`(*,4,H,W)`.
background_color: An optional background color. It can be a *tuple or list* of 3 floats,
- a tensor of shape :math:`(*,3,H,W)` for a per-pixel background, or a broadcastable
- tensor (e.g., :math:`(*,3,1,1)`). If None, a white background is used.
+ a torch.tensor of shape :math:`(*,3,H,W)` for a per-pixel background, or a broadcastable
+ torch.tensor (e.g., :math:`(*,3,1,1)`). If None, a white background is used.
Returns:
The converted RGB image with shape :math:`(*,3,H,W)`.
@@ -168,8 +168,8 @@ def rgba_to_rgb(image: Tensor, background_color: Optional[Tensor] = None) -> Ten
>>> # Test with a custom background color
>>> rgb_image_custom = rgba_to_rgb(rgba_image, background_color=(0.0, 0.0, 1.0)) # 2x3x32x32
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")
@@ -183,12 +183,13 @@ def rgba_to_rgb(image: Tensor, background_color: Optional[Tensor] = None) -> Ten
elif isinstance(background_color, (tuple, list)):
if len(background_color) != 3:
raise ValueError("background_color as a list/tuple must have 3 elements (R, G, B).")
- background_rgb = as_tensor(background_color, device=image.device, dtype=image.dtype).view(-1, 3, 1, 1)
+ background_rgb = torch.as_tensor(background_color, device=image.device, dtype=image.dtype).view(-1, 3, 1, 1)
- elif isinstance(background_color, Tensor):
+ elif isinstance(background_color, torch.Tensor):
if background_color.shape[-3] != 3:
raise ValueError(
- f"background_color tensor must have 3 channels in dimension -3. Got shape {background_color.shape}"
+ f"background_color torch.tensor must have 3 channels in dimension -3. "
+ f"Got shape {background_color.shape}"
)
background_rgb = background_color
@@ -200,7 +201,7 @@ def rgba_to_rgb(image: Tensor, background_color: Optional[Tensor] = None) -> Ten
return blended_rgb
-def rgba_to_bgr(image: Tensor) -> Tensor:
+def rgba_to_bgr(image: torch.Tensor) -> torch.Tensor:
r"""Convert an image from RGBA to BGR.
Args:
@@ -214,18 +215,18 @@ def rgba_to_bgr(image: Tensor) -> Tensor:
>>> output = rgba_to_bgr(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")
# convert to RGB first, then to BGR
- x_rgb: Tensor = rgba_to_rgb(image)
+ x_rgb: torch.Tensor = rgba_to_rgb(image)
return rgb_to_bgr(x_rgb)
-def rgb_to_linear_rgb(image: Tensor) -> Tensor:
+def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert an sRGB image to linear RGB. Used in colorspace conversions.
.. image:: _static/img/rgb_to_linear_rgb.png
@@ -241,18 +242,18 @@ def rgb_to_linear_rgb(image: Tensor) -> Tensor:
>>> output = rgb_to_linear_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
- lin_rgb: Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)
+ lin_rgb: torch.Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)
return lin_rgb
-def linear_rgb_to_rgb(image: Tensor) -> Tensor:
+def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert a linear RGB image to sRGB. Used in colorspace conversions.
Args:
@@ -266,21 +267,21 @@ def linear_rgb_to_rgb(image: Tensor) -> Tensor:
>>> output = linear_rgb_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
threshold = 0.0031308
- rgb: Tensor = torch.where(
+ rgb: torch.Tensor = torch.where(
image > threshold, 1.055 * torch.pow(image.clamp(min=threshold), 1 / 2.4) - 0.055, 12.92 * image
)
return rgb
-def normals_to_rgb255(image: Tensor) -> Tensor:
+def normals_to_rgb255(image: torch.Tensor) -> torch.Tensor:
r"""Convert surface normals to RGB [0, 255] for visualization purposes.
Args:
@@ -299,7 +300,7 @@ def normals_to_rgb255(image: Tensor) -> Tensor:
return rgb255
-def rgb_to_rgb255(image: Tensor) -> Tensor:
+def rgb_to_rgb255(image: torch.Tensor) -> torch.Tensor:
r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.
Args:
@@ -318,7 +319,7 @@ def rgb_to_rgb255(image: Tensor) -> Tensor:
return rgb255
-def rgb255_to_rgb(image: Tensor) -> Tensor:
+def rgb255_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.
Args:
@@ -337,7 +338,7 @@ def rgb255_to_rgb(image: Tensor) -> Tensor:
return rgb
-def rgb255_to_normals(image: Tensor) -> Tensor:
+def rgb255_to_normals(image: torch.Tensor) -> torch.Tensor:
r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.
Args:
@@ -352,11 +353,11 @@ def rgb255_to_normals(image: Tensor) -> Tensor:
"""
KORNIA_CHECK_IS_COLOR(image)
- normals = normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
+ normals = F.normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
return normals
-class BgrToRgb(Module):
+class BgrToRgb(nn.Module):
r"""Convert image from BGR to RGB.
The image data is assumed to be in the range of (0, 1).
@@ -378,11 +379,11 @@ class BgrToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return bgr_to_rgb(image)
-class RgbToBgr(Module):
+class RgbToBgr(nn.Module):
r"""Convert an image from RGB to BGR.
The image data is assumed to be in the range of (0, 1).
@@ -404,21 +405,21 @@ class RgbToBgr(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_bgr(image)
-class RgbToRgba(Module):
+class RgbToRgba(nn.Module):
r"""Convert an image from RGB to RGBA.
Add an alpha channel to existing RGB image.
Args:
- alpha_val: A float number for the alpha value or a tensor
+ alpha_val: A float number for the alpha value or a torch.tensor
of shape :math:`(*,1,H,W)`.
Returns:
- Tensor: RGBA version of the image with shape :math:`(*,4,H,W)`.
+ torch.Tensor: RGBA version of the image with shape :math:`(*,4,H,W)`.
Shape:
- image: :math:`(*, 3, H, W)`
@@ -436,21 +437,21 @@ class RgbToRgba(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
- def __init__(self, alpha_val: Union[float, Tensor]) -> None:
+ def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:
super().__init__()
self.alpha_val = alpha_val
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_rgba(image, self.alpha_val)
-class BgrToRgba(Module):
+class BgrToRgba(nn.Module):
r"""Convert an image from BGR to RGBA.
Add an alpha channel to existing RGB image.
Args:
- alpha_val: A float number for the alpha value or a tensor
+ alpha_val: A float number for the alpha value or a torch.tensor
of shape :math:`(*,1,H,W)`.
Returns:
@@ -472,15 +473,15 @@ class BgrToRgba(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
- def __init__(self, alpha_val: Union[float, Tensor]) -> None:
+ def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:
super().__init__()
self.alpha_val = alpha_val
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_rgba(image, self.alpha_val)
-class RgbaToRgb(Module):
+class RgbaToRgb(nn.Module):
r"""Convert an image from RGBA to RGB.
Remove an alpha channel from RGB image.
@@ -502,11 +503,11 @@ class RgbaToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgba_to_rgb(image)
-class RgbaToBgr(Module):
+class RgbaToBgr(nn.Module):
r"""Convert an image from RGBA to BGR.
Remove an alpha channel from BGR image.
@@ -528,11 +529,11 @@ class RgbaToBgr(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgba_to_bgr(image)
-class RgbToLinearRgb(Module):
+class RgbToLinearRgb(nn.Module):
r"""Convert an image from sRGB to linear RGB.
Reverses the gamma correction of sRGB to get linear RGB values for colorspace conversions.
@@ -562,11 +563,11 @@ class RgbToLinearRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_linear_rgb(image)
-class LinearRgbToRgb(Module):
+class LinearRgbToRgb(nn.Module):
r"""Convert a linear RGB image to sRGB.
Applies gamma correction to linear RGB values, at the end of colorspace conversions, to get sRGB.
@@ -595,11 +596,11 @@ class LinearRgbToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return linear_rgb_to_rgb(image)
-class NormalsToRgb255(Module):
+class NormalsToRgb255(nn.Module):
r"""Convert surface normals to RGB [0, 255] for visualization purposes.
Returns:
@@ -616,11 +617,11 @@ class NormalsToRgb255(Module):
"""
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return normals_to_rgb255(image)
-class RgbToRgb255(Module):
+class RgbToRgb255(nn.Module):
r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.
Returns:
@@ -637,11 +638,11 @@ class RgbToRgb255(Module):
"""
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_rgb255(image)
-class Rgb255ToRgb(Module):
+class Rgb255ToRgb(nn.Module):
r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.
Returns:
@@ -658,11 +659,11 @@ class Rgb255ToRgb(Module):
"""
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb255_to_rgb(image)
-class Rgb255ToNormals(Module):
+class Rgb255ToNormals(nn.Module):
r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.
Returns:
@@ -679,5 +680,5 @@ class Rgb255ToNormals(Module):
"""
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb255_to_normals(image)
diff --git a/kornia/color/sepia.py b/kornia/color/sepia.py
index 2919afe5a..36d27c5c4 100644
--- a/kornia/color/sepia.py
+++ b/kornia/color/sepia.py
@@ -16,21 +16,19 @@
#
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
-
-def sepia_from_rgb(input: Tensor, rescale: bool = True, eps: float = 1e-6) -> Tensor:
- r"""Apply to a tensor the sepia filter.
+def sepia_from_rgb(input: torch.Tensor, rescale: bool = True, eps: float = 1e-6) -> torch.Tensor:
+ r"""Apply to a torch.tensor the sepia filter.
Args:
- input: the input tensor with shape of :math:`(*, C, H, W)`.
- rescale: If True, the output tensor will be rescaled (max values be 1. or 255).
+ input: the input torch.tensor with shape of :math:`(*, C, H, W)`.
+ rescale: If True, the output torch.tensor will be rescaled (max values be 1. or 255).
eps: scalar to enforce numerical stability.
Returns:
- Tensor: The sepia tensor of same size and numbers of channels
+ torch.Tensor: The sepia torch.tensor of same size and numbers of channels
as the input with shape :math:`(*, C, H, W)`.
Example:
@@ -63,16 +61,16 @@ def sepia_from_rgb(input: Tensor, rescale: bool = True, eps: float = 1e-6) -> Te
return sepia_out
-class Sepia(Module):
- r"""Module that apply the sepia filter to tensors.
+class Sepia(nn.Module):
+ r"""nn.Module that apply the sepia filter to tensors.
Args:
- input: the input tensor with shape of :math:`(*, C, H, W)`.
- rescale: If True, the output tensor will be rescaled (max values be 1. or 255).
+ input: the input torch.tensor with shape of :math:`(*, C, H, W)`.
+ rescale: If True, the output torch.tensor will be rescaled (max values be 1. or 255).
eps: scalar to enforce numerical stability.
Returns:
- Tensor: The sepia tensor of same size and numbers of channels
+ torch.Tensor: The sepia torch.tensor of same size and numbers of channels
as the input with shape :math:`(*, C, H, W)`.
Example:
@@ -95,5 +93,5 @@ class Sepia(Module):
def __repr__(self) -> str:
return self.__class__.__name__ + f"(rescale={self.rescale}, eps={self.eps})"
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return sepia_from_rgb(input, rescale=self.rescale, eps=self.eps)
diff --git a/kornia/color/xyz.py b/kornia/color/xyz.py
index 33821cd31..d15e74a31 100644
--- a/kornia/color/xyz.py
+++ b/kornia/color/xyz.py
@@ -20,12 +20,10 @@ from __future__ import annotations
from typing import ClassVar
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
-
-def rgb_to_xyz(image: Tensor) -> Tensor:
+def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:
r"""Convert a RGB image to XYZ.
.. image:: _static/img/rgb_to_xyz.png
@@ -41,26 +39,26 @@ def rgb_to_xyz(image: Tensor) -> Tensor:
>>> output = rgb_to_xyz(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- r: Tensor = image[..., 0, :, :]
- g: Tensor = image[..., 1, :, :]
- b: Tensor = image[..., 2, :, :]
+ r: torch.Tensor = image[..., 0, :, :]
+ g: torch.Tensor = image[..., 1, :, :]
+ b: torch.Tensor = image[..., 2, :, :]
- x: Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b
- y: Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b
- z: Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b
+ x: torch.Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b
+ y: torch.Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b
+ z: torch.Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b
- out: Tensor = torch.stack([x, y, z], -3)
+ out: torch.Tensor = torch.stack([x, y, z], -3)
return out
-def xyz_to_rgb(image: Tensor) -> Tensor:
+def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert a XYZ image to RGB.
Args:
@@ -74,26 +72,26 @@ def xyz_to_rgb(image: Tensor) -> Tensor:
>>> output = xyz_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- x: Tensor = image[..., 0, :, :]
- y: Tensor = image[..., 1, :, :]
- z: Tensor = image[..., 2, :, :]
+ x: torch.Tensor = image[..., 0, :, :]
+ y: torch.Tensor = image[..., 1, :, :]
+ z: torch.Tensor = image[..., 2, :, :]
- r: Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z
- g: Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z
- b: Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z
+ r: torch.Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z
+ g: torch.Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z
+ b: torch.Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z
- out: Tensor = torch.stack([r, g, b], dim=-3)
+ out: torch.Tensor = torch.stack([r, g, b], dim=-3)
return out
-class RgbToXyz(Module):
+class RgbToXyz(nn.Module):
r"""Convert an image from RGB to XYZ.
The image data is assumed to be in the range of (0, 1).
@@ -118,11 +116,11 @@ class RgbToXyz(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_xyz(image)
-class XyzToRgb(Module):
+class XyzToRgb(nn.Module):
r"""Converts an image from XYZ to RGB.
Returns:
@@ -145,5 +143,5 @@ class XyzToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return xyz_to_rgb(image)
diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.py
index 7c25c713f..4f0d8571c 100644
--- a/kornia/color/ycbcr.py
+++ b/kornia/color/ycbcr.py
@@ -20,17 +20,15 @@ from __future__ import annotations
from typing import ClassVar
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
-
-def _rgb_to_y(r: Tensor, g: Tensor, b: Tensor) -> Tensor:
- y: Tensor = 0.299 * r + 0.587 * g + 0.114 * b
+def _rgb_to_y(r: torch.Tensor, g: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ y: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b
return y
-def rgb_to_ycbcr(image: Tensor) -> Tensor:
+def rgb_to_ycbcr(image: torch.Tensor) -> torch.Tensor:
r"""Convert an RGB image to YCbCr.
.. image:: _static/img/rgb_to_ycbcr.png
@@ -46,24 +44,24 @@ def rgb_to_ycbcr(image: Tensor) -> Tensor:
>>> output = rgb_to_ycbcr(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- r: Tensor = image[..., 0, :, :]
- g: Tensor = image[..., 1, :, :]
- b: Tensor = image[..., 2, :, :]
+ r: torch.Tensor = image[..., 0, :, :]
+ g: torch.Tensor = image[..., 1, :, :]
+ b: torch.Tensor = image[..., 2, :, :]
delta: float = 0.5
- y: Tensor = _rgb_to_y(r, g, b)
- cb: Tensor = (b - y) * 0.564 + delta
- cr: Tensor = (r - y) * 0.713 + delta
+ y: torch.Tensor = _rgb_to_y(r, g, b)
+ cb: torch.Tensor = (b - y) * 0.564 + delta
+ cr: torch.Tensor = (r - y) * 0.713 + delta
return torch.stack([y, cb, cr], -3)
-def rgb_to_y(image: Tensor) -> Tensor:
+def rgb_to_y(image: torch.Tensor) -> torch.Tensor:
r"""Convert an RGB image to Y.
Args:
@@ -77,21 +75,21 @@ def rgb_to_y(image: Tensor) -> Tensor:
>>> output = rgb_to_y(input) # 2x1x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- r: Tensor = image[..., 0:1, :, :]
- g: Tensor = image[..., 1:2, :, :]
- b: Tensor = image[..., 2:3, :, :]
+ r: torch.Tensor = image[..., 0:1, :, :]
+ g: torch.Tensor = image[..., 1:2, :, :]
+ b: torch.Tensor = image[..., 2:3, :, :]
- y: Tensor = _rgb_to_y(r, g, b)
+ y: torch.Tensor = _rgb_to_y(r, g, b)
return y
-def ycbcr_to_rgb(image: Tensor) -> Tensor:
+def ycbcr_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert an YCbCr image to RGB.
The image data is assumed to be in the range of (0, 1).
@@ -107,27 +105,27 @@ def ycbcr_to_rgb(image: Tensor) -> Tensor:
>>> output = ycbcr_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- y: Tensor = image[..., 0, :, :]
- cb: Tensor = image[..., 1, :, :]
- cr: Tensor = image[..., 2, :, :]
+ y: torch.Tensor = image[..., 0, :, :]
+ cb: torch.Tensor = image[..., 1, :, :]
+ cr: torch.Tensor = image[..., 2, :, :]
delta: float = 0.5
- cb_shifted: Tensor = cb - delta
- cr_shifted: Tensor = cr - delta
+ cb_shifted: torch.Tensor = cb - delta
+ cr_shifted: torch.Tensor = cr - delta
- r: Tensor = y + 1.403 * cr_shifted
- g: Tensor = y - 0.714 * cr_shifted - 0.344 * cb_shifted
- b: Tensor = y + 1.773 * cb_shifted
+ r: torch.Tensor = y + 1.403 * cr_shifted
+ g: torch.Tensor = y - 0.714 * cr_shifted - 0.344 * cb_shifted
+ b: torch.Tensor = y + 1.773 * cb_shifted
return torch.stack([r, g, b], -3).clamp(0, 1)
-class RgbToYcbcr(Module):
+class RgbToYcbcr(nn.Module):
r"""Convert an image from RGB to YCbCr.
The image data is assumed to be in the range of (0, 1).
@@ -149,11 +147,11 @@ class RgbToYcbcr(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return rgb_to_ycbcr(image)
-class YcbcrToRgb(Module):
+class YcbcrToRgb(nn.Module):
r"""Convert an image from YCbCr to Rgb.
The image data is assumed to be in the range of (0, 1).
@@ -175,5 +173,5 @@ class YcbcrToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return ycbcr_to_rgb(image)
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index ca7d4ed91..377a54a06 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -20,12 +20,10 @@ from __future__ import annotations
from typing import ClassVar
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
-
-def rgb_to_yuv(image: Tensor) -> Tensor:
+def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:
r"""Convert an RGB image to YUV.
.. image:: _static/img/rgb_to_yuv.png
@@ -49,26 +47,26 @@ def rgb_to_yuv(image: Tensor) -> Tensor:
>>> output = rgb_to_yuv(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- r: Tensor = image[..., 0, :, :]
- g: Tensor = image[..., 1, :, :]
- b: Tensor = image[..., 2, :, :]
+ r: torch.Tensor = image[..., 0, :, :]
+ g: torch.Tensor = image[..., 1, :, :]
+ b: torch.Tensor = image[..., 2, :, :]
- y: Tensor = 0.299 * r + 0.587 * g + 0.114 * b
- u: Tensor = -0.147 * r - 0.289 * g + 0.436 * b
- v: Tensor = 0.615 * r - 0.515 * g - 0.100 * b
+ y: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b
+ u: torch.Tensor = -0.147 * r - 0.289 * g + 0.436 * b
+ v: torch.Tensor = 0.615 * r - 0.515 * g - 0.100 * b
- out: Tensor = torch.stack([y, u, v], -3)
+ out: torch.Tensor = torch.stack([y, u, v], -3)
return out
-def rgb_to_yuv420(image: Tensor) -> tuple[Tensor, Tensor]:
+def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert an RGB image to YUV 420 (subsampled).
Input need to be padded to be evenly divisible by 2 horizontal and vertical.
@@ -84,16 +82,16 @@ def rgb_to_yuv420(image: Tensor) -> tuple[Tensor, Tensor]:
image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`.
Returns:
- A Tensor containing the Y plane with shape :math:`(*, 1, H, W)`
- A Tensor containing the UV planes with shape :math:`(*, 2, H/2, W/2)`
+ A torch.Tensor containing the Y plane with shape :math:`(*, 1, H, W)`
+ A torch.Tensor containing the UV planes with shape :math:`(*, 2, H/2, W/2)`
Example:
>>> input = torch.rand(2, 3, 4, 6)
>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3)
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
@@ -109,7 +107,7 @@ def rgb_to_yuv420(image: Tensor) -> tuple[Tensor, Tensor]:
)
-def rgb_to_yuv422(image: Tensor) -> tuple[Tensor, Tensor]:
+def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert an RGB image to YUV 422 (subsampled).
Input need to be padded to be evenly divisible by 2 vertical.
@@ -126,16 +124,16 @@ def rgb_to_yuv422(image: Tensor) -> tuple[Tensor, Tensor]:
image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`.
Returns:
- A Tensor containing the Y plane with shape :math:`(*, 1, H, W)`
- A Tensor containing the UV planes with shape :math:`(*, 2, H, W/2)`
+ A torch.Tensor containing the Y plane with shape :math:`(*, 1, H, W)`
+ A torch.Tensor containing the UV planes with shape :math:`(*, 2, H, W/2)`
Example:
>>> input = torch.rand(2, 3, 4, 6)
>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3)
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
@@ -148,7 +146,7 @@ def rgb_to_yuv422(image: Tensor) -> tuple[Tensor, Tensor]:
return (yuvimage[..., :1, :, :], yuvimage[..., 1:3, :, :].unfold(-1, 2, 2).mean(-1))
-def yuv_to_rgb(image: Tensor) -> Tensor:
+def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:
r"""Convert an YUV image to RGB.
The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are
@@ -169,26 +167,26 @@ def yuv_to_rgb(image: Tensor) -> Tensor:
>>> output = yuv_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if image.dim() < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- y: Tensor = image[..., 0, :, :]
- u: Tensor = image[..., 1, :, :]
- v: Tensor = image[..., 2, :, :]
+ y: torch.Tensor = image[..., 0, :, :]
+ u: torch.Tensor = image[..., 1, :, :]
+ v: torch.Tensor = image[..., 2, :, :]
- r: Tensor = y + 1.14 * v # coefficient for g is 0
- g: Tensor = y + -0.396 * u - 0.581 * v
- b: Tensor = y + 2.029 * u # coefficient for b is 0
+ r: torch.Tensor = y + 1.14 * v # coefficient for g is 0
+ g: torch.Tensor = y + -0.396 * u - 0.581 * v
+ b: torch.Tensor = y + 2.029 * u # coefficient for b is 0
- out: Tensor = torch.stack([r, g, b], -3)
+ out: torch.Tensor = torch.stack([r, g, b], -3)
return out
-def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
+def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
r"""Convert an YUV420 image to RGB.
Input need to be padded to be evenly divisible by 2 horizontal and vertical.
@@ -213,11 +211,11 @@ def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6
"""
- if not isinstance(imagey, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")
+ if not isinstance(imagey, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")
- if not isinstance(imageuv, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}")
+ if not isinstance(imageuv, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")
if len(imagey.shape) < 3 or imagey.shape[-3] != 1:
raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")
@@ -243,12 +241,12 @@ def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
[imagey, imageuv.repeat_interleave(2, dim=-1).repeat_interleave(2, dim=-2)],
dim=-3,
)
- # then convert the yuv444 tensor
+ # then convert the yuv444 torch.tensor
return yuv_to_rgb(yuv444image)
-def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
+def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
r"""Convert an YUV422 image to RGB.
Input need to be padded to be evenly divisible by 2 vertical.
@@ -273,11 +271,11 @@ def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5
"""
- if not isinstance(imagey, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")
+ if not isinstance(imagey, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")
- if not isinstance(imageuv, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}")
+ if not isinstance(imageuv, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")
if len(imagey.shape) < 3 or imagey.shape[-3] != 1:
raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")
@@ -295,11 +293,11 @@ def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
# first upsample
yuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1)], dim=-3)
- # then convert the yuv444 tensor
+ # then convert the yuv444 torch.tensor
return yuv_to_rgb(yuv444image)
-class RgbToYuv(Module):
+class RgbToYuv(nn.Module):
r"""Convert an image from RGB to YUV.
The image data is assumed to be in the range of :math:`(0, 1)`.
@@ -328,11 +326,11 @@ class RgbToYuv(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return rgb_to_yuv(input)
-class RgbToYuv420(Module):
+class RgbToYuv420(nn.Module):
r"""Convert an image from RGB to YUV420.
Width and Height evenly divisible by 2.
@@ -363,11 +361,11 @@ class RgbToYuv420(Module):
# TODO: Handle multiple inputs and outputs models later
ONNX_EXPORTABLE = False
- def forward(self, yuvinput: Tensor) -> tuple[Tensor, Tensor]: # skipcq: PYL-R0201
+ def forward(self, yuvinput: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: # skipcq: PYL-R0201
return rgb_to_yuv420(yuvinput)
-class RgbToYuv422(Module):
+class RgbToYuv422(nn.Module):
r"""Convert an image from RGB to YUV422.
Width must be evenly disvisible by 2.
@@ -398,11 +396,11 @@ class RgbToYuv422(Module):
# TODO: Handle multiple inputs and outputs models later
ONNX_EXPORTABLE = False
- def forward(self, yuvinput: Tensor) -> tuple[Tensor, Tensor]: # skipcq: PYL-R0201
+ def forward(self, yuvinput: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: # skipcq: PYL-R0201
return rgb_to_yuv422(yuvinput)
-class YuvToRgb(Module):
+class YuvToRgb(nn.Module):
r"""Convert an image from YUV to RGB.
The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are
@@ -429,11 +427,11 @@ class YuvToRgb(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return yuv_to_rgb(input)
-class Yuv420ToRgb(Module):
+class Yuv420ToRgb(nn.Module):
r"""Convert an image from YUV to RGB.
Width and Height must be evenly divisible by 2.
@@ -464,11 +462,11 @@ class Yuv420ToRgb(Module):
# TODO: Handle multiple inputs and outputs models later
ONNX_EXPORTABLE = False
- def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201
+ def forward(self, inputy: torch.Tensor, inputuv: torch.Tensor) -> torch.Tensor: # skipcq: PYL-R0201
return yuv420_to_rgb(inputy, inputuv)
-class Yuv422ToRgb(Module):
+class Yuv422ToRgb(nn.Module):
r"""Convert an image from YUV to RGB.
Width must be evenly divisible by 2.
@@ -499,5 +497,5 @@ class Yuv422ToRgb(Module):
# TODO: Handle multiple inputs and outputs models later
ONNX_EXPORTABLE = False
- def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201
+ def forward(self, inputy: torch.Tensor, inputuv: torch.Tensor) -> torch.Tensor: # skipcq: PYL-R0201
return yuv422_to_rgb(inputy, inputuv)
diff --git a/kornia/constants.py b/kornia/constants.py
index 8877e66ed..4f733d036 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -20,8 +20,6 @@ from typing import Iterator, Type, TypeVar, Union
import torch
-from kornia.core import Tensor
-
__all__ = ["BorderType", "DType", "Resample", "SamplePadding", "TKEnum", "pi"]
pi = torch.tensor(3.14159265358979323846)
@@ -102,11 +100,11 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
FLOAT64 = 3
@classmethod
- def get(cls, value: Union[str, int, torch.dtype, Tensor, "DType"]) -> "DType":
+ def get(cls, value: Union[str, int, torch.dtype, torch.Tensor, "DType"]) -> "DType":
if isinstance(value, torch.dtype):
return cls[str(value).upper()[6:]]
- elif isinstance(value, Tensor):
+ elif isinstance(value, torch.Tensor):
return cls(int(value.item()))
elif isinstance(value, str):
diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.py
index 401ba28e7..f0353ca6c 100644
--- a/kornia/contrib/boxmot_tracker.py
+++ b/kornia/contrib/boxmot_tracker.py
@@ -23,9 +23,10 @@ import os
from pathlib import Path
from typing import Any, Optional, Union
+import torch
+
from kornia.config import kornia_config
from kornia.contrib.object_detection import ObjectDetector, RTDETRDetectorBuilder
-from kornia.core import Tensor, tensor
from kornia.core.external import boxmot
from kornia.core.external import numpy as np
from kornia.io import write_image
@@ -42,7 +43,7 @@ class BoxMotTracker:
This module uses BoxMot library for tracking.
Args:
- detector: ObjectDetector: The detector model.
+ detector: The detector model.
tracker_model_name: The name of the tracker model. Valid options are:
- "BoTSORT"
- "DeepOCSORT"
@@ -52,9 +53,9 @@ class BoxMotTracker:
- "StrongSORT"
- "ImprAssoc"
tracker_model_weights: Path to the model weights for ReID (Re-Identification).
- device: Device on which to run the model (e.g., 'cpu' or 'cuda').
+ device: Union[str, torch.device, None] on which to run the model (e.g., 'cpu' or 'cuda').
fp16: Whether to use half-precision (fp16) for faster inference on compatible devices.
- per_class: Whether to perform per-class tracking
+ per_class: Whether to perform per-class tracking.
track_high_thresh: High threshold for detection confidence.
Detections above this threshold are used in the first association round.
track_low_thresh: Low threshold for detection confidence.
@@ -73,6 +74,7 @@ class BoxMotTracker:
.. code-block:: python
import kornia
+ import torch
image = kornia.utils.sample.get_sample_images()[0][None]
model = BoxMotTracker()
for i in range(4): # At least 4 frames are needed to initialize the tracking position
@@ -112,7 +114,7 @@ class BoxMotTracker:
**kwargs,
)
- def update(self, image: Tensor) -> None:
+ def update(self, image: torch.Tensor) -> None:
"""Update the tracker with a new image.
Args:
@@ -120,12 +122,12 @@ class BoxMotTracker:
"""
if not (image.ndim == 4 and image.shape[0] == 1) and not image.ndim == 3:
- raise ValueError(f"Input tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")
+ raise ValueError(f"Input torch.tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")
if image.ndim == 3:
image = image.unsqueeze(0)
- detections_raw: Union[Tensor, list[Tensor]] = self.detector(image)
+ detections_raw: Union[torch.Tensor, list[torch.Tensor]] = self.detector(image)
detections = detections_raw[0].cpu().numpy() # Batch size is 1
@@ -148,7 +150,7 @@ class BoxMotTracker:
# --> M X (x, y, x, y, id, conf, cls, ind)
return self.tracker.update(detections, frame_raw)
- def visualize(self, image: Tensor, show_trajectories: bool = True) -> Tensor:
+ def visualize(self, image: torch.Tensor, show_trajectories: bool = True) -> torch.Tensor:
"""Visualize the results of the tracker.
Args:
@@ -162,9 +164,9 @@ class BoxMotTracker:
frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)
self.tracker.plot_results(frame_raw, show_trajectories=show_trajectories)
- return tensor(frame_raw).permute(2, 0, 1)
+ return torch.tensor(frame_raw).permute(2, 0, 1)
- def save(self, image: Tensor, show_trajectories: bool = True, directory: Optional[str] = None) -> None:
+ def save(self, image: torch.Tensor, show_trajectories: bool = True, directory: Optional[str] = None) -> None:
"""Save the model to ONNX format.
Args:
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index 011785687..1de842e1d 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -18,10 +18,8 @@
import torch
import torch.nn.functional as F
-from kornia.core import Tensor
-
-def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor:
+def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torch.Tensor:
r"""Compute the Connected-component labelling (CCL) algorithm.
.. image:: https://github.com/kornia/data/raw/main/cells_segmented.png
@@ -49,8 +47,8 @@ def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor:
>>> img_labels = connected_components(img, num_iterations=100)
"""
- if not isinstance(image, Tensor):
- raise TypeError(f"Input imagetype is not a Tensor. Got: {type(image)}")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input imagetype is not a torch.Tensor. Got: {type(image)}")
if not isinstance(num_iterations, int) or num_iterations < 1:
raise TypeError("Input num_iterations must be a positive integer.")
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index aaae8e510..1727c3ee6 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -21,7 +21,6 @@ from typing import Callable, List, Optional, Tuple, Union
import torch
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.enhance import normalize_min_max
from kornia.filters import filter2d
@@ -35,10 +34,10 @@ def _diamond_square_seed(
replicates: int,
width: int,
height: int,
- random_fn: Callable[..., Tensor],
+ random_fn: Callable[..., torch.Tensor],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
"""Generate the diamond square image seee.
Args:
@@ -46,8 +45,8 @@ def _diamond_square_seed(
width: the expected image width.
height: the expected image height.
random_fn: the random function to generate the image seed.
- device: the torch device where to create the image seed.
- dtype: the torch dtype where to create the image seed.
+ device: the torch device torch.where to create the image seed.
+ dtype: the torch dtype torch.where to create the image seed.
Return:
the generated image seed of size Bx1xHxW.
@@ -63,7 +62,7 @@ def _diamond_square_seed(
# width is always 3
KORNIA_CHECK(height % 2 == 1 and height > 2, "Height must be odd and height bigger than 2")
- res: Tensor = random_fn([replicates, 1, width, height], device=device, dtype=dtype)
+ res: torch.Tensor = random_fn([replicates, 1, width, height], device=device, dtype=dtype)
res[..., ::2, ::2] = random_fn([replicates, 1, 2, (height + 1) // 2], device=device, dtype=dtype)
# Diamond step
@@ -89,12 +88,12 @@ def _diamond_square_seed(
def _one_diamond_one_square(
- img: Tensor,
- random_scale: Union[float, Tensor],
- random_fn: Callable[..., Tensor] = torch.rand,
- diamond_kernel: Optional[Tensor] = None,
- square_kernel: Optional[Tensor] = None,
-) -> Tensor:
+ img: torch.Tensor,
+ random_scale: Union[float, torch.Tensor],
+ random_fn: Callable[..., torch.Tensor] = torch.rand,
+ diamond_kernel: Optional[torch.Tensor] = None,
+ square_kernel: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
"""Doubles the image resolution by applying a single diamond square steps.
Recursive application of this method creates plasma fractals.
@@ -104,7 +103,8 @@ def _one_diamond_one_square(
If this function is run in the usual sense, it is more efficient if it is run in a no_grad()
Args:
- img: a 4D tensor where dimensions are Batch, Channel, Width, Height. Width and Height must both be 2^N+1 and
+ img: a 4D torch.tensor torch.where dimensions are Batch, Channel, Width, Height.
+ Width and Height must both be 2^N+1 and
Batch and Channels should in the usual case be 1.
random_scale: a float number in [0,1] controlling the randomness created pixels get. I the usual case, it is
halved at every application of this function.
@@ -113,19 +113,19 @@ def _one_diamond_one_square(
square_kernel: the 3x3 kernel to perform the square step.
Return:
- A tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1.
+ A torch.tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1.
"""
KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])
# TODO (anguelos) test multi channel and batch size > 1
if diamond_kernel is None:
- diamond_kernel = Tensor([default_diamond_kernel]).to(img) # 1x3x3
+ diamond_kernel = torch.Tensor([default_diamond_kernel]).to(img) # 1x3x3
if square_kernel is None:
- square_kernel = Tensor([default_square_kernel]).to(img) # 1x3x3
+ square_kernel = torch.Tensor([default_square_kernel]).to(img) # 1x3x3
batch_sz, _, height, width = img.shape
- new_img: Tensor = torch.zeros(
+ new_img: torch.Tensor = torch.zeros(
[batch_sz, 1, 2 * (height - 1) + 1, 2 * (width - 1) + 1], device=img.device, dtype=img.dtype
)
new_img[:, :, ::2, ::2] = img
@@ -137,7 +137,7 @@ def _one_diamond_one_square(
pad_compencate[:, :, 0, :] = factor
pad_compencate[:, :, -1, :] = factor
- random_img: Tensor = random_fn(new_img.size(), device=img.device, dtype=img.dtype) * random_scale
+ random_img: torch.Tensor = random_fn(new_img.size(), device=img.device, dtype=img.dtype) * random_scale
# TODO(edgar): use kornia.filter2d
# diamond
@@ -158,13 +158,13 @@ def _one_diamond_one_square(
def diamond_square(
output_size: Tuple[int, int, int, int],
- roughness: Union[float, Tensor] = 0.5,
- random_scale: Union[float, Tensor] = 1.0,
- random_fn: Callable[..., Tensor] = torch.rand,
+ roughness: Union[float, torch.Tensor] = 0.5,
+ random_scale: Union[float, torch.Tensor] = 1.0,
+ random_fn: Callable[..., torch.Tensor] = torch.rand,
normalize_range: Optional[Tuple[float, float]] = None,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
"""Generate Plasma Fractal Images using the diamond square algorithm.
See: https://en.wikipedia.org/wiki/Diamond-square_algorithm
@@ -173,19 +173,19 @@ def diamond_square(
output_size: a tuple of integers with the BxCxHxW of the image to be generated.
roughness: the scale value to apply at each recursion step.
random_scale: the initial value of the scale for recursion.
- random_fn: the callable function to use to sample a random tensor.
- normalize_range: whether to normalize using min-max the output map. In case of a
+ random_fn: the callable function to use to sample a random torch.tensor.
+ normalize_range: whether to F.normalize using min-max the output map. In case of a
range is specified, min-max norm is applied between the provided range.
device: the torch device to place the output map.
dtype: the torch dtype to place the output map.
Returns:
- A tensor with shape :math:`(B,C,H,W)` containing the fractal image.
+ A torch.tensor with shape :math:`(B,C,H,W)` containing the fractal image.
"""
KORNIA_CHECK(len(output_size) == 4, "output_size must be (B,C,H,W)")
- if not isinstance(random_scale, Tensor):
- random_scale = Tensor([[[[random_scale]]]]).to(device, dtype)
+ if not isinstance(random_scale, torch.Tensor):
+ random_scale = torch.Tensor([[[[random_scale]]]]).to(device, dtype)
random_scale = random_scale.expand([output_size[0] * output_size[1], 1, 1, 1])
else:
KORNIA_CHECK_IS_TENSOR(random_scale)
@@ -193,8 +193,8 @@ def diamond_square(
random_scale = random_scale.expand([output_size[0], output_size[1], 1, 1])
random_scale = random_scale.reshape([-1, 1, 1, 1])
- if not isinstance(roughness, Tensor):
- roughness = Tensor([[[[roughness]]]]).to(device, dtype)
+ if not isinstance(roughness, torch.Tensor):
+ roughness = torch.Tensor([[[[roughness]]]]).to(device, dtype)
roughness = roughness.expand([output_size[0] * output_size[1], 1, 1, 1])
else:
roughness = roughness.view(-1, 1, 1, 1)
@@ -212,7 +212,9 @@ def diamond_square(
recursion_depth: int = int(min(math.log2(p2_width - 1) - 1, math.log2(p2_height - 1) - 1))
seed_width: int = (p2_width - 1) // 2**recursion_depth + 1
seed_height: int = (p2_height - 1) // 2**recursion_depth + 1
- img: Tensor = random_scale * _diamond_square_seed(num_samples, seed_width, seed_height, random_fn, device, dtype)
+ img: torch.Tensor = random_scale * _diamond_square_seed(
+ num_samples, seed_width, seed_height, random_fn, device, dtype
+ )
# perform recursion
scale = random_scale
@@ -224,7 +226,7 @@ def diamond_square(
img = img[..., :width, :height]
img = img.view(output_size)
- # normalize the output in the range using min-max
+ # F.normalize the output in the range using min-max
if normalize_range is not None:
min_val, max_val = normalize_range
img = normalize_min_max(img.contiguous(), min_val, max_val)
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index d4e065da8..5ecbf0b51 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -20,9 +20,9 @@ from __future__ import annotations
from typing import Any, Optional, Union
import torch
+from torch import nn
from kornia.color.gray import grayscale_to_rgb
-from kornia.core import Tensor, tensor
from kornia.core.external import PILImage as Image
from kornia.core.external import onnx
from kornia.core.mixin.onnx import ONNXExportMixin
@@ -100,15 +100,15 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
)
@torch.inference_mode()
- def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:
+ def forward(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:
"""Forward pass of the edge detection model.
Args:
- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.
+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.
+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
Returns:
- output tensor.
+ output torch.tensor.
"""
images, image_sizes = self.pre_processor(images)
@@ -117,19 +117,19 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
def visualize(
self,
- images: Union[Tensor, list[Tensor]],
- edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,
+ images: Union[torch.Tensor, list[torch.Tensor]],
+ edge_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
output_type: str = "torch",
- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
"""Draw the edge detection results.
Args:
- images: input tensor.
+ images: input torch.tensor.
edge_maps: detected edges.
output_type: type of the output.
Returns:
- output tensor.
+ output torch.tensor.
"""
if edge_maps is None:
@@ -138,25 +138,25 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
for edge_map in edge_maps:
output.append(grayscale_to_rgb(edge_map)[0])
- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))
+ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, torch.Tensor))
def save(
self,
- images: Union[Tensor, list[Tensor]],
- edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,
+ images: Union[torch.Tensor, list[torch.Tensor]],
+ edge_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
directory: Optional[str] = None,
output_type: str = "torch",
) -> None:
"""Save the edge detection results.
Args:
- images: input tensor.
+ images: input torch.tensor.
edge_maps: detected edges.
output_type: type of the output.
- directory: where to save outputs.
+ directory: torch.where to save outputs.
Returns:
- output tensor.
+ output torch.tensor.
"""
outputs = self.visualize(images, edge_maps, output_type)
@@ -239,9 +239,7 @@ class EdgeDetectorBuilder:
"""
if model_name.lower() == "dexined":
# Normalize then scale to [0, 255]
- norm = Normalize(mean=tensor([[0.485, 0.456, 0.406]]), std=tensor([[1.0 / 255.0] * 3]))
- from torch import nn
-
+ norm = Normalize(mean=torch.tensor([[0.485, 0.456, 0.406]]), std=torch.tensor([[1.0 / 255.0] * 3]))
model = nn.Sequential(norm, DexiNed(pretrained=pretrained), nn.Sigmoid())
else:
raise ValueError(f"Model {model_name} not found. Please choose from 'dexined'.")
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 365b87c90..0a626edfb 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -21,10 +21,9 @@ from warnings import warn
import torch
import torch.nn.functional as F
+from torch import nn
from torch.nn.modules.utils import _pair
-from kornia.core import Module, Tensor, pad
-
FullPadType = Tuple[int, int, int, int]
TuplePadType = Union[Tuple[int, int], FullPadType]
PadType = Union[int, TuplePadType]
@@ -59,7 +58,7 @@ def compute_padding(
:func:`combine_tensor_patches` produces expected result.
Args:
- original_size: the size of the original tensor.
+ original_size: the size of the original torch.tensor.
window_size: the size of the sliding window used while extracting patches.
stride: The stride of the sliding window. Optional: if not specified, window_size will be used.
@@ -118,13 +117,13 @@ def compute_padding(
return padding
-class ExtractTensorPatches(Module):
- r"""Module that extract patches from tensors and stack them.
+class ExtractTensorPatches(nn.Module):
+ r"""nn.Module that extract patches from tensors and torch.stack them.
In the simplest case, the output value of the operator with input size
:math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`.
- where
+ torch.where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
@@ -134,10 +133,10 @@ class ExtractTensorPatches(Module):
left-right and top-bottom order.
* :attr:`window_size` is the size of the sliding window and controls the
- shape of the output tensor and defines the shape of the output patch.
+ shape of the output torch.tensor and defines the shape of the output patch.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
- * :attr:`padding` controls the amount of implicit zeros-paddings on both
+ * :attr:`padding` controls the amount of implicit torch.zeros-paddings on both
sizes at each dimension.
* :attr:`allow_auto_padding` allows automatic calculation of the padding required
to fit the window and stride into the image.
@@ -155,7 +154,7 @@ class ExtractTensorPatches(Module):
the width dimension.
Args:
- input: tensor image where to extract the patches with shape :math:`(B, C, H, W)`.
+ input: torch.tensor image torch.where to extract the patches with shape :math:`(B, C, H, W)`.
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
@@ -166,7 +165,7 @@ class ExtractTensorPatches(Module):
- Output: :math:`(B, N, C, H_{out}, W_{out})`
Returns:
- the tensor with the extracted patches.
+ the torch.tensor with the extracted patches.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
@@ -194,7 +193,7 @@ class ExtractTensorPatches(Module):
self.padding: PadType = padding
self.allow_auto_padding: bool = allow_auto_padding
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return extract_tensor_patches(
input,
self.window_size,
@@ -204,13 +203,13 @@ class ExtractTensorPatches(Module):
)
-class CombineTensorPatches(Module):
- r"""Module that combines patches back into full tensors.
+class CombineTensorPatches(nn.Module):
+ r"""nn.Module that combines patches back into full tensors.
In the simplest case, the output value of the operator with input size
:math:`(B, N, C, H_{out}, W_{out})` is :math:`(B, C, H, W)`.
- where
+ torch.where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
@@ -221,13 +220,13 @@ class CombineTensorPatches(Module):
* :attr:`original_size` is the size of the original image prior to
- extracting tensor patches and defines the shape of the output patch.
+ extracting torch.tensor patches and defines the shape of the output patch.
* :attr:`window_size` is the size of the sliding window used while
- extracting tensor patches.
+ extracting torch.tensor patches.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
* :attr:`unpadding` is the amount of padding to be removed. If specified,
- this value must be the same as padding used while extracting tensor patches.
+ this value must be the same as padding used while extracting torch.tensor patches.
* :attr:`allow_auto_unpadding` allows automatic calculation of the padding required
to fit the window and stride into the image. This must be used if the
`allow_auto_padding` flag was used for extracting the patches.
@@ -246,8 +245,8 @@ class CombineTensorPatches(Module):
the width dimension.
Args:
- patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
- original_size: the size of the original tensor and the output size.
+ patches: patched torch.tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ original_size: the size of the original torch.tensor and the output size.
window_size: the size of the sliding window used while extracting patches.
stride: stride of the sliding window.
unpadding: remove the padding added to both side of the input.
@@ -287,7 +286,7 @@ class CombineTensorPatches(Module):
self.unpadding: PadType = unpadding
self.allow_auto_unpadding: bool = allow_auto_unpadding
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return combine_tensor_patches(
input,
self.original_size,
@@ -312,21 +311,21 @@ def _check_patch_fit(original_size: Tuple[int, int], window_size: Tuple[int, int
def combine_tensor_patches(
- patches: Tensor,
+ patches: torch.Tensor,
original_size: Union[int, Tuple[int, int]],
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]],
allow_auto_unpadding: bool = False,
unpadding: PadType = 0,
eps: float = 1e-8,
-) -> Tensor:
+) -> torch.Tensor:
r"""Restore input from patches.
See :class:`~kornia.contrib.CombineTensorPatches` for details.
Args:
- patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
- original_size: the size of the original tensor and the output size.
+ patches: patched torch.tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ original_size: the size of the original torch.tensor and the output size.
window_size: the size of the sliding window used while extracting patches.
stride: stride of the sliding window.
unpadding: remove the padding added to both side of the input.
@@ -335,7 +334,7 @@ def combine_tensor_patches(
eps: small value used to prevent division by zero.
Return:
- The combined patches in an image tensor with shape :math:`(B, C, H, W)`.
+ The combined patches in an image torch.tensor with shape :math:`(B, C, H, W)`.
Example:
>>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))
@@ -382,7 +381,7 @@ def combine_tensor_patches(
if unpadding:
unpadding = create_padding_tuple(unpadding)
- ones = torch.ones(
+ ones_tensor = torch.ones(
patches.shape[0],
patches.shape[2],
original_size[0],
@@ -392,8 +391,8 @@ def combine_tensor_patches(
)
if unpadding:
- ones = pad(ones, pad=unpadding)
- restored_size = ones.shape[2:]
+ ones_tensor = F.pad(ones_tensor, pad=unpadding)
+ restored_size = ones_tensor.shape[2:]
patches = patches.permute(0, 2, 3, 4, 1)
patches = patches.reshape(patches.shape[0], -1, patches.shape[-1])
@@ -402,18 +401,18 @@ def combine_tensor_patches(
int_flag = 1
dtype = patches.dtype
patches = patches.float()
- ones = ones.float()
+ ones_tensor = ones_tensor.float()
# Calculate normalization map
- unfold_ones = F.unfold(ones, kernel_size=window_size, stride=stride)
+ unfold_ones = F.unfold(ones_tensor, kernel_size=window_size, stride=stride)
norm_map = F.fold(input=unfold_ones, output_size=restored_size, kernel_size=window_size, stride=stride)
if unpadding:
- norm_map = pad(norm_map, [-i for i in unpadding])
+ norm_map = F.pad(norm_map, [-i for i in unpadding])
- # Restored tensor
+ # Restored torch.tensor
saturated_restored_tensor = F.fold(input=patches, output_size=restored_size, kernel_size=window_size, stride=stride)
if unpadding:
- saturated_restored_tensor = pad(saturated_restored_tensor, [-i for i in unpadding])
+ saturated_restored_tensor = F.pad(saturated_restored_tensor, [-i for i in unpadding])
# Remove satuation effect due to multiple summations
restored_tensor = saturated_restored_tensor / (norm_map + eps)
@@ -422,7 +421,9 @@ def combine_tensor_patches(
return restored_tensor
-def _extract_tensor_patchesnd(input: Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]) -> Tensor:
+def _extract_tensor_patchesnd(
+ input: torch.Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]
+) -> torch.Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
@@ -432,25 +433,25 @@ def _extract_tensor_patchesnd(input: Tensor, window_sizes: Tuple[int, ...], stri
def extract_tensor_patches(
- input: Tensor,
+ input: torch.Tensor,
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]] = 1,
padding: PadType = 0,
allow_auto_padding: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Extract patches from tensors and stacks them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
Args:
- input: tensor image where to extract the patches with shape :math:`(B, C, H, W)`.
+ input: torch.tensor image torch.where to extract the patches with shape :math:`(B, C, H, W)`.
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
allow_auto_padding: whether to allow automatic padding if the window and stride do not fit into the image.
Returns:
- the tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ the torch.tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
@@ -465,7 +466,7 @@ def extract_tensor_patches(
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) != 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
@@ -493,6 +494,6 @@ def extract_tensor_patches(
if padding:
padding = create_padding_tuple(padding)
- input = pad(input, padding)
+ input = F.pad(input, padding)
return _extract_tensor_patchesnd(input, window_size, stride)
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index 539f82ebc..6e021ba7f 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -18,16 +18,16 @@
from typing import Dict, Optional, Tuple
import torch
+from torch import nn
from kornia.color import rgb_to_grayscale
-from kornia.core import Module, Tensor, concatenate, where, zeros_like
from kornia.feature import LocalFeatureMatcher, LoFTR
from kornia.geometry.homography import find_homography_dlt_iterated
from kornia.geometry.ransac import RANSAC
from kornia.geometry.transform import warp_perspective
-class ImageStitcher(Module):
+class ImageStitcher(nn.Module):
"""Stitch two images with overlapping fields of view.
Args:
@@ -51,7 +51,7 @@ class ImageStitcher(Module):
"""
- def __init__(self, matcher: Module, estimator: str = "ransac", blending_method: str = "naive") -> None:
+ def __init__(self, matcher: nn.Module, estimator: str = "ransac", blending_method: str = "naive") -> None:
super().__init__()
self.matcher = matcher
self.estimator = estimator
@@ -61,7 +61,7 @@ class ImageStitcher(Module):
if estimator == "ransac":
self.ransac = RANSAC("homography")
- def _estimate_homography(self, keypoints1: Tensor, keypoints2: Tensor) -> Tensor:
+ def _estimate_homography(self, keypoints1: torch.Tensor, keypoints2: torch.Tensor) -> torch.Tensor:
"""Estimate homography by the matched keypoints.
Args:
@@ -80,7 +80,7 @@ class ImageStitcher(Module):
raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use `ransac` or `vanilla` instead.")
return homo
- def estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor:
+ def estimate_transform(self, *args: torch.Tensor, **kwargs: torch.Tensor) -> torch.Tensor:
"""Compute the corresponding homography."""
kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"]
homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))]
@@ -88,18 +88,18 @@ class ImageStitcher(Module):
if len(homos) == 0:
raise RuntimeError("Compute homography failed. No matched keypoints found.")
- return concatenate(homos)
+ return torch.cat(homos)
- def blend_image(self, src_img: Tensor, dst_img: Tensor, mask: Tensor) -> Tensor:
+ def blend_image(self, src_img: torch.Tensor, dst_img: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Blend two images together."""
- out: Tensor
+ out: torch.Tensor
if self.blending_method == "naive":
- out = where(mask == 1, src_img, dst_img)
+ out = torch.where(mask == 1, src_img, dst_img)
else:
raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use `naive`.")
return out
- def preprocess(self, image_1: Tensor, image_2: Tensor) -> Dict[str, Tensor]:
+ def preprocess(self, image_1: torch.Tensor, image_2: torch.Tensor) -> Dict[str, torch.Tensor]:
"""Preprocess input to the required format."""
# TODO: probably perform histogram matching here.
if isinstance(self.matcher, (LoFTR, LocalFeatureMatcher)):
@@ -111,7 +111,7 @@ class ImageStitcher(Module):
raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")
return input_dict
- def postprocess(self, image: Tensor, mask: Tensor) -> Tensor:
+ def postprocess(self, image: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
# NOTE: assumes no batch mode. This method keeps all valid regions after stitching.
mask_ = mask.sum((0, 1))
index = int(mask_.bool().any(0).long().argmin().item())
@@ -119,23 +119,23 @@ class ImageStitcher(Module):
return image
return image[..., :index]
- def on_matcher(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
+ def on_matcher(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
return self.matcher(data)
def stitch_pair(
self,
- images_left: Tensor,
- images_right: Tensor,
- mask_left: Optional[Tensor] = None,
- mask_right: Optional[Tensor] = None,
- ) -> Tuple[Tensor, Tensor]:
+ images_left: torch.Tensor,
+ images_right: torch.Tensor,
+ mask_left: Optional[torch.Tensor] = None,
+ mask_right: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
# Compute the transformed images
input_dict = self.preprocess(images_left, images_right)
out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
correspondences = self.on_matcher(input_dict)
homo = self.estimate_transform(**correspondences)
src_img = warp_perspective(images_right, homo, out_shape)
- dst_img = concatenate([images_left, zeros_like(images_right)], -1)
+ dst_img = torch.cat([images_left, torch.zeros_like(images_right)], -1)
# Compute the transformed masks
if mask_left is None:
@@ -144,10 +144,10 @@ class ImageStitcher(Module):
mask_right = torch.ones_like(images_right)
# 'nearest' to ensure no floating points in the mask
src_mask = warp_perspective(mask_right, homo, out_shape, mode="nearest")
- dst_mask = concatenate([mask_left, zeros_like(mask_right)], -1)
+ dst_mask = torch.cat([mask_left, torch.zeros_like(mask_right)], -1)
return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
- def forward(self, *imgs: Tensor) -> Tensor:
+ def forward(self, *imgs: torch.Tensor) -> torch.Tensor:
img_out = imgs[0]
mask_left = torch.ones_like(img_out)
for i in range(len(imgs) - 1):
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index bbf8009a1..6d9bff2de 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -21,7 +21,6 @@ from __future__ import annotations
import torch
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.linalg import euclidean_distance
@@ -31,7 +30,7 @@ class KMeans:
Args:
num_clusters: number of clusters the data has to be assigned to
- cluster_centers: tensor of starting cluster centres can be passed instead of num_clusters
+ cluster_centers: torch.tensor of starting cluster centres can be passed instead of num_clusters
tolerance: float value. the algorithm terminates if the shift in centers is less than tolerance
max_iterations: number of iterations to run the algorithm for
seed: number to set torch manual seed for reproducibility
@@ -46,7 +45,7 @@ class KMeans:
def __init__(
self,
num_clusters: int,
- cluster_centers: Tensor | None,
+ cluster_centers: torch.Tensor | None,
tolerance: float = 10e-4,
max_iterations: int = 0,
seed: int | None = None,
@@ -62,37 +61,37 @@ class KMeans:
self.tolerance = tolerance
self.max_iterations = max_iterations
- self._final_cluster_assignments: None | Tensor = None
- self._final_cluster_centers: None | Tensor = None
+ self._final_cluster_assignments: None | torch.Tensor = None
+ self._final_cluster_centers: None | torch.Tensor = None
if seed is not None:
torch.manual_seed(seed)
@property
- def cluster_centers(self) -> Tensor:
- if isinstance(self._final_cluster_centers, Tensor):
+ def cluster_centers(self) -> torch.Tensor:
+ if isinstance(self._final_cluster_centers, torch.Tensor):
return self._final_cluster_centers
- if isinstance(self._cluster_centers, Tensor):
+ if isinstance(self._cluster_centers, torch.Tensor):
return self._cluster_centers
else:
raise TypeError("Model has not been fit to a dataset")
@property
- def cluster_assignments(self) -> Tensor:
- if isinstance(self._final_cluster_assignments, Tensor):
+ def cluster_assignments(self) -> torch.Tensor:
+ if isinstance(self._final_cluster_assignments, torch.Tensor):
return self._final_cluster_assignments
else:
raise TypeError("Model has not been fit to a dataset")
- def _initialise_cluster_centers(self, X: Tensor, num_clusters: int) -> Tensor:
+ def _initialise_cluster_centers(self, X: torch.Tensor, num_clusters: int) -> torch.Tensor:
"""Chooses num_cluster points from X as the initial cluster centers.
Args:
- X: 2D input tensor to be clustered
+ X: 2D input torch.tensor to be clustered
num_clusters: number of desired cluster centers
Returns:
- 2D Tensor with num_cluster rows
+ 2D torch.Tensor with num_cluster rows
"""
num_samples: int = len(X)
@@ -101,15 +100,15 @@ class KMeans:
initial_state = X[idx]
return initial_state
- def _pairwise_euclidean_distance(self, data1: Tensor, data2: Tensor) -> Tensor:
+ def _pairwise_euclidean_distance(self, data1: torch.Tensor, data2: torch.Tensor) -> torch.Tensor:
"""Compute pairwise squared distance between 2 sets of vectors.
Args:
- data1: 2D tensor of shape N, D
- data2: 2D tensor of shape C, D
+ data1: 2D torch.tensor of shape N, D
+ data2: 2D torch.tensor of shape C, D
Returns:
- 2D tensor of shape N, C
+ 2D torch.tensor of shape N, C
"""
# N*1*D
@@ -119,12 +118,12 @@ class KMeans:
distance = euclidean_distance(A, B)
return distance
- def fit(self, X: Tensor) -> None:
+ def fit(self, X: torch.Tensor) -> None:
"""Fit iterative KMeans clustering till a threshold for shift in cluster centers or a maximum no of iterations
have reached.
Args:
- X: 2D input tensor to be clustered
+ X: 2D input torch.tensor to be clustered
""" # noqa: D205
# X should have only 2 dimensions
@@ -143,12 +142,12 @@ class KMeans:
# X = X.to(self.device)
current_centers = self._cluster_centers
- previous_centers: Tensor | None = None
+ previous_centers: torch.Tensor | None = None
iteration: int = 0
while True:
# find distance between X and current_centers
- distance: Tensor = self._pairwise_euclidean_distance(X, current_centers)
+ distance: torch.Tensor = self._pairwise_euclidean_distance(X, current_centers)
cluster_assignment = distance.argmin(-1)
@@ -177,14 +176,14 @@ class KMeans:
self._final_cluster_assignments = cluster_assignment
self._final_cluster_centers = current_centers
- def predict(self, x: Tensor) -> Tensor:
+ def predict(self, x: torch.Tensor) -> torch.Tensor:
"""Find the cluster center closest to each point in x.
Args:
- x: 2D tensor
+ x: 2D torch.tensor
Returns:
- 1D tensor containing cluster id assigned to each data point in x
+ 1D torch.tensor containing cluster id assigned to each data point in x
"""
# x and cluster_centers should have same number of columns
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index 69e4d7a4b..89cbf154b 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -17,10 +17,11 @@
from typing import Any, Callable
-from kornia.core import Module, Tensor
+import torch
+from torch import nn
-class Lambda(Module):
+class Lambda(nn.Module):
"""Applies user-defined lambda as a transform.
Args:
@@ -38,12 +39,12 @@ class Lambda(Module):
"""
- def __init__(self, func: Callable[..., Tensor]) -> None:
+ def __init__(self, func: Callable[..., torch.Tensor]) -> None:
super().__init__()
if not callable(func):
raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}")
self.func = func
- def forward(self, img: Tensor, *args: Any, **kwargs: Any) -> Tensor:
+ def forward(self, img: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
return self.func(img, *args, **kwargs)
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 1c1f5473a..67b9ae950 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -22,8 +22,8 @@ from enum import Enum
from typing import Any, ClassVar, List, Optional, Tuple, Union
import torch
+from torch import nn
-from kornia.core import Module, Tensor, rand, tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.external import PILImage as Image
from kornia.core.external import onnx
@@ -90,11 +90,14 @@ class ObjectDetectorResult:
bbox: BoundingBox
-def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:
- """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.
+def results_from_detections(
+ detections: torch.Tensor, format: str | BoundingBoxDataFormat
+) -> list[ObjectDetectorResult]:
+ """Convert a detection torch.tensor to a list of :py:class:`ObjectDetectorResult`.
Args:
- detections: tensor with shape :math:`(D, 6)`, where :math:`D` is the number of detections in the given image,
+ detections: torch.tensor with shape :math:`(D, 6)`, torch.where :math:`D` is the number of
+ detections in the given image,
:math:`6` represents class id, score, and `xywh` bounding box.
format: detection format.
@@ -127,7 +130,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
name: str = "detection"
- def __init__(self, model: Module, pre_processor: Module, post_processor: Module) -> None:
+ def __init__(self, model: nn.Module, pre_processor: nn.Module, post_processor: nn.Module) -> None:
"""Initialize ObjectDetector.
Args:
@@ -160,15 +163,16 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
)
@torch.inference_mode()
- def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:
+ def forward(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:
"""Detect objects in a given list of images.
Args:
- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.
+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.
+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
Returns:
- list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the
+ list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`,
+ torch.where :math:`D` is the
number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.
"""
@@ -178,8 +182,11 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
return detections
def visualize(
- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, output_type: str = "torch"
- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore
+ self,
+ images: Union[torch.Tensor, list[torch.Tensor]],
+ detections: Optional[torch.Tensor] = None,
+ output_type: str = "torch",
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
"""Very simple drawing.
Needs to be more fancy later.
@@ -195,16 +202,19 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
)
output.append(out_img[0])
- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))
+ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, torch.Tensor))
def save(
- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None
+ self,
+ images: Union[torch.Tensor, list[torch.Tensor]],
+ detections: Optional[torch.Tensor] = None,
+ directory: Optional[str] = None,
) -> None:
"""Save the output image(s) to a directory.
Args:
- images: input tensor.
- detections: detection tensor.
+ images: input torch.tensor.
+ detections: detection torch.tensor.
directory: directory to save the images.
"""
@@ -279,7 +289,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
)
-class BoxFiltering(Module, ONNXExportMixin):
+class BoxFiltering(nn.Module, ONNXExportMixin):
"""Filter boxes according to the desired threshold.
Args:
@@ -295,8 +305,8 @@ class BoxFiltering(Module, ONNXExportMixin):
def __init__(
self,
- confidence_threshold: Optional[Union[Tensor, float]] = None,
- classes_to_keep: Optional[Union[Tensor, List[int]]] = None,
+ confidence_threshold: Optional[Union[torch.Tensor, float]] = None,
+ classes_to_keep: Optional[Union[torch.Tensor, List[int]]] = None,
filter_as_zero: bool = False,
) -> None:
super().__init__()
@@ -304,37 +314,42 @@ class BoxFiltering(Module, ONNXExportMixin):
self.classes_to_keep = None
self.confidence_threshold = None
if classes_to_keep is not None:
- self.classes_to_keep = classes_to_keep if isinstance(classes_to_keep, Tensor) else tensor(classes_to_keep)
+ self.classes_to_keep = (
+ classes_to_keep if isinstance(classes_to_keep, torch.Tensor) else torch.tensor(classes_to_keep)
+ )
if confidence_threshold is not None:
self.confidence_threshold = (
confidence_threshold or confidence_threshold
- if isinstance(confidence_threshold, Tensor)
- else tensor(confidence_threshold)
+ if isinstance(confidence_threshold, torch.Tensor)
+ else torch.tensor(confidence_threshold)
)
def forward(
- self, boxes: Tensor, confidence_threshold: Optional[Tensor] = None, classes_to_keep: Optional[Tensor] = None
- ) -> Union[Tensor, List[Tensor]]:
+ self,
+ boxes: torch.Tensor,
+ confidence_threshold: Optional[torch.Tensor] = None,
+ classes_to_keep: Optional[torch.Tensor] = None,
+ ) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Filter boxes according to the desired threshold.
To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.
Args:
- boxes: [B, D, 6], where B is the batchsize, D is the number of detections in the image,
+ boxes: [B, D, 6], torch.where B is the batchsize, D is the number of detections in the image,
6 represent (class_id, confidence_score, x, y, w, h).
confidence_threshold: an 0-d scalar that represents the desired threshold.
- classes_to_keep: a 1-d tensor of classes to keep. If None, keep all classes.
+ classes_to_keep: a 1-d torch.tensor of classes to keep. If None, keep all classes.
Returns:
- Union[Tensor, List[Tensor]]
- If `filter_as_zero` is True, return a tensor of shape [D, 6], where D is the total number of
+ Union[torch.Tensor, List[torch.Tensor]]
+ If `filter_as_zero` is True, return a torch.tensor of shape [D, 6], torch.where D is the total number of
detections as input.
- If `filter_as_zero` is False, return a list of tensors of shape [D, 6], where D is the number of
+ If `filter_as_zero` is False, return a list of tensors of shape [D, 6], torch.where D is the number of
valid detections for each element in the batch.
"""
# Apply confidence filtering
- zero_tensor = tensor(0.0, device=boxes.device, dtype=boxes.dtype)
+ zero_tensor = torch.tensor(0.0, device=boxes.device, dtype=boxes.dtype)
confidence_threshold = (
confidence_threshold or self.confidence_threshold or zero_tensor
) # If None, use 0 as threshold
@@ -368,8 +383,8 @@ class BoxFiltering(Module, ONNXExportMixin):
def _create_dummy_input(
self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None
- ) -> Union[Tuple[Any, ...], Tensor]:
- pseudo_input = rand(
+ ) -> Union[Tuple[Any, ...], torch.Tensor]:
+ pseudo_input = torch.rand(
*[
((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)
for i, dim in enumerate(input_shape)
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index b012626e9..c3ba46a9f 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -21,7 +21,6 @@ import torch
from torch import nn
from kornia.config import kornia_config
-from kornia.core import Tensor
from kornia.core.external import PILImage as Image
from kornia.core.external import basicsr, onnx
from kornia.core.mixin.onnx import ONNXExportMixin
@@ -50,15 +49,15 @@ class SuperResolution(ModelBase, ONNXExportMixin):
pseudo_image_size: Optional[int]
@torch.inference_mode()
- def forward(self, images: Union[Tensor, List[Tensor]]) -> Union[Tensor, List[Tensor]]:
+ def forward(self, images: Union[torch.Tensor, List[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Forward pass of the super resolution model.
Args:
- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.
+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.
+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
Returns:
- output tensor.
+ output torch.tensor.
"""
output = self.pre_processor(images)
@@ -74,19 +73,19 @@ class SuperResolution(ModelBase, ONNXExportMixin):
def visualize(
self,
- images: Union[Tensor, List[Tensor]],
- edge_maps: Optional[Union[Tensor, List[Tensor]]] = None,
+ images: Union[torch.Tensor, List[torch.Tensor]],
+ edge_maps: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
output_type: str = "torch",
- ) -> Union[Tensor, List[Tensor], List["Image.Image"]]: # type: ignore
+ ) -> Union[torch.Tensor, List[torch.Tensor], List["Image.Image"]]: # type: ignore
"""Draw the super resolution results.
Args:
- images: input tensor.
+ images: input torch.tensor.
edge_maps: detected edges.
output_type: type of the output.
Returns:
- output tensor.
+ output torch.tensor.
"""
if edge_maps is None:
@@ -95,26 +94,26 @@ class SuperResolution(ModelBase, ONNXExportMixin):
for edge_map in edge_maps:
output.append(edge_map)
- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))
+ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, torch.Tensor))
def save(
self,
- images: Union[Tensor, List[Tensor]],
- edge_maps: Optional[Union[Tensor, List[Tensor]]] = None,
+ images: Union[torch.Tensor, List[torch.Tensor]],
+ edge_maps: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
directory: Optional[str] = None,
output_type: str = "torch",
) -> None:
"""Save the super resolution results.
Args:
- images: input tensor.
+ images: input torch.tensor.
edge_maps: detected edges.
output_type: type of the output.
- directory: where to save outputs.
+ directory: torch.where to save outputs.
output_type: backend used to generate outputs.
Returns:
- output tensor.
+ output torch.tensor.
"""
outputs = self.visualize(images, edge_maps, output_type)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index e2d7fb224..72cc290d3 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -20,12 +20,12 @@ from __future__ import annotations
from typing import Any, Optional
import torch
+import torch.nn.functional as F
from kornia.augmentation import LongestMaxSize
from kornia.augmentation.container.augment import AugmentationSequential
-from kornia.core import Tensor, pad, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-from kornia.enhance import normalize
+from kornia.enhance import normalize as kornia_normalize
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.models.sam import Sam, SamConfig
@@ -39,7 +39,7 @@ class VisualPrompter:
For default the images are transformed to have their long side with size of the `image_encoder.img_size`. This
Prompter class ensure to transform the images and the prompts before prediction. Also, the image is passed
- automatically for the method `preprocess_image`, which is responsible for normalize the image and pad it to have
+ automatically for the method `preprocess_image`, which is responsible for F.normalize the image and F.pad it to have
the right size for the SAM model :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`. For
default the image is normalized by the mean and standard deviation of the SAM dataset values.
@@ -81,8 +81,12 @@ class VisualPrompter:
if isinstance(config, SamConfig):
self.model = Sam.from_config(config)
transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
- self.pixel_mean: Optional[Tensor] = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
- self.pixel_std: Optional[Tensor] = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
+ self.pixel_mean: Optional[torch.Tensor] = (
+ torch.tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
+ )
+ self.pixel_std: Optional[torch.Tensor] = (
+ torch.tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
+ )
else:
raise NotImplementedError
@@ -96,13 +100,16 @@ class VisualPrompter:
self._input_encoder_size: None | tuple[int, int] = None
self.reset_image()
- def preprocess_image(self, x: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> Tensor:
- """Normalize and pad a tensor.
+ def preprocess_image(
+ self, x: torch.Tensor, mean: Optional[torch.Tensor] = None, std: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ """Normalize and F.pad a torch.tensor.
- For normalize the tensor: will prioritize the `mean` and `std` passed as argument, if None will use the default
+ For F.normalize the tensor: will prioritize the `mean` and `std` passed as argument,
+ if None will use the default
Sam Dataset values.
- For pad the tensor: Will pad the tensor into the right and bottom to match with the size of
+ For F.pad the tensor: Will F.pad the torch.tensor into the right and bottom to match with the size of
`self.model.image_encoder.img_size`
Args:
@@ -114,26 +121,28 @@ class VisualPrompter:
The image preprocessed (normalized if has mean and str available and padded to encoder size)
"""
- if isinstance(mean, Tensor) and isinstance(std, Tensor):
- x = normalize(x, mean, std)
- elif isinstance(self.pixel_mean, Tensor) and isinstance(self.pixel_std, Tensor):
- x = normalize(x, self.pixel_mean, self.pixel_std)
+ if isinstance(mean, torch.Tensor) and isinstance(std, torch.Tensor):
+ x = kornia_normalize(x, mean, std)
+ elif isinstance(self.pixel_mean, torch.Tensor) and isinstance(self.pixel_std, torch.Tensor):
+ x = kornia_normalize(x, self.pixel_mean, self.pixel_std)
encoder_im_size = self.model.image_encoder.img_size
pad_h = encoder_im_size - x.shape[-2]
pad_w = encoder_im_size - x.shape[-1]
- x = pad(x, (0, pad_w, 0, pad_h))
+ x = F.pad(x, (0, pad_w, 0, pad_h))
return x
@torch.no_grad()
- def set_image(self, image: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> None:
+ def set_image(
+ self, image: torch.Tensor, mean: Optional[torch.Tensor] = None, std: Optional[torch.Tensor] = None
+ ) -> None:
"""Set the embeddings from the given image with `image_decoder` of the model.
Prepare the given image with the selected transforms and the preprocess method.
Args:
- image: RGB image. Normally images with range of [0-1], the model preprocess normalize the
+ image: RGB image. Normally images with range of [0-1], the model preprocess F.normalize the
pixel values with the mean and std defined in its initialization. Expected to be into a float32
dtype. Shape :math:`(3, H, W)`.
mean: mean value of dataset for normalization.
@@ -157,20 +166,20 @@ class VisualPrompter:
self.image_embeddings = self.model.image_encoder(image)
self.is_image_set = True
- def _valid_keypoints(self, keypoints: Keypoints | Tensor, labels: Tensor) -> Keypoints:
+ def _valid_keypoints(self, keypoints: Keypoints | torch.Tensor, labels: torch.Tensor) -> Keypoints:
"""Validate the keypoints shape and ensure to be a Keypoints."""
KORNIA_CHECK_SHAPE(keypoints.data, ["K", "N", "2"])
KORNIA_CHECK_SHAPE(labels.data, ["K", "N"])
KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], "The keypoints and labels should have the same batch size")
- if isinstance(keypoints, Tensor):
+ if isinstance(keypoints, torch.Tensor):
keypoints = Keypoints.from_tensor(keypoints)
return keypoints
- def _valid_boxes(self, boxes: Boxes | Tensor) -> Boxes:
+ def _valid_boxes(self, boxes: Boxes | torch.Tensor) -> Boxes:
"""Validate the boxes shape and ensure to be a Boxes into xyxy mode."""
- if isinstance(boxes, Tensor):
+ if isinstance(boxes, torch.Tensor):
KORNIA_CHECK_SHAPE(boxes.data, ["K", "4"])
boxes = Boxes(boxes, mode="xyxy")
@@ -181,45 +190,45 @@ class VisualPrompter:
return boxes_xyxy
- def _valid_masks(self, masks: Tensor) -> Tensor:
+ def _valid_masks(self, masks: torch.Tensor) -> torch.Tensor:
"""Validate the input masks shape."""
KORNIA_CHECK_SHAPE(masks, ["K", "1", "256", "256"])
return masks
def _transform_prompts(
- self, *prompts: Tensor | Boxes | Keypoints, data_keys: Optional[list[str]] = None
- ) -> dict[str, Tensor | Boxes | Keypoints]:
+ self, *prompts: torch.Tensor | Boxes | Keypoints, data_keys: Optional[list[str]] = None
+ ) -> dict[str, torch.Tensor | Boxes | Keypoints]:
transformed_prompts = self.transforms(*prompts, data_keys=data_keys, params=self._tfs_params)
if data_keys is None:
data_keys = []
- # prevent unpacking tensor when creating the output dict (issue #2627)
+ # prevent unpacking torch.tensor when creating the output dict (issue #2627)
if not isinstance(transformed_prompts, (list, tuple)):
transformed_prompts = [transformed_prompts]
return {key: transformed_prompts[idx] for idx, key in enumerate(data_keys)}
def preprocess_prompts(
self,
- keypoints: Optional[Keypoints | Tensor] = None,
- keypoints_labels: Optional[Tensor] = None,
- boxes: Optional[Boxes | Tensor] = None,
- masks: Optional[Tensor] = None,
+ keypoints: Optional[Keypoints | torch.Tensor] = None,
+ keypoints_labels: Optional[torch.Tensor] = None,
+ boxes: Optional[Boxes | torch.Tensor] = None,
+ masks: Optional[torch.Tensor] = None,
) -> Prompts:
"""Validate and preprocess the given prompts to be aligned with the input image."""
data_keys = []
- to_transform: list[Keypoints | Boxes | Tensor] = []
+ to_transform: list[Keypoints | Boxes | torch.Tensor] = []
- if isinstance(keypoints, (Keypoints, Tensor)) and isinstance(keypoints_labels, Tensor):
+ if isinstance(keypoints, (Keypoints, torch.Tensor)) and isinstance(keypoints_labels, torch.Tensor):
keypoints = self._valid_keypoints(keypoints, keypoints_labels)
data_keys.append("keypoints")
to_transform.append(keypoints)
- if isinstance(boxes, (Boxes, Tensor)):
+ if isinstance(boxes, (Boxes, torch.Tensor)):
self._valid_boxes(boxes)
data_keys.append("bbox_xyxy")
to_transform.append(boxes)
- if isinstance(masks, Tensor):
+ if isinstance(masks, torch.Tensor):
self._valid_masks(masks)
data = self._transform_prompts(*to_transform, data_keys=data_keys)
@@ -243,10 +252,10 @@ class VisualPrompter:
@torch.no_grad()
def predict(
self,
- keypoints: Optional[Keypoints | Tensor] = None,
- keypoints_labels: Optional[Tensor] = None,
- boxes: Optional[Boxes | Tensor] = None,
- masks: Optional[Tensor] = None,
+ keypoints: Optional[Keypoints | torch.Tensor] = None,
+ keypoints_labels: Optional[torch.Tensor] = None,
+ boxes: Optional[Boxes | torch.Tensor] = None,
+ masks: Optional[torch.Tensor] = None,
multimask_output: bool = True,
output_original_size: bool = True,
) -> SegmentationResults:
@@ -258,9 +267,9 @@ class VisualPrompter:
keypoints_labels: Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background
point. Shape :math:`(K, N)`. Where `N` is the number of points, and `K` the number of
prompts.
- boxes: A box prompt to the model. If a tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
+ boxes: A box prompt to the model. If a torch.tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
masks: A low resolution mask input to the model, typically coming from a previous prediction
- iteration. Has shape :math:`(K, 1, H, W)`, where for SAM, H=W=256.
+ iteration. Has shape :math:`(K, 1, H, W)`, torch.where for SAM, H=W=256.
multimask_output: If true, the model will return three masks. For ambiguous input prompts (such as a
single click), this will often produce better masks than a single prediction. If only
a single mask is needed, the model's predicted quality score can be used to select the
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index fc366686a..b1c24870d 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -21,40 +21,6 @@ This subpackage provides core functionality, device management, and backend supp
"""
from . import external
-from ._backend import (
- Device,
- Dtype,
- Module,
- ModuleList,
- Parameter,
- Sequential,
- Tensor,
- arange,
- as_tensor,
- complex,
- concatenate,
- cos,
- deg2rad,
- diag,
- einsum,
- eye,
- linspace,
- map_coordinates,
- normalize,
- ones,
- ones_like,
- pad,
- rad2deg,
- rand,
- sin,
- softmax,
- stack,
- tan,
- tensor,
- where,
- zeros,
- zeros_like,
-)
from .mixin import (
ImageModuleMixIn,
ONNXExportMixin,
@@ -65,44 +31,12 @@ from .module import ImageModule, ImageSequential
from .tensor_wrapper import TensorWrapper # type: ignore
__all__ = [
- "Device",
- "Dtype",
"ImageModule",
"ImageModuleMixIn",
"ImageSequential",
- "Module",
- "ModuleList",
"ONNXExportMixin",
"ONNXMixin",
"ONNXRuntimeMixin",
- "Parameter",
- "Sequential",
- "Tensor",
"TensorWrapper",
- "arange",
- "as_tensor",
- "complex",
- "concatenate",
- "cos",
- "deg2rad",
- "diag",
- "einsum",
"external",
- "eye",
- "linspace",
- "map_coordinates",
- "normalize",
- "ones",
- "ones_like",
- "pad",
- "rad2deg",
- "rand",
- "sin",
- "softmax",
- "stack",
- "tan",
- "tensor",
- "where",
- "zeros",
- "zeros_like",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
deleted file mode 100644
index 07f04f5d6..000000000
--- a/kornia/core/_backend.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-from typing import Union
-
-import torch
-
-# classes
-Tensor = torch.Tensor
-tensor = torch.tensor
-Module = torch.nn.Module
-ModuleList = torch.nn.ModuleList
-Parameter = torch.nn.Parameter
-Sequential = torch.nn.Sequential
-
-# functions
-# NOTE: ideally we expose what we find in numpy
-arange = torch.arange
-concatenate = torch.cat
-stack = torch.stack
-linspace = torch.linspace
-normalize = torch.nn.functional.normalize
-pad = torch.nn.functional.pad
-eye = torch.eye
-einsum = torch.einsum
-zeros = torch.zeros
-zeros_like = torch.zeros_like
-ones = torch.ones
-ones_like = torch.ones_like
-where = torch.where
-complex = torch.complex
-diag = torch.diag
-softmax = torch.nn.functional.softmax
-map_coordinates = torch.nn.functional.grid_sample
-cos = torch.cos
-sin = torch.sin
-tan = torch.tan
-deg2rad = torch.deg2rad
-rad2deg = torch.rad2deg
-
-# constructors
-as_tensor = torch.as_tensor
-from_numpy = torch.from_numpy
-
-# random
-rand = torch.rand
-
-# type alias
-Device = Union[str, torch.device, None]
-Dtype = Union[torch.dtype, None]
diff --git a/kornia/core/check.py b/kornia/core/check.py
index c5f9eeb4e..d075135cc 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -26,7 +26,6 @@ import torch
from torch import float16, float32, float64
from typing_extensions import TypeGuard
-from kornia.core import Tensor
from kornia.core.exceptions import (
BaseError,
DeviceError,
@@ -102,9 +101,9 @@ def disable_checks() -> None:
"""Disable all Kornia validation checks for production.
Note:
- This function can override the initial setting determined at import time.
- The module-level flag is evaluated once at import time for performance, but
- can be changed at runtime via this function or `enable_checks()`.
+ This function has no effect if checks were disabled at import time
+ (via `python -O` or KORNIA_CHECKS=0). The module-level flag is
+ evaluated once at import time for performance.
Example:
>>> disable_checks()
@@ -118,11 +117,6 @@ def disable_checks() -> None:
def enable_checks() -> None:
"""Enable all Kornia validation checks.
- Note:
- This function can override the initial setting determined at import time.
- The module-level flag is evaluated once at import time for performance, but
- can be changed at runtime via this function or `disable_checks()`.
-
Example:
>>> enable_checks()
>>> are_checks_enabled()
@@ -135,7 +129,7 @@ def enable_checks() -> None:
# Logger api
-def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether a tensor has a specified shape.
The shape can be specified with a implicit or explicit list of strings.
@@ -320,7 +314,7 @@ def KORNIA_CHECK_TYPE(
return True
-def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[Tensor]:
+def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[torch.Tensor]:
"""Check the input variable is a Tensor.
Args:
@@ -347,7 +341,7 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =
if not _KORNIA_CHECKS_ENABLED:
return True
- if not isinstance(x, Tensor):
+ if not isinstance(x, torch.Tensor):
if raises:
error_msg = f"Type mismatch: expected Tensor, got {type(x).__name__}."
if msg is not None:
@@ -355,13 +349,13 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =
raise TypeCheckError(
error_msg,
actual_type=type(x),
- expected_type=Tensor,
+ expected_type=torch.Tensor,
)
return False
return True
-def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[Tensor]]:
+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[torch.Tensor]]:
"""Check the input variable is a List of Tensors.
Args:
@@ -392,20 +386,20 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool =
if not _KORNIA_CHECKS_ENABLED:
return True
- are_tensors = isinstance(x, list) and all(isinstance(d, Tensor) for d in x)
+ are_tensors = isinstance(x, list) and all(isinstance(d, torch.Tensor) for d in x)
if not are_tensors:
if raises:
error_msg = f"Type mismatch: expected list[Tensor], got {type(x).__name__}."
raise TypeCheckError(
error_msg,
actual_type=type(x),
- expected_type=list[Tensor],
+ expected_type=list[torch.Tensor],
)
return False
return True
-def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_DEVICE(x: torch.Tensor, y: torch.Tensor, raises: bool = True) -> bool:
"""Check whether two tensor in the same device.
Args:
@@ -447,7 +441,7 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
return True
-def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether a list provided tensors live in the same device.
Args:
@@ -493,7 +487,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None,
return True
-def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_SHAPE(x: torch.Tensor, y: torch.Tensor, raises: bool = True) -> bool:
"""Check whether two tensor have the same shape.
Args:
@@ -537,7 +531,7 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
return True
-def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is a color images.
Args:
@@ -574,7 +568,7 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = T
return True
-def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale.
Args:
@@ -611,7 +605,7 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = Tr
return True
-def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale or color.
Args:
@@ -648,7 +642,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises:
return True
-def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool:
+def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool:
"""Check whether an image tensor is ranged properly [0, 1] for float or [0, 2 ** bits] for int.
Args:
@@ -696,7 +690,7 @@ def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = T
return True
-def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: bool = True) -> bool:
+def KORNIA_CHECK_DM_DESC(desc1: torch.Tensor, desc2: torch.Tensor, dm: torch.Tensor, raises: bool = True) -> bool:
"""Check whether the provided descriptors match with a distance matrix.
Args:
@@ -750,7 +744,7 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: bool
return True
-def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool:
+def KORNIA_CHECK_LAF(laf: torch.Tensor, raises: bool = True) -> bool:
"""Check whether a Local Affine Frame (laf) has a valid shape.
Args:
@@ -775,11 +769,13 @@ def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool:
return KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"], raises=raises)
-def _handle_invalid_range(msg: Optional[str], raises: bool, min_val: float | Tensor, max_val: float | Tensor) -> bool:
+def _handle_invalid_range(
+ msg: Optional[str], raises: bool, min_val: float | torch.Tensor, max_val: float | torch.Tensor
+) -> bool:
"""Handle invalid range cases."""
# Extract scalar values if tensors
- min_scalar = min_val.item() if isinstance(min_val, Tensor) else min_val
- max_scalar = max_val.item() if isinstance(max_val, Tensor) else max_val
+ min_scalar = min_val.item() if isinstance(min_val, torch.Tensor) else min_val
+ max_scalar = max_val.item() if isinstance(max_val, torch.Tensor) else max_val
err_msg = f"Value range mismatch: expected [0, 1], got [{min_scalar}, {max_scalar}]."
if msg is not None:
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index ac1f4700e..ca1e9e574 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -21,7 +21,8 @@ import os
from functools import wraps
from typing import Any, Callable, List, Optional, Tuple, Union
-from kornia.core._backend import Tensor, from_numpy
+import torch
+
from kornia.core.external import PILImage as Image
from kornia.core.external import numpy as np
@@ -107,7 +108,7 @@ class ImageModuleMixIn:
"""
if isinstance(arg, (str,)) and os.path.exists(arg):
return True
- if isinstance(arg, (Tensor,)):
+ if isinstance(arg, (torch.Tensor,)):
return True
# Make sure that the numpy and PIL are not necessarily needed to be imported.
if isinstance(arg, (np.ndarray,)): # type: ignore
@@ -116,7 +117,7 @@ class ImageModuleMixIn:
return True
return False
- def to_tensor(self, x: Any) -> Tensor:
+ def to_tensor(self, x: Any) -> torch.Tensor:
"""Convert input to tensor.
Supports image path, numpy array, PIL image, and raw tensor.
@@ -132,14 +133,14 @@ class ImageModuleMixIn:
from kornia.io import ImageLoadType, load_image # pylint: disable=C0415
return load_image(x, ImageLoadType.UNCHANGED) / 255
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
return x
if isinstance(x, (np.ndarray,)): # type: ignore
from kornia.utils.image import image_to_tensor # pylint: disable=C0415
return image_to_tensor(x) / 255
if isinstance(x, (Image.Image,)): # type: ignore
- return from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
+ return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
raise TypeError("Input type not supported")
def to_numpy(self, x: Any) -> "np.array": # type: ignore
@@ -152,7 +153,7 @@ class ImageModuleMixIn:
np.array: The converted numpy array.
"""
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
return x.cpu().detach().numpy()
if isinstance(x, (np.ndarray,)): # type: ignore
return x
@@ -170,7 +171,7 @@ class ImageModuleMixIn:
Image.Image: The converted PIL image.
"""
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
x = x.cpu().detach() * 255
if x.dim() == 3:
x = x.permute(1, 2, 0)
@@ -187,9 +188,9 @@ class ImageModuleMixIn:
raise TypeError("Input type not supported")
def _detach_tensor_to_cpu(
- self, output_image: Union[Tensor, List[Tensor], Tuple[Tensor]]
- ) -> Union[Tensor, List[Tensor], Tuple[Tensor]]:
- if isinstance(output_image, (Tensor,)):
+ self, output_image: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]
+ ) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:
+ if isinstance(output_image, (torch.Tensor,)):
return output_image.detach().cpu()
if isinstance(
output_image,
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 3885f3c20..de71ec187 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -27,9 +27,9 @@ from typing import (
)
import torch
+from torch import nn
import kornia
-from kornia.core import Module, Tensor, rand
from kornia.core.external import numpy as np
from kornia.core.external import onnx
from kornia.core.external import onnxruntime as ort
@@ -69,7 +69,7 @@ class ONNXExportMixin:
input_shape: Optional[list[int]] = None,
output_shape: Optional[list[int]] = None,
pseudo_shape: Optional[list[int]] = None,
- model: Optional[Module] = None,
+ model: Optional[nn.Module] = None,
save: bool = True,
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
@@ -149,8 +149,8 @@ class ONNXExportMixin:
def _create_dummy_input(
self, input_shape: list[int], pseudo_shape: Optional[list[int]] = None
- ) -> Union[tuple[Any, ...], Tensor]:
- return rand(
+ ) -> Union[tuple[Any, ...], torch.Tensor]:
+ return torch.rand(
*[
((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)
for i, dim in enumerate(input_shape)
diff --git a/kornia/core/module.py b/kornia/core/module.py
index 3dcaca8e0..546d42e34 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -23,10 +23,12 @@ import os
from functools import wraps
from typing import Any, Callable, Optional, Union
+import torch
+from torch import nn
+
# TODO: not use top level import
import kornia
-from ._backend import Module, Sequential, Tensor, from_numpy
from .external import PILImage as Image
from .external import numpy as np
from .mixin.onnx import ONNXExportMixin
@@ -56,10 +58,18 @@ class ImageModuleMixIn:
Callable: Decorated function with converted input and output types.
"""
+ # Ensure output_type has a valid default
+ if not output_type or output_type not in ("tensor", "numpy", "pil"):
+ output_type = "tensor"
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Union[Any, list[Any]]:
+ # Remove output_type and input_names_to_handle from kwargs if present
+ # (they are handled by the decorator, not the wrapped function)
+ kwargs.pop("output_type", None)
+ kwargs.pop("input_names_to_handle", None)
+
# If input_names_to_handle is None, handle all inputs
if input_names_to_handle is None:
# Convert all args to tensors
@@ -113,7 +123,7 @@ class ImageModuleMixIn:
"""
if isinstance(arg, (str,)) and os.path.exists(arg):
return True
- if isinstance(arg, (Tensor,)):
+ if isinstance(arg, (torch.Tensor,)):
return True
# Make sure that the numpy and PIL are not necessarily needed to be imported.
if isinstance(arg, (np.ndarray,)): # type: ignore
@@ -122,7 +132,7 @@ class ImageModuleMixIn:
return True
return False
- def to_tensor(self, x: Any) -> Tensor:
+ def to_tensor(self, x: Any) -> torch.Tensor:
"""Convert input to tensor.
Supports image path, numpy array, PIL image, and raw tensor.
@@ -136,12 +146,12 @@ class ImageModuleMixIn:
"""
if isinstance(x, (str,)):
return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
return x
if isinstance(x, (np.ndarray,)): # type: ignore
return kornia.utils.image.image_to_tensor(x) / 255
if isinstance(x, (Image.Image,)): # type: ignore
- return from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
+ return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
raise TypeError("Input type not supported")
def to_numpy(self, x: Any) -> np.array: # type: ignore
@@ -154,7 +164,7 @@ class ImageModuleMixIn:
np.array: The converted numpy array.
"""
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
return x.cpu().detach().numpy()
if isinstance(x, (np.ndarray,)): # type: ignore
return x
@@ -172,7 +182,7 @@ class ImageModuleMixIn:
Image.Image: The converted PIL image.
"""
- if isinstance(x, (Tensor,)):
+ if isinstance(x, (torch.Tensor,)):
tensor = x.detach().cpu()
if tensor.ndim == 3:
tensor.mul_(255)
@@ -194,8 +204,8 @@ class ImageModuleMixIn:
raise TypeError("Input type not supported")
def _detach_tensor_to_cpu(
- self, output_image: Union[Tensor, list[Tensor], tuple[Tensor]]
- ) -> Union[Tensor, list[Tensor], tuple[Tensor]]:
+ self, output_image: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]
+ ) -> Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]:
"""Detach the input tensor (or list/tuple of tensors) from the GPU and move it to the CPU.
Args:
@@ -205,7 +215,7 @@ class ImageModuleMixIn:
Union[Tensor, list[Tensor], tuple[Tensor]]: The tensor(s) moved to the CPU and detached from
the computational graph.
"""
- if isinstance(output_image, (Tensor,)):
+ if isinstance(output_image, (torch.Tensor,)):
return output_image.detach().cpu()
if isinstance(
output_image,
@@ -264,7 +274,7 @@ class ImageModuleMixIn:
kornia.io.write_image(name, out_image.mul(255.0).byte())
-class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):
+class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
"""Handles image-based operations.
This modules accepts multiple input and output data types, provides end-to-end
@@ -323,7 +333,7 @@ class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):
return _output_image
-class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin):
+class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
"""Handles image-based operations as a sequential module.
This modules accepts multiple input and output data types, provides end-to-end
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 93a533a38..af51a2f97 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -21,10 +21,10 @@ from math import pi
from typing import ClassVar, Optional, Union
import torch
+import torch.nn.functional as F
+from torch import nn
from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv
-from kornia.core import ImageModule as Module
-from kornia.core import Parameter, Tensor, tensor
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_COLOR_OR_GRAY,
@@ -34,18 +34,18 @@ from kornia.utils.helpers import _torch_histc_cast
from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video
-def adjust_saturation_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
+def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
Expecting image to be in hsv format already.
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
@@ -56,15 +56,15 @@ def adjust_saturation_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor
h, s, v = torch.chunk(image, chunks=3, dim=-3)
# transform the hue value and appl module
- s_out: Tensor = torch.clamp(s * factor, min=0, max=1)
+ s_out: torch.Tensor = torch.clamp(s * factor, min=0, max=1)
# pack back back the corrected hue
- out: Tensor = torch.cat([h, s_out, v], dim=-3)
+ out: torch.Tensor = torch.cat([h, s_out, v], dim=-3)
return out
-def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
+def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image by blending the image with its grayscaled version.
The image is expected to be an RGB image or a gray image in the range of [0, 1].
@@ -75,7 +75,7 @@ def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float,
this is just a convenience function to have compatibility with Pil
Args:
- image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ image: Image/torch.Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
@@ -94,34 +94,34 @@ def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float,
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
KORNIA_CHECK_IS_COLOR_OR_GRAY(image, "Image should be an RGB or gray image")
if image.shape[-3] == 1:
return image
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
while len(factor.shape) != len(image.shape):
factor = factor[..., None]
- x_other: Tensor = rgb_to_grayscale(image)
+ x_other: torch.Tensor = rgb_to_grayscale(image)
# blend the image with the grayscaled image
- x_adjusted: Tensor = (1 - factor) * x_other + factor * image
+ x_adjusted: torch.Tensor = (1 - factor) * x_other + factor * image
# clamp the output
- out: Tensor = torch.clamp(x_adjusted, 0.0, 1.0)
+ out: torch.Tensor = torch.clamp(x_adjusted, 0.0, 1.0)
return out
-def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
+def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
.. image:: _static/img/adjust_saturation.png
@@ -129,7 +129,7 @@ def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
The image is expected to be an RGB image in the range of [0, 1].
Args:
- image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ image: Image/torch.Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
saturation_mode: The mode to adjust saturation.
@@ -152,26 +152,26 @@ def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
"""
# convert the rgb image to hsv
- x_hsv: Tensor = rgb_to_hsv(image)
+ x_hsv: torch.Tensor = rgb_to_hsv(image)
# perform the conversion
- x_adjusted: Tensor = adjust_saturation_raw(x_hsv, factor)
+ x_adjusted: torch.Tensor = adjust_saturation_raw(x_hsv, factor)
# convert back to rgb
- out: Tensor = hsv_to_rgb(x_adjusted)
+ out: torch.Tensor = hsv_to_rgb(x_adjusted)
return out
-def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
+def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust hue of an image.
Expecting image to be in hsv format already.
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(
- isinstance(factor, (float, Tensor)),
- f"The factor should be a float number or Tensor in the range between [-PI, PI]. Got {type(factor)}",
+ isinstance(factor, (float, torch.Tensor)),
+ f"The factor should be a float number or torch.Tensor in the range between [-PI, PI]. Got {type(factor)}",
)
if isinstance(factor, float):
@@ -188,15 +188,15 @@ def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
# transform the hue value and appl module
divisor: float = 2 * pi
- h_out: Tensor = torch.fmod(h + factor, divisor)
+ h_out: torch.Tensor = torch.fmod(h + factor, divisor)
# pack back back the corrected hue
- out: Tensor = torch.cat([h_out, s, v], dim=-3)
+ out: torch.Tensor = torch.cat([h_out, s, v], dim=-3)
return out
-def adjust_hue(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
+def adjust_hue(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust hue of an image.
.. image:: _static/img/adjust_hue.png
@@ -228,18 +228,20 @@ def adjust_hue(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
"""
# convert the rgb image to hsv
- x_hsv: Tensor = rgb_to_hsv(image)
+ x_hsv: torch.Tensor = rgb_to_hsv(image)
# perform the conversion
- x_adjusted: Tensor = adjust_hue_raw(x_hsv, factor)
+ x_adjusted: torch.Tensor = adjust_hue_raw(x_hsv, factor)
# convert back to rgb
- out: Tensor = hsv_to_rgb(x_adjusted)
+ out: torch.Tensor = hsv_to_rgb(x_adjusted)
return out
-def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float, Tensor] = 1.0) -> Tensor:
+def adjust_gamma(
+ input: torch.Tensor, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.0
+) -> torch.Tensor:
r"""Perform gamma correction on an image.
.. image:: _static/img/adjust_contrast.png
@@ -272,20 +274,20 @@ def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float,
torch.Size([2, 5, 3, 3])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if not isinstance(gamma, (float, Tensor)):
- raise TypeError(f"The gamma should be a positive float or Tensor. Got {type(gamma)}")
+ if not isinstance(gamma, (float, torch.Tensor)):
+ raise TypeError(f"The gamma should be a positive float or torch.Tensor. Got {type(gamma)}")
- if not isinstance(gain, (float, Tensor)):
- raise TypeError(f"The gain should be a positive float or Tensor. Got {type(gain)}")
+ if not isinstance(gain, (float, torch.Tensor)):
+ raise TypeError(f"The gain should be a positive float or torch.Tensor. Got {type(gain)}")
if isinstance(gamma, float):
- gamma = Tensor([gamma])
+ gamma = torch.Tensor([gamma])
if isinstance(gain, float):
- gain = Tensor([gain])
+ gain = torch.Tensor([gain])
gamma = gamma.to(input.device).to(input.dtype)
gain = gain.to(input.device).to(input.dtype)
@@ -303,20 +305,20 @@ def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float,
gain = torch.unsqueeze(gain, dim=-1)
# Apply the gamma correction
- x_adjust: Tensor = gain * torch.pow(input, gamma)
+ x_adjust: torch.Tensor = gain * torch.pow(input, gamma)
# Truncate between pixel values
- out: Tensor = torch.clamp(x_adjust, 0.0, 1.0)
+ out: torch.Tensor = torch.clamp(x_adjust, 0.0, 1.0)
return out
-def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor:
- r"""Adjust the contrast of an image tensor.
+def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True) -> torch.Tensor:
+ r"""Adjust the contrast of an image torch.tensor.
.. image:: _static/img/adjust_contrast.png
- This implementation follows Szeliski's book convention, where contrast is defined as
+ This implementation follows Szeliski's book convention, torch.where contrast is defined as
a `multiplicative` operation directly to raw pixel values. Beware that other frameworks
might use different conventions which can be difficult to reproduce exact results.
@@ -355,12 +357,12 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
@@ -370,7 +372,7 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
KORNIA_CHECK(any(factor >= 0), "Contrast factor must be positive.")
# Apply contrast factor to each channel
- img_adjust: Tensor = image * factor
+ img_adjust: torch.Tensor = image * factor
# Truncate between pixel values
if clip_output:
@@ -379,8 +381,8 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
return img_adjust
-def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
- r"""Adjust the contrast of an image tensor by subtracting the mean over channels.
+def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
+ r"""Adjust the contrast of an image torch.tensor by subtracting the mean over channels.
.. note::
this is just a convenience function to have compatibility with Pil. For exact
@@ -410,12 +412,12 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
@@ -430,19 +432,21 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te
img_mean = image.mean()
# Apply contrast factor subtracting the mean
- img_adjust: Tensor = image * factor + img_mean * (1 - factor)
+ img_adjust: torch.Tensor = image * factor + img_mean * (1 - factor)
img_adjust = img_adjust.clamp(min=0.0, max=1.0)
return img_adjust
-def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor:
- r"""Adjust the brightness of an image tensor.
+def adjust_brightness(
+ image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True
+) -> torch.Tensor:
+ r"""Adjust the brightness of an image torch.tensor.
.. image:: _static/img/adjust_brightness.png
- This implementation follows Szeliski's book convention, where brightness is defined as
+ This implementation follows Szeliski's book convention, torch.where brightness is defined as
an `additive` operation directly to raw pixel and shift its values according the applied
factor and range of the image values. Beware that other framework might use different
conventions which can be difficult to reproduce exact results.
@@ -464,7 +468,7 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output:
clip_output: Whether to clip output to be in [0,1].
Return:
- Adjusted tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.
@@ -482,13 +486,13 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output:
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
- # convert factor to a tensor
+ # convert factor to a torch.tensor
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
@@ -496,7 +500,7 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output:
factor = factor[..., None]
# shift pixel values
- img_adjust: Tensor = image + factor
+ img_adjust: torch.Tensor = image + factor
# truncate between pixel values
if clip_output:
@@ -505,8 +509,10 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output:
return img_adjust
-def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor:
- r"""Adjust the brightness accumulatively of an image tensor.
+def adjust_brightness_accumulative(
+ image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True
+) -> torch.Tensor:
+ r"""Adjust the brightness accumulatively of an image torch.tensor.
This implementation follows PIL convention.
@@ -520,7 +526,7 @@ def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor],
clip_output: Whether to clip output to be in [0,1].
Return:
- Adjusted tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -535,13 +541,13 @@ def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor],
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
+ KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
- # convert factor to a tensor
+ # convert factor to a torch.tensor
if isinstance(factor, float):
- # TODO: figure out how to create later a tensor without importing torch
+ # TODO: figure out how to create later a torch.tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- elif isinstance(factor, Tensor):
+ elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
# make factor broadcastable
@@ -549,7 +555,7 @@ def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor],
factor = factor[..., None]
# shift pixel values
- img_adjust: Tensor = image * factor
+ img_adjust: torch.Tensor = image * factor
# truncate between pixel values
if clip_output:
@@ -558,8 +564,8 @@ def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor],
return img_adjust
-def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> Tensor:
- """Adjust sigmoid correction on the input image tensor.
+def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> torch.Tensor:
+ """Adjust sigmoid correction on the input image torch.tensor.
The input image is expected to be in the range of [0, 1].
@@ -574,7 +580,7 @@ def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bo
inv: If is set to True the function will return the inverse sigmoid correction.
Returns:
- Adjusted tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -592,8 +598,8 @@ def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bo
return img_adjust
-def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: bool = True) -> Tensor:
- """Adjust log correction on the input image tensor.
+def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_output: bool = True) -> torch.Tensor:
+ """Adjust log correction on the input image torch.tensor.
The input image is expected to be in the range of [0, 1].
@@ -607,7 +613,7 @@ def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: b
clip_output: Whether to clip the output image with range of [0, 1].
Returns:
- Adjusted tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.zeros(1, 1, 2, 2)
@@ -630,7 +636,7 @@ def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: b
return img_adjust
-def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:
+def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5) -> torch.Tensor:
r"""For each pixel in the image, select the pixel if the value is less than the threshold.
Otherwise, subtract 1.0 from the pixel.
@@ -638,20 +644,20 @@ def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:
Args:
input: image or batched images to solarize.
thresholds: solarize thresholds.
- If int or one element tensor, input will be solarized across the whole batch.
- If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).
+ If int or one element torch.tensor, input will be solarized across the whole batch.
+ If 1-d torch.tensor, input will be solarized element-wise, len(thresholds) == len(input).
Returns:
Solarized images.
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if not isinstance(thresholds, (float, Tensor)):
- raise TypeError(f"The factor should be either a float or Tensor. Got {type(thresholds)}")
+ if not isinstance(thresholds, (float, torch.Tensor)):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(thresholds)}")
- if isinstance(thresholds, Tensor) and len(thresholds.shape) != 0:
+ if isinstance(thresholds, torch.Tensor) and len(thresholds.shape) != 0:
if not (input.size(0) == len(thresholds) and len(thresholds.shape) == 1):
raise AssertionError(f"thresholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}")
# TODO: I am not happy about this line, but no easy to do batch-wise operation
@@ -662,10 +668,10 @@ def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:
def solarize(
- input: Tensor,
- thresholds: Union[float, Tensor] = 0.5,
- additions: Optional[Union[float, Tensor]] = None,
-) -> Tensor:
+ input: torch.Tensor,
+ thresholds: Union[float, torch.Tensor] = 0.5,
+ additions: Optional[Union[float, torch.Tensor]] = None,
+) -> torch.Tensor:
r"""For each pixel in the image less than threshold.
.. image:: _static/img/solarize.png
@@ -674,14 +680,14 @@ def solarize(
The value of 'addition' is between -0.5 and 0.5.
Args:
- input: image tensor with shapes like :math:`(*, C, H, W)` to solarize.
+ input: image torch.tensor with shapes like :math:`(*, C, H, W)` to solarize.
thresholds: solarize thresholds.
- If int or one element tensor, input will be solarized across the whole batch.
- If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).
+ If int or one element torch.tensor, input will be solarized across the whole batch.
+ If 1-d torch.tensor, input will be solarized element-wise, len(thresholds) == len(input).
additions: between -0.5 and 0.5.
If None, no addition will be performed.
- If int or one element tensor, same addition will be added across the whole batch.
- If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).
+ If int or one element torch.tensor, same addition will be added across the whole batch.
+ If 1-d torch.tensor, additions will be added element-wisely, len(additions) == len(input).
Returns:
The solarized images with shape :math:`(*, C, H, W)`.
@@ -699,18 +705,18 @@ def solarize(
torch.Size([2, 4, 3, 3])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if not isinstance(thresholds, (float, Tensor)):
- raise TypeError(f"The factor should be either a float or Tensor. Got {type(thresholds)}")
+ if not isinstance(thresholds, (float, torch.Tensor)):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(thresholds)}")
if isinstance(thresholds, float):
thresholds = torch.as_tensor(thresholds)
if additions is not None:
- if not isinstance(additions, (float, Tensor)):
- raise TypeError(f"The factor should be either a float or Tensor. Got {type(additions)}")
+ if not isinstance(additions, (float, torch.Tensor)):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(additions)}")
if isinstance(additions, float):
additions = torch.as_tensor(additions)
@@ -718,7 +724,7 @@ def solarize(
if not torch.all((additions < 0.5) * (additions > -0.5)):
raise AssertionError(f"The value of 'addition' is between -0.5 and 0.5. Got {additions}.")
- if isinstance(additions, Tensor) and len(additions.shape) != 0:
+ if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:
if not (input.size(0) == len(additions) and len(additions.shape) == 1):
raise AssertionError(f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}")
# TODO: I am not happy about this line, but no easy to do batch-wise operation
@@ -731,7 +737,7 @@ def solarize(
@perform_keep_shape_image
-def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
+def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:
r"""Reduce the number of bits for each color channel.
.. image:: _static/img/posterize.png
@@ -739,11 +745,12 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
Non-differentiable function, ``torch.uint8`` involved.
Args:
- input: image tensor with shape :math:`(*, C, H, W)` to posterize.
+ input: image torch.tensor with shape :math:`(*, C, H, W)` to posterize.
bits: number of high bits. Must be in range [0, 8].
- If int or one element tensor, input will be posterized by this bits.
- If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
- If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]
+ If int or one element torch.tensor, input will be posterized by this bits.
+ If 1-d torch.tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
+ If n-d torch.tensor, input will be posterized element-channel-wisely,
+ bits.shape == input.shape[:len(bits.shape)]
Returns:
Image with reduced color channels with shape :math:`(*, C, H, W)`.
@@ -759,11 +766,11 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
torch.Size([2, 6, 3, 3])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if not isinstance(bits, (int, Tensor)):
- raise TypeError(f"bits type is not an int or Tensor. Got {type(bits)}")
+ if not isinstance(bits, (int, torch.Tensor)):
+ raise TypeError(f"bits type is not an int or torch.Tensor. Got {type(bits)}")
if isinstance(bits, int):
bits = torch.as_tensor(bits)
@@ -778,13 +785,13 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
# Ref: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L222
# Potential approach: implementing kornia.LUT with floating points
# https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472
- def _left_shift(input: Tensor, shift: Tensor) -> Tensor:
+ def _left_shift(input: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:
return ((input * 255).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.0
- def _right_shift(input: Tensor, shift: Tensor) -> Tensor:
+ def _right_shift(input: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:
return (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0
- def _posterize_one(input: Tensor, bits: Tensor) -> Tensor:
+ def _posterize_one(input: torch.Tensor, bits: torch.Tensor) -> torch.Tensor:
# Single bits value condition
if bits == 0:
return torch.zeros_like(input)
@@ -820,8 +827,8 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
@perform_keep_shape_image
-def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
- r"""Apply sharpness to the input tensor.
+def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
+ r"""Apply sharpness to the input torch.tensor.
.. image:: _static/img/sharpness.png
@@ -829,10 +836,10 @@ def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326
Args:
- input: image tensor with shape :math:`(*, C, H, W)` to sharpen.
+ input: image torch.tensor with shape :math:`(*, C, H, W)` to sharpen.
factor: factor of sharpness strength. Must be above 0.
- If float or one element tensor, input will be sharpened by the same factor across the whole batch.
- If 1-d tensor, input will be sharpened element-wisely, len(factor) == len(input).
+ If float or one element torch.tensor, input will be sharpened by the same factor across the whole batch.
+ If 1-d torch.tensor, input will be sharpened element-wisely, len(factor) == len(input).
Returns:
Sharpened image or images with shape :math:`(*, C, H, W)`.
@@ -843,12 +850,12 @@ def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
torch.Size([1, 1, 5, 5])
"""
- if not isinstance(factor, Tensor):
+ if not isinstance(factor, torch.Tensor):
factor = torch.as_tensor(factor, device=input.device, dtype=input.dtype)
if len(factor.size()) != 0 and factor.shape != torch.Size([input.size(0)]):
raise AssertionError(
- "Input batch size shall match with factor size if factor is not a 0-dim tensor. "
+ "Input batch size shall match with factor size if factor is not a 0-dim torch.tensor. "
f"Got {input.size(0)} and {factor.shape}"
)
@@ -866,8 +873,8 @@ def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
# For the borders of the resulting image, fill in the values of the original image.
mask = torch.ones_like(degenerate)
- padded_mask = torch.nn.functional.pad(mask, [1, 1, 1, 1])
- padded_degenerate = torch.nn.functional.pad(degenerate, [1, 1, 1, 1])
+ padded_mask = F.pad(mask, [1, 1, 1, 1])
+ padded_degenerate = F.pad(degenerate, [1, 1, 1, 1])
result = torch.where(padded_mask == 1, padded_degenerate, input)
if len(factor.size()) == 0:
@@ -875,25 +882,25 @@ def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
return torch.stack([_blend_one(result[i], input[i], factor[i]) for i in range(len(factor))])
-def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor:
+def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:
r"""Blend two images into one.
Args:
- input1: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- input2: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- factor: factor 0-dim tensor.
+ input1: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ input2: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ factor: factor 0-dim torch.tensor.
Returns:
- : image tensor with the batch in the zero position.
+ : image torch.tensor with the batch in the zero position.
"""
- if not isinstance(input1, Tensor):
- raise AssertionError(f"`input1` must be a tensor. Got {input1}.")
- if not isinstance(input2, Tensor):
- raise AssertionError(f"`input1` must be a tensor. Got {input2}.")
+ if not isinstance(input1, torch.Tensor):
+ raise AssertionError(f"`input1` must be a torch.tensor. Got {input1}.")
+ if not isinstance(input2, torch.Tensor):
+ raise AssertionError(f"`input1` must be a torch.tensor. Got {input2}.")
- if isinstance(factor, Tensor) and len(factor.size()) != 0:
- raise AssertionError(f"Factor shall be a float or single element tensor. Got {factor}.")
+ if isinstance(factor, torch.Tensor) and len(factor.size()) != 0:
+ raise AssertionError(f"Factor shall be a float or single element torch.tensor. Got {factor}.")
if factor == 0.0:
return input1
if factor == 1.0:
@@ -905,7 +912,7 @@ def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor:
return torch.clamp(res, 0, 1)
-def _build_lut(histo: Tensor, step: Tensor) -> Tensor:
+def _build_lut(histo: torch.Tensor, step: torch.Tensor) -> torch.Tensor:
# Compute the cumulative sum, shifting by step // 2
# and then normalization by step.
step_trunc = torch.div(step, 2, rounding_mode="trunc")
@@ -918,28 +925,28 @@ def _build_lut(histo: Tensor, step: Tensor) -> Tensor:
# Code taken from: https://github.com/pytorch/vision/pull/796
-def _scale_channel(im: Tensor) -> Tensor:
+def _scale_channel(im: torch.Tensor) -> torch.Tensor:
r"""Scale the data in the channel to implement equalize.
Args:
- im: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ im: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
Returns:
- image tensor with the batch in the zero position.
+ image torch.tensor with the batch in the zero position.
"""
min_ = im.min()
max_ = im.max()
if min_.item() < 0.0 and not torch.isclose(min_, torch.as_tensor(0.0, dtype=min_.dtype)):
- raise ValueError(f"Values in the input tensor must greater or equal to 0.0. Found {min_.item()}.")
+ raise ValueError(f"Values in the input torch.tensor must greater or equal to 0.0. Found {min_.item()}.")
if max_.item() > 1.0 and not torch.isclose(max_, torch.as_tensor(1.0, dtype=max_.dtype)):
- raise ValueError(f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}.")
+ raise ValueError(f"Values in the input torch.tensor must lower or equal to 1.0. Found {max_.item()}.")
ndims = len(im.shape)
if ndims not in (2, 3):
- raise TypeError(f"Input tensor must have 2 or 3 dimensions. Found {ndims}.")
+ raise TypeError(f"Input torch.tensor must have 2 or 3 dimensions. Found {ndims}.")
im = im * 255.0
# Compute the histogram of the image channel.
@@ -961,8 +968,8 @@ def _scale_channel(im: Tensor) -> Tensor:
@perform_keep_shape_image
-def equalize(input: Tensor) -> Tensor:
- r"""Apply equalize on the input tensor.
+def equalize(input: torch.Tensor) -> torch.Tensor:
+ r"""Apply equalize on the input torch.tensor.
.. image:: _static/img/equalize.png
@@ -970,10 +977,10 @@ def equalize(input: Tensor) -> Tensor:
https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355
Args:
- input: image tensor to equalize with shape :math:`(*, C, H, W)`.
+ input: image torch.tensor to equalize with shape :math:`(*, C, H, W)`.
Returns:
- Equalized image tensor with shape :math:`(*, C, H, W)`.
+ Equalized image torch.tensor with shape :math:`(*, C, H, W)`.
Example:
>>> x = torch.rand(1, 2, 3, 3)
@@ -991,14 +998,14 @@ def equalize(input: Tensor) -> Tensor:
@perform_keep_shape_video
-def equalize3d(input: Tensor) -> Tensor:
- r"""Equalize the values for a 3D volumetric tensor.
+def equalize3d(input: torch.Tensor) -> torch.Tensor:
+ r"""Equalize the values for a 3D volumetric torch.tensor.
Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
Args:
- input: image tensor with shape :math:`(*, C, D, H, W)` to equalize.
+ input: image torch.tensor with shape :math:`(*, C, D, H, W)` to equalize.
Returns:
Equalized volume with shape :math:`(B, C, D, H, W)`.
@@ -1014,15 +1021,15 @@ def equalize3d(input: Tensor) -> Tensor:
return torch.stack(res)
-def invert(image: Tensor, max_val: Optional[Tensor] = None) -> Tensor:
- r"""Invert the values of an input image tensor by its maximum value.
+def invert(image: torch.Tensor, max_val: Optional[torch.Tensor] = None) -> torch.Tensor:
+ r"""Invert the values of an input image torch.tensor by its maximum value.
.. image:: _static/img/invert.png
Args:
- image: The input tensor to invert with an arbitatry shape.
- max_val: The expected maximum value in the input tensor. The shape has to
- according to the input tensor shape, or at least has to work with broadcasting.
+ image: The input torch.tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input torch.tensor. The shape has to
+ according to the input torch.tensor shape, or at least has to work with broadcasting.
Example:
>>> img = torch.rand(1, 2, 4, 4)
@@ -1038,20 +1045,20 @@ def invert(image: Tensor, max_val: Optional[Tensor] = None) -> Tensor:
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(image, Tensor):
- raise AssertionError(f"Input is not a Tensor. Got: {type(input)}")
+ if not isinstance(image, torch.Tensor):
+ raise AssertionError(f"Input is not a torch.Tensor. Got: {type(input)}")
if max_val is None:
- _max_val = tensor([1.0])
+ _max_val = torch.tensor([1.0])
else:
_max_val = max_val
- if not isinstance(_max_val, Tensor):
- raise AssertionError(f"max_val is not a Tensor. Got: {type(_max_val)}")
+ if not isinstance(_max_val, torch.Tensor):
+ raise AssertionError(f"max_val is not a torch.Tensor. Got: {type(_max_val)}")
return _max_val.to(image) - image
-class AdjustSaturation(Module):
+class AdjustSaturation(nn.Module):
r"""Adjust color saturation of an image.
The input image is expected to be an RGB image in the range of [0, 1].
@@ -1062,7 +1069,7 @@ class AdjustSaturation(Module):
saturation_mode: The mode to adjust saturation.
Shape:
- - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ - Input: Image/torch.Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
- Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
@@ -1091,15 +1098,15 @@ class AdjustSaturation(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def __init__(self, saturation_factor: Union[float, Tensor]) -> None:
+ def __init__(self, saturation_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.saturation_factor: Union[float, Tensor] = saturation_factor
+ self.saturation_factor: Union[float, torch.Tensor] = saturation_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_saturation(input, self.saturation_factor)
-class AdjustSaturationWithGraySubtraction(Module):
+class AdjustSaturationWithGraySubtraction(nn.Module):
r"""Adjust color saturation of an image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -1113,7 +1120,7 @@ class AdjustSaturationWithGraySubtraction(Module):
saturation_mode: The mode to adjust saturation.
Shape:
- - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ - Input: Image/torch.Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
- Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
@@ -1142,15 +1149,15 @@ class AdjustSaturationWithGraySubtraction(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def __init__(self, saturation_factor: Union[float, Tensor]) -> None:
+ def __init__(self, saturation_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.saturation_factor: Union[float, Tensor] = saturation_factor
+ self.saturation_factor: Union[float, torch.Tensor] = saturation_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_saturation_with_gray_subtraction(input, self.saturation_factor)
-class AdjustHue(Module):
+class AdjustHue(nn.Module):
r"""Adjust hue of an image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -1165,7 +1172,7 @@ class AdjustHue(Module):
image with complementary colors while 0 gives the original image.
Shape:
- - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ - Input: Image/torch.Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
- Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
@@ -1193,15 +1200,15 @@ class AdjustHue(Module):
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
- def __init__(self, hue_factor: Union[float, Tensor]) -> None:
+ def __init__(self, hue_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.hue_factor: Union[float, Tensor] = hue_factor
+ self.hue_factor: Union[float, torch.Tensor] = hue_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_hue(input, self.hue_factor)
-class AdjustGamma(Module):
+class AdjustGamma(nn.Module):
r"""Perform gamma correction on an image.
The input image is expected to be in the range of [0, 1].
@@ -1231,16 +1238,16 @@ class AdjustGamma(Module):
"""
- def __init__(self, gamma: Union[float, Tensor], gain: Union[float, Tensor] = 1.0) -> None:
+ def __init__(self, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.0) -> None:
super().__init__()
- self.gamma: Union[float, Tensor] = gamma
- self.gain: Union[float, Tensor] = gain
+ self.gamma: Union[float, torch.Tensor] = gamma
+ self.gain: Union[float, torch.Tensor] = gain
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_gamma(input, self.gamma, self.gain)
-class AdjustContrast(Module):
+class AdjustContrast(nn.Module):
r"""Adjust Contrast of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
@@ -1270,15 +1277,15 @@ class AdjustContrast(Module):
"""
- def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
+ def __init__(self, contrast_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.contrast_factor: Union[float, Tensor] = contrast_factor
+ self.contrast_factor: Union[float, torch.Tensor] = contrast_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_contrast(input, self.contrast_factor)
-class AdjustContrastWithMeanSubtraction(Module):
+class AdjustContrastWithMeanSubtraction(nn.Module):
r"""Adjust Contrast of an image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -1309,15 +1316,15 @@ class AdjustContrastWithMeanSubtraction(Module):
"""
- def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
+ def __init__(self, contrast_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.contrast_factor: Union[float, Tensor] = contrast_factor
+ self.contrast_factor: Union[float, torch.Tensor] = contrast_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_contrast_with_mean_subtraction(input, self.contrast_factor)
-class AdjustBrightness(Module):
+class AdjustBrightness(nn.Module):
r"""Adjust Brightness of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
@@ -1346,16 +1353,16 @@ class AdjustBrightness(Module):
"""
- def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
+ def __init__(self, brightness_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.brightness_factor: Union[float, Tensor] = brightness_factor
+ self.brightness_factor: Union[float, torch.Tensor] = brightness_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_brightness(input, self.brightness_factor)
-class AdjustSigmoid(Module):
- r"""Adjust the contrast of an image tensor or performs sigmoid correction on the input image tensor.
+class AdjustSigmoid(nn.Module):
+ r"""Adjust the contrast of an image torch.tensor or performs sigmoid correction on the input image torch.tensor.
The input image is expected to be in the range of [0, 1].
@@ -1383,12 +1390,12 @@ class AdjustSigmoid(Module):
self.gain: float = gain
self.inv: bool = inv
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return adjust_sigmoid(image, cutoff=self.cutoff, gain=self.gain, inv=self.inv)
-class AdjustLog(Module):
- """Adjust log correction on the input image tensor.
+class AdjustLog(nn.Module):
+ """Adjust log correction on the input image torch.tensor.
The input image is expected to be in the range of [0, 1].
@@ -1415,11 +1422,11 @@ class AdjustLog(Module):
self.inv: bool = inv
self.clip_output: bool = clip_output
- def forward(self, image: Tensor) -> Tensor:
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
return adjust_log(image, gain=self.gain, inv=self.inv, clip_output=self.clip_output)
-class AdjustBrightnessAccumulative(Module):
+class AdjustBrightnessAccumulative(nn.Module):
r"""Adjust Brightness of an image accumulatively.
This implementation aligns PIL. Hence, the output is close to TorchVision.
@@ -1448,21 +1455,21 @@ class AdjustBrightnessAccumulative(Module):
"""
- def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
+ def __init__(self, brightness_factor: Union[float, torch.Tensor]) -> None:
super().__init__()
- self.brightness_factor: Union[float, Tensor] = brightness_factor
+ self.brightness_factor: Union[float, torch.Tensor] = brightness_factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_brightness_accumulative(input, self.brightness_factor)
-class Invert(Module):
- r"""Invert the values of an input tensor by its maximum value.
+class Invert(nn.Module):
+ r"""Invert the values of an input torch.tensor by its maximum value.
Args:
- input: The input tensor to invert with an arbitatry shape.
- max_val: The expected maximum value in the input tensor. The shape has to
- according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.
+ input: The input torch.tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input torch.tensor. The shape has to
+ according to the input torch.tensor shape, or at least has to work with broadcasting. Default: 1.0.
Example:
>>> img = torch.rand(1, 2, 4, 4)
@@ -1479,14 +1486,14 @@ class Invert(Module):
"""
- def __init__(self, max_val: Optional[Tensor] = None) -> None:
+ def __init__(self, max_val: Optional[torch.Tensor] = None) -> None:
super().__init__()
if max_val is None:
max_val = torch.tensor(1.0)
- if not isinstance(max_val, Parameter):
+ if not isinstance(max_val, nn.Parameter):
self.register_buffer("max_val", max_val)
else:
self.max_val = max_val
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return invert(input, self.max_val)
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index bbbb5a869..b6294ccac 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -17,14 +17,19 @@
from typing import Union
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
def add_weighted(
- src1: Tensor, alpha: Union[float, Tensor], src2: Tensor, beta: Union[float, Tensor], gamma: Union[float, Tensor]
-) -> Tensor:
+ src1: torch.Tensor,
+ alpha: Union[float, torch.Tensor],
+ src2: torch.Tensor,
+ beta: Union[float, torch.Tensor],
+ gamma: Union[float, torch.Tensor],
+) -> torch.Tensor:
r"""Calculate the weighted sum of two Tensors.
.. image:: _static/img/add_weighted.png
@@ -35,14 +40,14 @@ def add_weighted(
out = src1 * alpha + src2 * beta + gamma
Args:
- src1: Tensor with an arbitrary shape, equal to shape of src2.
- alpha: weight of the src1 elements as Union[float, Tensor].
- src2: Tensor with an arbitrary shape, equal to shape of src1.
- beta: weight of the src2 elements as Union[float, Tensor].
- gamma: scalar added to each sum as Union[float, Tensor].
+ src1: torch.Tensor with an arbitrary shape, equal to shape of src2.
+ alpha: weight of the src1 elements as Union[float, torch.Tensor].
+ src2: torch.Tensor with an arbitrary shape, equal to shape of src1.
+ beta: weight of the src2 elements as Union[float, torch.Tensor].
+ gamma: scalar added to each sum as Union[float, torch.Tensor].
Returns:
- Weighted Tensor with shape equal to src1 and src2 shapes.
+ Weighted torch.Tensor with shape equal to src1 and src2 shapes.
Example:
>>> input1 = torch.rand(1, 1, 5, 5)
@@ -52,32 +57,32 @@ def add_weighted(
torch.Size([1, 1, 5, 5])
Notes:
- Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
+ torch.Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
"""
KORNIA_CHECK_IS_TENSOR(src1)
KORNIA_CHECK_IS_TENSOR(src2)
KORNIA_CHECK(src1.shape == src2.shape, f"src1 and src2 have different shapes. Got {src1.shape} and {src2.shape}")
- if isinstance(alpha, Tensor):
+ if isinstance(alpha, torch.Tensor):
KORNIA_CHECK(src1.shape == alpha.shape, "alpha has a different shape than src.")
else:
- alpha = tensor(alpha, dtype=src1.dtype, device=src1.device)
+ alpha = torch.tensor(alpha, dtype=src1.dtype, device=src1.device)
- if isinstance(beta, Tensor):
+ if isinstance(beta, torch.Tensor):
KORNIA_CHECK(src1.shape == beta.shape, "beta has a different shape than src.")
else:
- beta = tensor(beta, dtype=src1.dtype, device=src1.device)
+ beta = torch.tensor(beta, dtype=src1.dtype, device=src1.device)
- if isinstance(gamma, Tensor):
+ if isinstance(gamma, torch.Tensor):
KORNIA_CHECK(src1.shape == gamma.shape, "gamma has a different shape than src.")
else:
- gamma = tensor(gamma, dtype=src1.dtype, device=src1.device)
+ gamma = torch.tensor(gamma, dtype=src1.dtype, device=src1.device)
return src1 * alpha + src2 * beta + gamma
-class AddWeighted(Module):
+class AddWeighted(nn.Module):
r"""Calculate the weighted sum of two Tensors.
The function calculates the weighted sum of two Tensors as follows:
@@ -86,14 +91,14 @@ class AddWeighted(Module):
out = src1 * alpha + src2 * beta + gamma
Args:
- alpha: weight of the src1 elements as Union[float, Tensor].
- beta: weight of the src2 elements as Union[float, Tensor].
- gamma: scalar added to each sum as Union[float, Tensor].
+ alpha: weight of the src1 elements as Union[float, torch.Tensor].
+ beta: weight of the src2 elements as Union[float, torch.Tensor].
+ gamma: scalar added to each sum as Union[float, torch.Tensor].
Shape:
- - Input1: Tensor with an arbitrary shape, equal to shape of Input2.
- - Input2: Tensor with an arbitrary shape, equal to shape of Input1.
- - Output: Weighted tensor with shape equal to src1 and src2 shapes.
+ - Input1: torch.Tensor with an arbitrary shape, equal to shape of Input2.
+ - Input2: torch.Tensor with an arbitrary shape, equal to shape of Input1.
+ - Output: Weighted torch.tensor with shape equal to src1 and src2 shapes.
Example:
>>> input1 = torch.rand(1, 1, 5, 5)
@@ -103,15 +108,17 @@ class AddWeighted(Module):
torch.Size([1, 1, 5, 5])
Notes:
- Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
+ torch.Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
"""
- def __init__(self, alpha: Union[float, Tensor], beta: Union[float, Tensor], gamma: Union[float, Tensor]) -> None:
+ def __init__(
+ self, alpha: Union[float, torch.Tensor], beta: Union[float, torch.Tensor], gamma: Union[float, torch.Tensor]
+ ) -> None:
super().__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
- def forward(self, src1: Tensor, src2: Tensor) -> Tensor:
+ def forward(self, src1: torch.Tensor, src2: torch.Tensor) -> torch.Tensor:
return add_weighted(src1, self.alpha, src2, self.beta, self.gamma)
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 1fda149e0..281e5d2fd 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -19,10 +19,10 @@ from typing import Optional, Tuple
import torch
-from kornia.core import Tensor
-
-def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1e-10) -> Tuple[Tensor, Tensor]:
+def marginal_pdf(
+ values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Calculate the marginal probability distribution function of the input based on the number of histogram bins.
Args:
@@ -32,19 +32,19 @@ def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1
epsilon: scalar, for numerical stability.
Returns:
- Tuple[Tensor, Tensor]:
- - Tensor: shape [BxN].
- - Tensor: shape [BxNxNUM_BINS].
+ Tuple[torch.Tensor, torch.Tensor]:
+ - torch.Tensor: shape [BxN].
+ - torch.Tensor: shape [BxNxNUM_BINS].
"""
- if not isinstance(values, Tensor):
- raise TypeError(f"Input values type is not a Tensor. Got {type(values)}")
+ if not isinstance(values, torch.Tensor):
+ raise TypeError(f"Input values type is not a torch.Tensor. Got {type(values)}")
- if not isinstance(bins, Tensor):
- raise TypeError(f"Input bins type is not a Tensor. Got {type(bins)}")
+ if not isinstance(bins, torch.Tensor):
+ raise TypeError(f"Input bins type is not a torch.Tensor. Got {type(bins)}")
- if not isinstance(sigma, Tensor):
- raise TypeError(f"Input sigma type is not a Tensor. Got {type(sigma)}")
+ if not isinstance(sigma, torch.Tensor):
+ raise TypeError(f"Input sigma type is not a torch.Tensor. Got {type(sigma)}")
if not values.dim() == 3:
raise ValueError(f"Input values must be a of the shape BxNx1. Got {values.shape}")
@@ -65,7 +65,7 @@ def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1
return pdf, kernel_values
-def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1e-10) -> Tensor:
+def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
"""Calculate the joint probability distribution function of the input tensors based on the number of histogram bins.
Args:
@@ -77,11 +77,11 @@ def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1
shape [BxNUM_BINSxNUM_BINS].
"""
- if not isinstance(kernel_values1, Tensor):
- raise TypeError(f"Input kernel_values1 type is not a Tensor. Got {type(kernel_values1)}")
+ if not isinstance(kernel_values1, torch.Tensor):
+ raise TypeError(f"Input kernel_values1 type is not a torch.Tensor. Got {type(kernel_values1)}")
- if not isinstance(kernel_values2, Tensor):
- raise TypeError(f"Input kernel_values2 type is not a Tensor. Got {type(kernel_values2)}")
+ if not isinstance(kernel_values2, torch.Tensor):
+ raise TypeError(f"Input kernel_values2 type is not a torch.Tensor. Got {type(kernel_values2)}")
if not kernel_values1.dim() == 3:
raise ValueError(f"Input kernel_values1 must be a of the shape BxN. Got {kernel_values1.shape}")
@@ -102,13 +102,13 @@ def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1
return pdf
-def histogram(x: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor:
- """Estimate the histogram of the input tensor.
+def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
+ """Estimate the histogram of the input torch.tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x: Input tensor to compute the histogram with shape :math:`(B, D)`.
+ x: Input torch.tensor to compute the histogram with shape :math:`(B, D)`.
bins: The number of bins to use the histogram :math:`(N_{bins})`.
bandwidth: Gaussian smoothing factor with shape shape [1].
epsilon: A scalar, for numerical stability.
@@ -129,14 +129,16 @@ def histogram(x: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10
return pdf
-def histogram2d(x1: Tensor, x2: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor:
- """Estimate the 2d histogram of the input tensor.
+def histogram2d(
+ x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10
+) -> torch.Tensor:
+ """Estimate the 2d histogram of the input torch.tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x1: Input tensor to compute the histogram with shape :math:`(B, D1)`.
- x2: Input tensor to compute the histogram with shape :math:`(B, D2)`.
+ x1: Input torch.tensor to compute the histogram with shape :math:`(B, D1)`.
+ x2: Input torch.tensor to compute the histogram with shape :math:`(B, D2)`.
bins: The number of bins to use the histogram :math:`(N_{bins})`.
bandwidth: Gaussian smoothing factor with shape shape [1].
epsilon: A scalar, for numerical stability. Default: 1e-10.
@@ -162,22 +164,22 @@ def histogram2d(x1: Tensor, x2: Tensor, bins: Tensor, bandwidth: Tensor, epsilon
def image_histogram2d(
- image: Tensor,
+ image: torch.Tensor,
min: float = 0.0,
max: float = 255.0,
n_bins: int = 256,
bandwidth: Optional[float] = None,
- centers: Optional[Tensor] = None,
+ centers: Optional[torch.Tensor] = None,
return_pdf: bool = False,
kernel: str = "triangular",
eps: float = 1e-10,
-) -> Tuple[Tensor, Tensor]:
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Estimate the histogram of the input image(s).
The calculation uses triangular kernel density estimation.
Args:
- image: Input tensor to compute the histogram with shape
+ image: Input torch.tensor to compute the histogram with shape
:math:`(H, W)`, :math:`(C, H, W)` or :math:`(B, C, H, W)`.
min: Lower end of the interval (inclusive).
max: Upper end of the interval (inclusive). Ignored when
@@ -199,18 +201,18 @@ def image_histogram2d(
Computed histogram of shape :math:`(bins)`, :math:`(C, bins)`,
:math:`(B, C, bins)`.
Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`,
- :math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shape
+ :math:`(B, C, bins)`, if return_pdf is ``True``. torch.Tensor of torch.zeros with shape
of the histogram otherwise.
"""
- if image is not None and not isinstance(image, Tensor):
- raise TypeError(f"Input image type is not a Tensor. Got {type(image)}.")
+ if image is not None and not isinstance(image, torch.Tensor):
+ raise TypeError(f"Input image type is not a torch.Tensor. Got {type(image)}.")
- if centers is not None and not isinstance(centers, Tensor):
- raise TypeError(f"Bins' centers type is not a Tensor. Got {type(centers)}.")
+ if centers is not None and not isinstance(centers, torch.Tensor):
+ raise TypeError(f"Bins' centers type is not a torch.Tensor. Got {type(centers)}.")
if centers is not None and len(centers.shape) > 0 and centers.dim() != 1:
- raise ValueError(f"Bins' centers must be a Tensor of the shape (n_bins,). Got {centers.shape}.")
+ raise ValueError(f"Bins' centers must be a torch.Tensor of the shape (n_bins,). Got {centers.shape}.")
if not isinstance(min, float):
raise TypeError(f"Type of lower end of the range is not a float. Got {type(min)}.")
diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.py
index 272711445..07d4444ae 100644
--- a/kornia/enhance/integral.py
+++ b/kornia/enhance/integral.py
@@ -17,25 +17,26 @@
from typing import Optional, Tuple
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Tensor:
- """Calculate integral of the input tensor.
+def integral_tensor(input: torch.Tensor, dim: Optional[Tuple[int, ...]] = None) -> torch.Tensor:
+ """Calculate integral of the input torch.tensor.
The algorithm computes the integral image by summing over the specified dimensions.
In case dim is specified, the contained dimensions must be unique and sorted in ascending order
- and not exceed the number of dimensions of the input tensor.
+ and not exceed the number of dimensions of the input torch.tensor.
Args:
- input: the input tensor with shape :math:`(*, D)`. Where D is the number of dimensions.
+ input: the input torch.tensor with shape :math:`(*, D)`. Where D is the number of dimensions.
dim: the dimension to be summed.
Returns:
- Integral tensor for the input tensor with shape :math:`(*, D)`.
+ Integral torch.tensor for the input torch.tensor with shape :math:`(*, D)`.
Examples:
>>> input = torch.ones(3, 5)
@@ -60,16 +61,16 @@ def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Ten
return output
-def integral_image(image: Tensor) -> Tensor:
- r"""Calculate integral of the input image tensor.
+def integral_image(image: torch.Tensor) -> torch.Tensor:
+ r"""Calculate integral of the input image torch.tensor.
This particular version sums over the last two dimensions.
Args:
- image: the input image tensor with shape :math:`(*, H, W)`.
+ image: the input image torch.tensor with shape :math:`(*, H, W)`.
Returns:
- Integral tensor for the input image tensor with shape :math:`(*, H, W)`.
+ Integral torch.tensor for the input image torch.tensor with shape :math:`(*, H, W)`.
Examples:
>>> input = torch.ones(1, 5, 5)
@@ -87,14 +88,14 @@ def integral_image(image: Tensor) -> Tensor:
return integral_tensor(image, (-2, -1))
-class IntegralTensor(Module):
- r"""Calculates integral of the input tensor.
+class IntegralTensor(nn.Module):
+ r"""Calculates integral of the input torch.tensor.
Args:
- image: the input tensor with shape :math:`(B,C,H,W)`.
+ image: the input torch.tensor with shape :math:`(B,C,H,W)`.
Returns:
- Integral tensor for the input tensor with shape :math:`(B,C,H,W)`.
+ Integral torch.tensor for the input torch.tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -115,20 +116,20 @@ class IntegralTensor(Module):
super().__init__()
self.dim = dim
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return integral_tensor(input, self.dim)
-class IntegralImage(Module):
- """Calculates integral of the input image tensor.
+class IntegralImage(nn.Module):
+ """Calculates integral of the input image torch.tensor.
This particular version sums over the last two dimensions.
Args:
- image: the input image tensor with shape :math:`(B,C,H,W)`.
+ image: the input image torch.tensor with shape :math:`(B,C,H,W)`.
Returns:
- Integral tensor for the input image tensor with shape :math:`(B,C,H,W)`.
+ Integral torch.tensor for the input image torch.tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -146,5 +147,5 @@ class IntegralImage(Module):
"""
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return integral_image(input)
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 31cc2b7b8..3ea1ebf61 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -18,14 +18,14 @@
from __future__ import annotations
import math
+from typing import Union
import torch
import torch.nn.functional as F
+from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
from kornia.constants import pi
-from kornia.core import Device, Dtype, Parameter, Tensor
-from kornia.core import ImageModule as Module
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_TENSOR,
@@ -39,12 +39,14 @@ from kornia.utils.misc import (
differentiable_polynomial_rounding,
)
-_DCT8_CACHE: dict[tuple[Dtype, Device], tuple[Tensor, Tensor]] = {}
+_DCT8_CACHE: dict[
+ tuple[Union[torch.dtype, None], Union[str, torch.device, None]], tuple[torch.Tensor, torch.Tensor]
+] = {}
__all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"]
-def _get_default_qt_y(device: Device, dtype: Dtype) -> Tensor:
+def _get_default_qt_y(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:
"""Generate default Quantization table of Y channel."""
return torch.tensor(
[
@@ -62,7 +64,7 @@ def _get_default_qt_y(device: Device, dtype: Dtype) -> Tensor:
)
-def _get_default_qt_c(device: Device, dtype: Dtype) -> Tensor:
+def _get_default_qt_c(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:
"""Generate default Quantization table of C channels."""
return torch.tensor(
[
@@ -80,69 +82,69 @@ def _get_default_qt_c(device: Device, dtype: Dtype) -> Tensor:
)
-def _patchify_8x8(input: Tensor) -> Tensor:
+def _patchify_8x8(input: torch.Tensor) -> torch.Tensor:
"""Extract non-overlapping 8 x 8 patches from the given input image.
Args:
- input (Tensor): Input image of the shape :math:`(B, H, W)`.
+ input (torch.Tensor): Input image of the shape :math:`(B, H, W)`.
Returns:
- output (Tensor): Image patchify of the shape :math:`(B, N, 8, 8)`.
+ output (torch.Tensor): Image patchify of the shape :math:`(B, N, 8, 8)`.
"""
# Get input shape
B, H, W = input.shape
# Patchify to shape [B, N, H // 8, W // 8]
- output: Tensor = input.view(B, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4).reshape(B, -1, 8, 8)
+ output: torch.Tensor = input.view(B, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4).reshape(B, -1, 8, 8)
return output
-def _unpatchify_8x8(input: Tensor, H: int, W: int) -> Tensor:
+def _unpatchify_8x8(input: torch.Tensor, H: int, W: int) -> torch.Tensor:
"""Reverse non-overlapping 8 x 8 patching.
Args:
- input (Tensor): Input image of the shape :math:`(B, N, 8, 8)`.
- H: height of resulting tensor.
- W: width of resulting tensor.
+ input (torch.Tensor): Input image of the shape :math:`(B, N, 8, 8)`.
+ H: height of resulting torch.tensor.
+ W: width of resulting torch.tensor.
Returns:
- output (Tensor): Image patchify of the shape :math:`(B, H, W)`.
+ output (torch.Tensor): Image patchify of the shape :math:`(B, H, W)`.
"""
# Get input shape
B, _N = input.shape[:2]
# Unpatch to [B, H, W]
- output: Tensor = input.view(B, H // 8, W // 8, 8, 8).permute(0, 1, 3, 2, 4).reshape(B, H, W)
+ output: torch.Tensor = input.view(B, H // 8, W // 8, 8, 8).permute(0, 1, 3, 2, 4).reshape(B, H, W)
return output
-def _dct_8x8(input: Tensor) -> Tensor:
+def _dct_8x8(input: torch.Tensor) -> torch.Tensor:
"""Perform an 8 x 8 discrete cosine transform.
Args:
- input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`.
+ input (torch.Tensor): Patched input torch.tensor of the shape :math:`(B, N, 8, 8)`.
Returns:
- output (Tensor): DCT output tensor of the shape :math:`(B, N, 8, 8)`.
+ output (torch.Tensor): DCT output torch.tensor of the shape :math:`(B, N, 8, 8)`.
"""
# Get dtype and device
- dtype: Dtype = input.dtype
- device: Device = input.device
+ dtype: Union[torch.dtype, None] = input.dtype
+ device: Union[str, torch.device, None] = input.device
dct_tensor, dct_scale = _get_dct8_basis_scale(dtype, device)
# Apply DCT
- output: Tensor = dct_scale[None, None] * torch.tensordot(input - 128.0, dct_tensor)
+ output: torch.Tensor = dct_scale[None, None] * torch.tensordot(input - 128.0, dct_tensor)
return output
-def _idct_8x8(input: Tensor) -> Tensor:
+def _idct_8x8(input: torch.Tensor) -> torch.Tensor:
"""Perform an 8 x 8 inverse discrete cosine transform.
Args:
- input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`.
+ input (torch.Tensor): Patched input torch.tensor of the shape :math:`(B, N, 8, 8)`.
Returns:
- output (Tensor): IDCT output tensor of the shape :math:`(B, N, 8, 8)`.
+ output (torch.Tensor): IDCT output torch.tensor of the shape :math:`(B, N, 8, 8)`.
"""
dtype = input.dtype
@@ -152,7 +154,7 @@ def _idct_8x8(input: Tensor) -> Tensor:
spatial_idx = idx.unsqueeze(0)
freq_idx = idx.unsqueeze(1)
- basis = ((2.0 * spatial_idx + 1.0) * freq_idx * pi / 16.0).cos()
+ basis = torch.cos((2.0 * spatial_idx + 1.0) * freq_idx * pi / 16.0)
alpha = torch.ones(8, dtype=dtype, device=device)
alpha[0] = 1.0 / (2**0.5)
dct_scale = torch.outer(alpha, alpha)
@@ -166,19 +168,19 @@ def _idct_8x8(input: Tensor) -> Tensor:
def _jpeg_quality_to_scale(
- compression_strength: Tensor,
-) -> Tensor:
+ compression_strength: torch.Tensor,
+) -> torch.Tensor:
"""Convert a given JPEG quality to the scaling factor.
Args:
- compression_strength (Tensor): Compression strength ranging from 0 to 100. Any shape is supported.
+ compression_strength (torch.Tensor): Compression strength ranging from 0 to 100. Any shape is supported.
Returns:
- scale (Tensor): Scaling factor to be applied to quantization matrix. Same shape as input.
+ scale (torch.Tensor): Scaling factor to be applied to quantization matrix. Same shape as input.
"""
# Get scale
- scale: Tensor = differentiable_polynomial_floor(
+ scale: torch.Tensor = differentiable_polynomial_floor(
torch.where(
compression_strength < 50,
5000.0 / compression_strength,
@@ -189,78 +191,78 @@ def _jpeg_quality_to_scale(
def _quantize(
- input: Tensor,
- jpeg_quality: Tensor,
- quantization_table: Tensor,
-) -> Tensor:
+ input: torch.Tensor,
+ jpeg_quality: torch.Tensor,
+ quantization_table: torch.Tensor,
+) -> torch.Tensor:
"""Perform quantization.
Args:
- input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`.
- jpeg_quality (Tensor): Compression strength to be applied, shape is :math:`(B)`.
- quantization_table (Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`.
+ input (torch.Tensor): Input torch.tensor of the shape :math:`(B, N, 8, 8)`.
+ jpeg_quality (torch.Tensor): Compression strength to be applied, shape is :math:`(B)`.
+ quantization_table (torch.Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`.
Returns:
- output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`.
+ output (torch.Tensor): Quantized output torch.tensor of the shape :math:`(B, N, 8, 8)`.
"""
# Scale quantization table
- quantization_table_scaled: Tensor = (
+ quantization_table_scaled: torch.Tensor = (
quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None]
)
# Perform scaling
quantization_table = differentiable_polynomial_floor(
differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
)
- output: Tensor = input / quantization_table
+ output: torch.Tensor = input / quantization_table
# Perform rounding
output = differentiable_polynomial_rounding(output)
return output
def _dequantize(
- input: Tensor,
- jpeg_quality: Tensor,
- quantization_table: Tensor,
-) -> Tensor:
+ input: torch.Tensor,
+ jpeg_quality: torch.Tensor,
+ quantization_table: torch.Tensor,
+) -> torch.Tensor:
"""Perform dequantization.
Args:
- input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`.
- jpeg_quality (Tensor): Compression strength to be applied, shape is :math:`(B)`.
- quantization_table (Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`.
+ input (torch.Tensor): Input torch.tensor of the shape :math:`(B, N, 8, 8)`.
+ jpeg_quality (torch.Tensor): Compression strength to be applied, shape is :math:`(B)`.
+ quantization_table (torch.Tensor): Quantization table of the shape :math:`(1, 8, 8)` or :math:`(B, 8, 8)`.
Returns:
- output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`.
+ output (torch.Tensor): Quantized output torch.tensor of the shape :math:`(B, N, 8, 8)`.
"""
# Scale quantization table
- quantization_table_scaled: Tensor = (
+ quantization_table_scaled: torch.Tensor = (
quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None]
)
# Perform scaling
- output: Tensor = input * differentiable_polynomial_floor(
+ output: torch.Tensor = input * differentiable_polynomial_floor(
differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
)
return output
-def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]:
+def _chroma_subsampling(input_ycbcr: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Implement chroma subsampling.
Args:
- input_ycbcr (Tensor): YCbCr input tensor of the shape :math:`(B, 3, H, W)`.
+ input_ycbcr (torch.Tensor): YCbCr input torch.tensor of the shape :math:`(B, 3, H, W)`.
Returns:
- output_y (Tensor): Y component (not-subsampled), shape is :math:`(B, H, W)`.
- output_cb (Tensor): Cb component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
- output_cr (Tensor): Cr component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
+ output_y (torch.Tensor): Y component (not-subsampled), shape is :math:`(B, H, W)`.
+ output_cb (torch.Tensor): Cb component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
+ output_cr (torch.Tensor): Cr component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
"""
# Get components
- output_y: Tensor = input_ycbcr[:, 0]
- output_cb: Tensor = input_ycbcr[:, 1]
- output_cr: Tensor = input_ycbcr[:, 2]
+ output_y: torch.Tensor = input_ycbcr[:, 0]
+ output_cb: torch.Tensor = input_ycbcr[:, 1]
+ output_cr: torch.Tensor = input_ycbcr[:, 2]
# Perform average pooling of Cb and Cr channels
output_cb = rescale(
output_cb[:, None],
@@ -279,18 +281,18 @@ def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]:
return output_y, output_cb[:, 0], output_cr[:, 0]
-def _chroma_upsampling(input_c: Tensor) -> Tensor:
+def _chroma_upsampling(input_c: torch.Tensor) -> torch.Tensor:
"""Perform chroma upsampling.
Args:
- input_c (Tensor): Cb or Cr component to be upsampled of the shape :math:`(B, H, W)`.
+ input_c (torch.Tensor): Cb or Cr component to be upsampled of the shape :math:`(B, H, W)`.
Returns:
- output_c (Tensor): Upsampled C(b or r) component of the shape :math:`(B, H * 2, W * 2)`.
+ output_c (torch.Tensor): Upsampled C(b or r) component of the shape :math:`(B, H * 2, W * 2)`.
"""
# Upsample component
- output_c: Tensor = rescale(
+ output_c: torch.Tensor = rescale(
input_c[:, None],
factor=2.0,
interpolation="bilinear",
@@ -301,27 +303,27 @@ def _chroma_upsampling(input_c: Tensor) -> Tensor:
def _jpeg_encode(
- image_rgb: Tensor,
- jpeg_quality: Tensor,
- quantization_table_y: Tensor,
- quantization_table_c: Tensor,
-) -> tuple[Tensor, Tensor, Tensor]:
+ image_rgb: torch.Tensor,
+ jpeg_quality: torch.Tensor,
+ quantization_table_y: torch.Tensor,
+ quantization_table_c: torch.Tensor,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Perform JPEG encoding.
Args:
- image_rgb (Tensor): RGB input images of the shape :math:`(B, 3, H, W)`.
- jpeg_quality (Tensor): Compression strength of the shape :math:`(B)`.
- quantization_table_y (Tensor): Quantization table for Y channel.
- quantization_table_c (Tensor): Quantization table for C channels.
+ image_rgb (torch.Tensor): RGB input images of the shape :math:`(B, 3, H, W)`.
+ jpeg_quality (torch.Tensor): Compression strength of the shape :math:`(B)`.
+ quantization_table_y (torch.Tensor): Quantization table for Y channel.
+ quantization_table_c (torch.Tensor): Quantization table for C channels.
Returns:
- y_encoded (Tensor): Encoded Y component of the shape :math:`(B, N, 8, 8)`.
- cb_encoded (Tensor): Encoded Cb component of the shape :math:`(B, N, 8, 8)`.
- cr_encoded (Tensor): Encoded Cr component of the shape :math:`(B, N, 8, 8)`.
+ y_encoded (torch.Tensor): Encoded Y component of the shape :math:`(B, N, 8, 8)`.
+ cb_encoded (torch.Tensor): Encoded Cb component of the shape :math:`(B, N, 8, 8)`.
+ cr_encoded (torch.Tensor): Encoded Cr component of the shape :math:`(B, N, 8, 8)`.
"""
# Convert RGB image to YCbCr.
- image_ycbcr: Tensor = rgb_to_ycbcr(image_rgb)
+ image_ycbcr: torch.Tensor = rgb_to_ycbcr(image_rgb)
# Scale pixel-range to [0, 255]
image_ycbcr = 255.0 * image_ycbcr
# Perform chroma subsampling
@@ -334,7 +336,7 @@ def _jpeg_encode(
)
dct_y = _dct_8x8(input_y)
dct_cb_cr = _dct_8x8(torch.cat((input_cb, input_cr), dim=1))
- y_encoded: Tensor = _quantize(
+ y_encoded: torch.Tensor = _quantize(
dct_y,
jpeg_quality,
quantization_table_y,
@@ -348,29 +350,29 @@ def _jpeg_encode(
def _jpeg_decode(
- input_y: Tensor,
- input_cb: Tensor,
- input_cr: Tensor,
- jpeg_quality: Tensor,
+ input_y: torch.Tensor,
+ input_cb: torch.Tensor,
+ input_cr: torch.Tensor,
+ jpeg_quality: torch.Tensor,
H: int,
W: int,
- quantization_table_y: Tensor,
- quantization_table_c: Tensor,
-) -> Tensor:
+ quantization_table_y: torch.Tensor,
+ quantization_table_c: torch.Tensor,
+) -> torch.Tensor:
"""Perform JPEG decoding.
Args:
- input_y (Tensor): Compressed Y component of the shape :math:`(B, N, 8, 8)`.
- input_cb (Tensor): Compressed Cb component of the shape :math:`(B, N, 8, 8)`.
- input_cr (Tensor): Compressed Cr component of the shape :math:`(B, N, 8, 8)`.
- jpeg_quality (Tensor): Compression strength of the shape :math:`(B)`.
+ input_y (torch.Tensor): Compressed Y component of the shape :math:`(B, N, 8, 8)`.
+ input_cb (torch.Tensor): Compressed Cb component of the shape :math:`(B, N, 8, 8)`.
+ input_cr (torch.Tensor): Compressed Cr component of the shape :math:`(B, N, 8, 8)`.
+ jpeg_quality (torch.Tensor): Compression strength of the shape :math:`(B)`.
H (int): Original image height.
W (int): Original image width.
- quantization_table_y (Tensor): Quantization table for Y channel.
- quantization_table_c (Tensor): Quantization table for C channels.
+ quantization_table_y (torch.Tensor): Quantization table for Y channel.
+ quantization_table_c (torch.Tensor): Quantization table for C channels.
Returns:
- rgb_decoded (Tensor): Decompressed RGB image of the shape :math:`(B, 3, H, W)`.
+ rgb_decoded (torch.Tensor): Decompressed RGB image of the shape :math:`(B, 3, H, W)`.
"""
# Dequantize inputs
@@ -385,23 +387,23 @@ def _jpeg_decode(
quantization_table_c,
)
# Perform inverse DCT
- idct_y: Tensor = _idct_8x8(input_y)
+ idct_y: torch.Tensor = _idct_8x8(input_y)
idct_cb, idct_cr = _idct_8x8(input_cb_cr).chunk(2, dim=1)
# Reverse patching
- image_y: Tensor = _unpatchify_8x8(idct_y, H, W)
- image_cb: Tensor = _unpatchify_8x8(idct_cb, H // 2, W // 2)
- image_cr: Tensor = _unpatchify_8x8(idct_cr, H // 2, W // 2)
+ image_y: torch.Tensor = _unpatchify_8x8(idct_y, H, W)
+ image_cb: torch.Tensor = _unpatchify_8x8(idct_cb, H // 2, W // 2)
+ image_cr: torch.Tensor = _unpatchify_8x8(idct_cr, H // 2, W // 2)
# Perform chroma upsampling
image_cb = _chroma_upsampling(image_cb)
image_cr = _chroma_upsampling(image_cr)
# Back to [0, 1] pixel-range
- image_ycbcr: Tensor = torch.stack((image_y, image_cb, image_cr), dim=1) / 255.0
+ image_ycbcr: torch.Tensor = torch.stack((image_y, image_cb, image_cr), dim=1) / 255.0
# Convert back to RGB space.
- rgb_decoded: Tensor = ycbcr_to_rgb(image_ycbcr)
+ rgb_decoded: torch.Tensor = ycbcr_to_rgb(image_ycbcr)
return rgb_decoded
-def _perform_padding(image: Tensor) -> tuple[Tensor, int, int]:
+def _perform_padding(image: torch.Tensor) -> tuple[torch.Tensor, int, int]:
"""Pad a given image to be dividable by 16.
Args:
@@ -418,18 +420,18 @@ def _perform_padding(image: Tensor) -> tuple[Tensor, int, int]:
# Compute horizontal and vertical padding
h_pad: int = math.ceil(H / 16) * 16 - H
w_pad: int = math.ceil(W / 16) * 16 - W
- # Perform padding (we follow JPEG and pad only the bottom and right side of the image)
- image_padded: Tensor = F.pad(image, (0, w_pad, 0, h_pad), "replicate")
+ # Perform padding (we follow JPEG and F.pad only the bottom and right side of the image)
+ image_padded: torch.Tensor = F.pad(image, (0, w_pad, 0, h_pad), "replicate")
return image_padded, h_pad, w_pad
@perform_keep_shape_image
def jpeg_codec_differentiable(
- image_rgb: Tensor,
- jpeg_quality: Tensor,
- quantization_table_y: Tensor | None = None,
- quantization_table_c: Tensor | None = None,
-) -> Tensor:
+ image_rgb: torch.Tensor,
+ jpeg_quality: torch.Tensor,
+ quantization_table_y: torch.Tensor | None = None,
+ quantization_table_c: torch.Tensor | None = None,
+) -> torch.Tensor:
r"""Differentiable JPEG encoding-decoding module.
Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:
@@ -507,8 +509,8 @@ def jpeg_codec_differentiable(
KORNIA_CHECK_IS_TENSOR(image_rgb)
KORNIA_CHECK_IS_TENSOR(jpeg_quality)
# Get device and dtype
- dtype: Dtype = image_rgb.dtype
- device: Device = image_rgb.device
+ dtype: Union[torch.dtype, None] = image_rgb.dtype
+ device: Union[str, torch.device, None] = image_rgb.device
# Use default QT if QT is not given
quantization_table_y = _get_default_qt_y(device, dtype) if quantization_table_y is None else quantization_table_y
quantization_table_c = _get_default_qt_c(device, dtype) if quantization_table_c is None else quantization_table_c
@@ -554,7 +556,7 @@ def jpeg_codec_differentiable(
f"Batch dimensions do not match. "
f"Got {image_rgb.shape[0]} images and {jpeg_quality.shape[0]} JPEG qualities.",
)
- # keep jpeg_quality same device as input tensor
+ # keep jpeg_quality same device as input torch.tensor
jpeg_quality = jpeg_quality.to(device, dtype)
# Quantization tables to same device and dtype as input image
quantization_table_y = quantization_table_y.to(device, dtype)
@@ -566,7 +568,7 @@ def jpeg_codec_differentiable(
quantization_table_c=quantization_table_c,
quantization_table_y=quantization_table_y,
)
- image_rgb_jpeg: Tensor = _jpeg_decode(
+ image_rgb_jpeg: torch.Tensor = _jpeg_decode(
input_y=y_encoded,
input_cb=cb_encoded,
input_cr=cr_encoded,
@@ -583,12 +585,14 @@ def jpeg_codec_differentiable(
return image_rgb_jpeg
-def _get_dct8_basis_scale(dtype: Dtype, device: Device) -> tuple[Tensor, Tensor]:
+def _get_dct8_basis_scale(
+ dtype: Union[torch.dtype, None], device: Union[str, torch.device, None]
+) -> tuple[torch.Tensor, torch.Tensor]:
key = (dtype, device)
if key not in _DCT8_CACHE:
i = torch.arange(8, dtype=dtype, device=device)
freq = (2.0 * i + 1.0)[:, None] * i[None, :] * (pi / 16.0)
- basis_1d = freq.cos()
+ basis_1d = torch.cos(freq)
dct_tensor = basis_1d[:, None, :, None] * basis_1d[None, :, None, :]
alpha = torch.ones(8, dtype=dtype, device=device)
alpha[0] = 1.0 / (2**0.5)
@@ -597,7 +601,7 @@ def _get_dct8_basis_scale(dtype: Dtype, device: Device) -> tuple[Tensor, Tensor]
return _DCT8_CACHE[key]
-class JPEGCodecDifferentiable(Module):
+class JPEGCodecDifferentiable(nn.Module):
r"""Differentiable JPEG encoding-decoding module.
Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:
@@ -671,27 +675,27 @@ class JPEGCodecDifferentiable(Module):
def __init__(
self,
- quantization_table_y: Tensor | Parameter | None = None,
- quantization_table_c: Tensor | Parameter | None = None,
+ quantization_table_y: torch.Tensor | nn.Parameter | None = None,
+ quantization_table_c: torch.Tensor | nn.Parameter | None = None,
) -> None:
super().__init__()
# Get default quantization tables if needed
quantization_table_y = _get_default_qt_y(None, None) if quantization_table_y is None else quantization_table_y
quantization_table_c = _get_default_qt_c(None, None) if quantization_table_c is None else quantization_table_c
- if isinstance(quantization_table_y, Parameter):
+ if isinstance(quantization_table_y, nn.Parameter):
self.register_parameter("quantization_table_y", quantization_table_y)
else:
self.register_buffer("quantization_table_y", quantization_table_y)
- if isinstance(quantization_table_c, Parameter):
+ if isinstance(quantization_table_c, nn.Parameter):
self.register_parameter("quantization_table_c", quantization_table_c)
else:
self.register_buffer("quantization_table_c", quantization_table_c)
def forward(
self,
- image_rgb: Tensor,
- jpeg_quality: Tensor,
- ) -> Tensor:
+ image_rgb: torch.Tensor,
+ jpeg_quality: torch.Tensor,
+ ) -> torch.Tensor:
device = image_rgb.device
dtype = image_rgb.dtype
# Move quantization tables to the same device and dtype as input
@@ -699,7 +703,7 @@ class JPEGCodecDifferentiable(Module):
quantization_table_y = self.quantization_table_y.to(device, dtype)
quantization_table_c = self.quantization_table_c.to(device, dtype)
# Perform encoding-decoding
- image_rgb_jpeg: Tensor = jpeg_codec_differentiable(
+ image_rgb_jpeg: torch.Tensor = jpeg_codec_differentiable(
image_rgb,
jpeg_quality=jpeg_quality,
quantization_table_c=quantization_table_c,
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index bae4c8971..72457f4b0 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -15,21 +15,20 @@
# limitations under the License.
#
-"""Module containing functionals for intensity normalisation."""
+"""nn.Module containing functionals for intensity normalisation."""
from typing import List, Tuple, Union
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
from kornia.utils.image import perform_keep_shape_image
__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]
-class Normalize(Module):
- r"""Normalize a tensor image with mean and standard deviation.
+class Normalize(nn.Module):
+ r"""Normalize a torch.tensor image with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
@@ -41,8 +40,8 @@ class Normalize(Module):
std: Standard deviations for each channel.
Shape:
- - Input: Image tensor of size :math:`(*, C, ...)`.
- - Output: Normalised tensor with same size as input :math:`(*, C, ...)`.
+ - Input: Image torch.tensor of size :math:`(*, C, ...)`.
+ - Output: Normalised torch.tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -61,8 +60,8 @@ class Normalize(Module):
def __init__(
self,
- mean: Union[Tensor, Tuple[float], List[float], float],
- std: Union[Tensor, Tuple[float], List[float], float],
+ mean: Union[torch.Tensor, Tuple[float], List[float], float],
+ std: Union[torch.Tensor, Tuple[float], List[float], float],
) -> None:
super().__init__()
@@ -81,7 +80,7 @@ class Normalize(Module):
self.mean = mean
self.std = std
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return normalize(input, self.mean, self.std)
def __repr__(self) -> str:
@@ -89,8 +88,8 @@ class Normalize(Module):
return self.__class__.__name__ + repr
-def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:
- r"""Normalize an image/video tensor with mean and standard deviation.
+def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
+ r"""Normalize an image/video torch.tensor with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
@@ -98,12 +97,12 @@ def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- data: Image tensor of size :math:`(B, C, *)`.
+ data: Image torch.tensor of size :math:`(B, C, *)`.
mean: Mean for each channel.
std: Standard deviations for each channel.
Return:
- Normalised tensor with same size as input :math:`(B, C, *)`.
+ Normalised torch.tensor with same size as input :math:`(B, C, *)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -122,8 +121,8 @@ def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:
shape = data.shape
if torch.onnx.is_in_onnx_export():
- if not isinstance(mean, Tensor) or not isinstance(std, Tensor):
- raise ValueError("Only tensor is accepted when converting to ONNX.")
+ if not isinstance(mean, torch.Tensor) or not isinstance(std, torch.Tensor):
+ raise ValueError("Only torch.tensor is accepted when converting to ONNX.")
if mean.shape[0] != 1 or std.shape[0] != 1:
raise ValueError(
"Batch dimension must be one for broadcasting when converting to ONNX."
@@ -152,13 +151,13 @@ def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:
mean = mean[..., None]
std = std[..., None]
- out: Tensor = (data.view(shape[0], shape[1], -1) - mean) / std
+ out: torch.Tensor = (data.view(shape[0], shape[1], -1) - mean) / std
return out.view(shape)
-class Denormalize(Module):
- r"""Denormalize a tensor image with mean and standard deviation.
+class Denormalize(nn.Module):
+ r"""Denormalize a torch.tensor image with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
@@ -170,8 +169,8 @@ class Denormalize(Module):
std: Standard deviations for each channel.
Shape:
- - Input: Image tensor of size :math:`(*, C, ...)`.
- - Output: Denormalised tensor with same size as input :math:`(*, C, ...)`.
+ - Input: Image torch.tensor of size :math:`(*, C, ...)`.
+ - Output: Denormalised torch.tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -188,13 +187,13 @@ class Denormalize(Module):
"""
- def __init__(self, mean: Union[Tensor, float], std: Union[Tensor, float]) -> None:
+ def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
super().__init__()
self.mean = mean
self.std = std
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return denormalize(input, self.mean, self.std)
def __repr__(self) -> str:
@@ -202,8 +201,8 @@ class Denormalize(Module):
return self.__class__.__name__ + repr
-def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, float]) -> Tensor:
- r"""Denormalize an image/video tensor with mean and standard deviation.
+def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:
+ r"""Denormalize an image/video torch.tensor with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
@@ -211,12 +210,12 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- data: Image tensor of size :math:`(B, C, *)`.
+ data: Image torch.tensor of size :math:`(B, C, *)`.
mean: Mean for each channel.
std: Standard deviations for each channel.
Return:
- Denormalised tensor with same size as input :math:`(B, C, *)`.
+ Denormalised torch.tensor with same size as input :math:`(B, C, *)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -235,8 +234,8 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo
shape = data.shape
if torch.onnx.is_in_onnx_export():
- if not isinstance(mean, Tensor) or not isinstance(std, Tensor):
- raise ValueError("Only tensor is accepted when converting to ONNX.")
+ if not isinstance(mean, torch.Tensor) or not isinstance(std, torch.Tensor):
+ raise ValueError("Only torch.tensor is accepted when converting to ONNX.")
if mean.shape[0] != 1 or std.shape[0] != 1:
raise ValueError("Batch dimension must be one for broadcasting when converting to ONNX.")
else:
@@ -261,7 +260,7 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo
if mean.dim() == 1:
mean = mean.view(1, -1, *([1] * (data.dim() - 2)))
- # If the tensor is >1D (e.g., (B, C)), reshape to (B, C, 1, ...)
+ # If the torch.tensor is >1D (e.g., (B, C)), reshape to (B, C, 1, ...)
else:
while len(mean.shape) < data.dim():
mean = mean.unsqueeze(-1)
@@ -276,24 +275,24 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo
@perform_keep_shape_image
-def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> Tensor:
- r"""Normalise an image/video tensor by MinMax and re-scales the value between a range.
+def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:
+ r"""Normalise an image/video torch.tensor by MinMax and re-scales the value between a range.
The data is normalised using the following formulation:
.. math::
y_i = (b - a) * \frac{x_i - \text{min}(x)}{\text{max}(x) - \text{min}(x)} + a
- where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.
+ torch.where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.
Args:
- x: The image tensor to be normalised with shape :math:`(*, C, H, W)`.
+ x: The image torch.tensor to be normalised with shape :math:`(*, C, H, W)`.
min_val: The minimum value for the new range.
max_val: The maximum value for the new range.
eps: Float number to avoid zero division.
Returns:
- The normalised image tensor with same shape as input :math:`(*, C, H, W)`.
+ The normalised image torch.tensor with same shape as input :math:`(*, C, H, W)`.
Example:
>>> x = torch.rand(1, 5, 3, 3)
@@ -304,8 +303,8 @@ def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps
tensor(1.0000)
"""
- if not isinstance(x, Tensor):
- raise TypeError(f"data should be a tensor. Got: {type(x)}.")
+ if not isinstance(x, torch.Tensor):
+ raise TypeError(f"data should be a torch.tensor. Got: {type(x)}.")
if not isinstance(min_val, float):
raise TypeError(f"'min_val' should be a float. Got: {type(min_val)}.")
diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.py
index b22e353e3..6b6358b6f 100644
--- a/kornia/enhance/rescale.py
+++ b/kornia/enhance/rescale.py
@@ -17,26 +17,26 @@
from typing import Union
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, tensor
+import torch
+from torch import nn
-class Rescale(Module):
+class Rescale(nn.Module):
r"""Initialize the Rescale operator.
Args:
- factor: The scaling factor. Could be a float or a 0-d tensor.
+ factor: The scaling factor. Could be a float or a 0-d torch.tensor.
"""
- def __init__(self, factor: Union[float, Tensor]) -> None:
+ def __init__(self, factor: Union[float, torch.Tensor]) -> None:
super().__init__()
if isinstance(factor, float):
- self.factor = tensor(factor)
+ self.factor = torch.tensor(factor)
else:
- if not isinstance(factor, Tensor) or factor.ndim != 0:
- raise TypeError(f"Expected factor to be a float or a 0-d tensor, got {factor}.")
+ if not isinstance(factor, torch.Tensor) or factor.ndim != 0:
+ raise TypeError(f"Expected factor to be a float or a 0-d torch.tensor, got {factor}.")
self.factor = factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return input * self.factor
diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.py
index e392eb64c..9e634d07d 100644
--- a/kornia/enhance/shift_rgb.py
+++ b/kornia/enhance/shift_rgb.py
@@ -15,11 +15,13 @@
# limitations under the License.
#
-from kornia.core import Tensor, stack
+
+import torch
+
from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR
-def shift_rgb(image: Tensor, r_shift: Tensor, g_shift: Tensor, b_shift: Tensor) -> Tensor:
+def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:
"""Shift rgb channels.
Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels.
@@ -29,6 +31,6 @@ def shift_rgb(image: Tensor, r_shift: Tensor, g_shift: Tensor, b_shift: Tensor)
shifts = [r_shift, g_shift, b_shift]
- shifted = (image + stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1)
+ shifted = (image + torch.stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1)
return shifted
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 8c4737713..601c55303 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -18,28 +18,26 @@
from typing import List, Optional, Tuple
import torch
-
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, concatenate, tensor
+from torch import nn
__all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"]
-class ZCAWhitening(Module):
+class ZCAWhitening(nn.Module):
r"""Compute the ZCA whitening matrix transform and the mean vector and applies the transform to the data.
- The data tensor is flattened, and the mean :math:`\mathbf{\mu}`
+ The data torch.tensor is flattened, and the mean :math:`\mathbf{\mu}`
and covariance matrix :math:`\mathbf{\Sigma}` are computed from
- the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, where
+ the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, torch.where
:math:`N` is the sample size and :math:`D` is flattened dimensionality
- (e.g. for a tensor with size 5x3x2x2 :math:`N = 5` and :math:`D = 12`). The ZCA whitening
+ (e.g. for a torch.tensor with size 5x3x2x2 :math:`N = 5` and :math:`D = 12`). The ZCA whitening
transform is given by:
.. math::
\mathbf{X}_{\text{zca}} = (\mathbf{X - \mu})(US^{-\frac{1}{2}}U^T)^T
- where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
+ torch.where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
eigenvalues of :math:`\Sigma`. After the transform is applied, the output is reshaped to same shape.
Args:
@@ -96,11 +94,11 @@ class ZCAWhitening(Module):
self.fitted = False
- self.mean_vector: Tensor
- self.transform_matrix: Tensor
- self.transform_inv: Optional[Tensor]
+ self.mean_vector: torch.Tensor
+ self.transform_matrix: torch.Tensor
+ self.transform_inv: Optional[torch.Tensor]
- def fit(self, x: Tensor) -> "ZCAWhitening":
+ def fit(self, x: torch.Tensor) -> "ZCAWhitening":
r"""Fit ZCA whitening matrices to the data.
Args:
@@ -128,7 +126,7 @@ class ZCAWhitening(Module):
return self
- def forward(self, x: Tensor, include_fit: bool = False) -> Tensor:
+ def forward(self, x: torch.Tensor, include_fit: bool = False) -> torch.Tensor:
r"""Apply the whitening transform to the data.
Args:
@@ -149,7 +147,7 @@ class ZCAWhitening(Module):
return x_whiten
- def inverse_transform(self, x: Tensor) -> Tensor:
+ def inverse_transform(self, x: torch.Tensor) -> torch.Tensor:
r"""Apply the inverse transform to the whitened data.
Args:
@@ -166,9 +164,9 @@ class ZCAWhitening(Module):
raise RuntimeError("Did not compute inverse ZCA. Please set compute_inv to True")
if self.transform_inv is None:
- raise TypeError("The transform inverse should be a Tensor. Gotcha None.")
+ raise TypeError("The transform inverse should be a torch.Tensor. Gotcha None.")
- mean_inv: Tensor = -self.mean_vector.mm(self.transform_matrix)
+ mean_inv: torch.Tensor = -self.mean_vector.mm(self.transform_matrix)
y = linear_transform(x, self.transform_inv, mean_inv)
@@ -176,15 +174,15 @@ class ZCAWhitening(Module):
def zca_mean(
- inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False
-) -> Tuple[Tensor, Tensor, Optional[Tensor]]:
+ inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
r"""Compute the ZCA whitening matrix and mean vector.
The output can be used with :py:meth:`~kornia.color.linear_transform`.
See :class:`~kornia.color.ZCAWhitening` for details.
Args:
- inp: input data tensor.
+ inp: input data torch.tensor.
dim: Specifies the dimension that serves as the samples dimension.
unbiased: Whether to use the unbiased estimate of the covariance matrix.
eps: a small number used for numerical stability.
@@ -212,8 +210,8 @@ def zca_mean(
>>> # transform_matrix.size() equals (12,12) and the mean vector.size equal (1,12)
"""
- if not isinstance(inp, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
+ if not isinstance(inp, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(inp)}")
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -237,21 +235,21 @@ def zca_mean(
if dim < 0:
dim = len(inp_size) + dim
- feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
+ feat_dims = torch.cat([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
- new_order: List[int] = concatenate([tensor([dim]), feat_dims]).tolist()
+ new_order: List[int] = torch.cat([torch.tensor([dim]), feat_dims]).tolist()
inp_permute = inp.permute(new_order)
N = inp_size[dim]
- feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
- mean: Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
+ mean: torch.Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
mean = mean.reshape((1, num_features))
- inp_center_flat: Tensor = inp_permute.reshape((N, num_features)) - mean
+ inp_center_flat: torch.Tensor = inp_permute.reshape((N, num_features)) - mean
cov = inp_center_flat.t().mm(inp_center_flat)
@@ -263,23 +261,23 @@ def zca_mean(
U, S, _ = torch.linalg.svd(cov)
S = S.reshape(-1, 1)
- S_inv_root: Tensor = torch.rsqrt(S + eps)
- T: Tensor = (U).mm(S_inv_root * U.t())
+ S_inv_root: torch.Tensor = torch.rsqrt(S + eps)
+ T: torch.Tensor = (U).mm(S_inv_root * U.t())
- T_inv: Optional[Tensor] = None
+ T_inv: Optional[torch.Tensor] = None
if return_inverse:
T_inv = (U).mm(torch.sqrt(S + eps) * U.t())
return T, mean, T_inv
-def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> Tensor:
+def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:
r"""Apply ZCA whitening transform.
See :class:`~kornia.color.ZCAWhitening` for details.
Args:
- inp: input data tensor.
+ inp: input data torch.tensor.
dim: Specifies the dimension that serves as the samples dimension.
unbiased: Whether to use the unbiased estimate of the covariance matrix.
eps: a small number used for numerical stability.
@@ -299,8 +297,8 @@ def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e
[-1.0000, -0.5773]])
"""
- if not isinstance(inp, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
+ if not isinstance(inp, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(inp)}")
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -318,10 +316,13 @@ def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e
return inp_whiten
-def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor, dim: int = 0) -> Tensor:
- r"""Given a transformation matrix and a mean vector, this function will flatten the input tensor along the given
- dimension and subtract the mean vector from it. Then the dot product with the transformation matrix will be
- computed and then the resulting tensor is reshaped to the original input shape.
+def linear_transform(
+ inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0
+) -> torch.Tensor:
+ r"""Given a transformation matrix and a mean vector, this function will flatten the input
+ torch.tensor along the given dimension and subtract the mean vector from it. Then the dot
+ product with the transformation matrix will be computed and then the resulting torch.tensor
+ is reshaped to the original input shape.
.. math::
@@ -342,20 +343,20 @@ def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor,
Transformed data.
Example:
- >>> # Example where dim = 3
+ >>> # Example torch.where dim = 3
>>> inp = torch.ones((10,3,4,5))
>>> transform_mat = torch.ones((10*3*4,10*3*4))
>>> mean = 2*torch.ones((1,10*3*4))
>>> out = linear_transform(inp, transform_mat, mean, 3)
- >>> print(out.shape, out.unique()) # Should a be (10,3,4,5) tensor of -120s
+ >>> print(out.shape, out.unique()) # Should a be (10,3,4,5) torch.tensor of -120s
torch.Size([10, 3, 4, 5]) tensor([-120.])
- >>> # Example where dim = 0
+ >>> # Example torch.where dim = 0
>>> inp = torch.ones((10,2))
>>> transform_mat = torch.ones((2,2))
>>> mean = torch.zeros((1,2))
>>> out = linear_transform(inp, transform_mat, mean)
- >>> print(out.shape, out.unique()) # Should a be (10,2) tensor of 2s
+ >>> print(out.shape, out.unique()) # Should a be (10,2) torch.tensor of 2s
torch.Size([10, 2]) tensor([2.])
""" # noqa: D205
@@ -369,15 +370,15 @@ def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor,
if dim < 0:
dim = len(inp_size) + dim
- feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
+ feat_dims = torch.cat([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
- perm = concatenate([tensor([dim]), feat_dims])
+ perm = torch.cat([torch.tensor([dim]), feat_dims])
perm_inv = torch.argsort(perm)
new_order: List[int] = perm.tolist()
inv_order: List[int] = perm_inv.tolist()
- feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
inp_permute = inp.permute(new_order)
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 70179fff1..4f75398d0 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -23,7 +23,6 @@ from typing import Optional, Tuple, Union
import torch
-from kornia.core import Tensor, as_tensor
from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale
@@ -49,15 +48,15 @@ def get_adalam_default_config() -> AdalamConfig:
def match_adalam(
- desc1: Tensor,
- desc2: Tensor,
- lafs1: Tensor,
- lafs2: Tensor,
+ desc1: torch.Tensor,
+ desc2: torch.Tensor,
+ lafs1: torch.Tensor,
+ lafs2: torch.Tensor,
config: Optional[AdalamConfig] = None,
hw1: Optional[Tuple[int, int]] = None,
hw2: Optional[Tuple[int, int]] = None,
- dm: Optional[Tensor] = None,
-) -> Tuple[Tensor, Tensor]:
+ dm: Optional[torch.Tensor] = None,
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Perform descriptor matching, followed by AdaLAM filtering.
See :cite:`AdaLAM2020` for more details.
@@ -70,7 +69,7 @@ def match_adalam(
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
config: dict with AdaLAM config
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
hw1: Height/width of image.
hw2: Height/width of image.
@@ -78,8 +77,8 @@ def match_adalam(
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- where 0 <= B3 <= B1.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ torch.where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -132,38 +131,38 @@ class AdalamFilter:
def filter_matches(
self,
- k1: Tensor,
- k2: Tensor,
- putative_matches: Tensor,
- scores: Tensor,
- mnn: Optional[Tensor] = None,
+ k1: torch.Tensor,
+ k2: torch.Tensor,
+ putative_matches: torch.Tensor,
+ scores: torch.Tensor,
+ mnn: Optional[torch.Tensor] = None,
im1shape: Optional[Tuple[int, int]] = None,
im2shape: Optional[Tuple[int, int]] = None,
- o1: Optional[Tensor] = None,
- o2: Optional[Tensor] = None,
- s1: Optional[Tensor] = None,
- s2: Optional[Tensor] = None,
+ o1: Optional[torch.Tensor] = None,
+ o2: Optional[torch.Tensor] = None,
+ s1: Optional[torch.Tensor] = None,
+ s2: Optional[torch.Tensor] = None,
return_dist: bool = False,
- ) -> Union[Tuple[Tensor, Tensor], Tensor]:
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""Call the core functionality of AdaLAM, i.e. just outlier filtering.
No sanity check is performed on the inputs.
Args:
k1: keypoint locations in the source image, in pixel coordinates.
- Expected a float32 tensor with shape (num_keypoints_in_source_image, 2).
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source_image, 2).
k2: keypoint locations in the destination image, in pixel coordinates.
- Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).
+ Expected a float32 torch.tensor with shape (num_keypoints_in_destination_image, 2).
putative_matches: Initial set of putative matches to be filtered.
The current implementation assumes that these are unfiltered nearest neighbor matches,
so it requires this to be a list of indices a_i such that the source keypoint i is
associated to the destination keypoint a_i. For now to use AdaLAM on different inputs a
workaround on the input format is required.
- Expected a long tensor with shape (num_keypoints_in_source_image,).
+ Expected a long torch.tensor with shape (num_keypoints_in_source_image,).
scores: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on
- seed point selection. Expected a bool tensor with shape (num_keypoints_in_source_image,)
+ seed point selection. Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of
wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
of source image
@@ -172,17 +171,18 @@ class AdalamFilter:
of destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config
is set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
- Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
o2: same as o1 but for destination.
s1: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
- Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
s2: same as s1 but for destination.
return_dist: if True, inverse confidence value is also outputted.
Returns:
Filtered putative matches.
- A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
+ A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ keypoints in k1 and k2.
"""
with torch.no_grad():
@@ -204,18 +204,18 @@ class AdalamFilter:
def match_and_filter(
self,
- k1: Tensor,
- k2: Tensor,
- d1: Tensor,
- d2: Tensor,
+ k1: torch.Tensor,
+ k2: torch.Tensor,
+ d1: torch.Tensor,
+ d2: torch.Tensor,
im1shape: Optional[Tuple[int, int]] = None,
im2shape: Optional[Tuple[int, int]] = None,
- o1: Optional[Tensor] = None,
- o2: Optional[Tensor] = None,
- s1: Optional[Tensor] = None,
- s2: Optional[Tensor] = None,
+ o1: Optional[torch.Tensor] = None,
+ o2: Optional[torch.Tensor] = None,
+ s1: Optional[torch.Tensor] = None,
+ s2: Optional[torch.Tensor] = None,
return_dist: bool = False,
- ) -> Union[Tuple[Tensor, Tensor], Tensor]:
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""Match and filter with AdaLAM.
This function:
@@ -253,7 +253,8 @@ class AdalamFilter:
Returns:
Filtered putative matches.
- A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
+ A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ keypoints in k1 and k2.
"""
if s1 is None or s2 is None:
@@ -268,18 +269,18 @@ class AdalamFilter:
"Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501
"Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501
)
- _k1 = as_tensor(k1, device=self.config["device"], dtype=torch.float32)
- _k2 = as_tensor(k2, device=self.config["device"], dtype=torch.float32)
- _d1 = as_tensor(d1, device=self.config["device"], dtype=torch.float32)
- _d2 = as_tensor(d2, device=self.config["device"], dtype=torch.float32)
+ _k1 = torch.as_tensor(k1, device=self.config["device"], dtype=torch.float32)
+ _k2 = torch.as_tensor(k2, device=self.config["device"], dtype=torch.float32)
+ _d1 = torch.as_tensor(d1, device=self.config["device"], dtype=torch.float32)
+ _d2 = torch.as_tensor(d2, device=self.config["device"], dtype=torch.float32)
if o1 is not None:
- _o1 = as_tensor(o1, device=self.config["device"], dtype=torch.float32)
- _o2 = as_tensor(o2, device=self.config["device"], dtype=torch.float32)
+ _o1 = torch.as_tensor(o1, device=self.config["device"], dtype=torch.float32)
+ _o2 = torch.as_tensor(o2, device=self.config["device"], dtype=torch.float32)
else:
_o1, _o2 = o1, o2
if s1 is not None:
- _s1 = as_tensor(s1, device=self.config["device"], dtype=torch.float32)
- _s2 = as_tensor(s2, device=self.config["device"], dtype=torch.float32)
+ _s1 = torch.as_tensor(s1, device=self.config["device"], dtype=torch.float32)
+ _s2 = torch.as_tensor(s2, device=self.config["device"], dtype=torch.float32)
else:
_s1, _s2 = s1, s2
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 7616c54b8..df9f888fd 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -21,8 +21,6 @@ from typing import Optional, Tuple, Union
import torch
from typing_extensions import NotRequired, TypedDict
-from kornia.core import Tensor, concatenate, tensor, where
-
from .ransac import ransac
from .utils import dist_matrix, orientation_diff
@@ -48,7 +46,7 @@ class AdalamConfig(TypedDict):
runtime
force_seed_mnn: Whether to consider only MNN for the purpose of selecting seeds. Generally improves accuracy
at the cost of runtime
- device: Device to be used for running AdaLAM. Use GPU if available.
+ device: Union[str, torch.device, None] to be used for running AdaLAM. Use GPU if available.
mnn: Default None. You can provide a MNN mask in input to skip MNN computation and still get the improvement.
"""
@@ -64,15 +62,15 @@ class AdalamConfig(TypedDict):
refit: NotRequired[bool]
force_seed_mnn: NotRequired[bool]
device: NotRequired[torch.device]
- mnn: NotRequired[Tensor]
+ mnn: NotRequired[torch.Tensor]
-def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
+def _no_match(dm: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Output empty tensors.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
"""
dists = torch.empty(0, 1, device=dm.device, dtype=dm.dtype)
@@ -81,8 +79,12 @@ def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
def select_seeds(
- dist1: Tensor, R1: Union[float, Tensor], scores1: Tensor, fnn12: Tensor, mnn: Optional[Tensor]
-) -> Tuple[Tensor, Tensor]:
+ dist1: torch.Tensor,
+ R1: Union[float, torch.Tensor],
+ scores1: torch.Tensor,
+ fnn12: torch.Tensor,
+ mnn: Optional[torch.Tensor],
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Select seed correspondences among the set of available matches.
dist1: Precomputed distance matrix between keypoints in image I_1
@@ -92,7 +94,7 @@ def select_seeds(
The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.
If None, it disables the mutual nearest neighbor filtering on seed point selection.
- Expected a bool tensor with shape (num_keypoints_in_source_image,)
+ Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
Returns:
Indices of seed points.
@@ -111,29 +113,29 @@ def select_seeds(
im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 < 0.8**2)
# collect all seeds in both images and the 1NN of the seeds of the other image
- im1seeds = where(im1bs)[0] # (n1bs) index format
+ im1seeds = torch.where(im1bs)[0] # (n1bs) index format
im2seeds = fnn12[im1bs] # (n1bs) index format
return im1seeds, im2seeds
def extract_neighborhood_sets(
- o1: Optional[Tensor],
- o2: Optional[Tensor],
- s1: Optional[Tensor],
- s2: Optional[Tensor],
- dist1: Tensor,
- im1seeds: Tensor,
- im2seeds: Tensor,
- k1: Tensor,
- k2: Tensor,
- R1: Union[float, Tensor],
- R2: Union[float, Tensor],
- fnn12: Tensor,
+ o1: Optional[torch.Tensor],
+ o2: Optional[torch.Tensor],
+ s1: Optional[torch.Tensor],
+ s2: Optional[torch.Tensor],
+ dist1: torch.Tensor,
+ im1seeds: torch.Tensor,
+ im2seeds: torch.Tensor,
+ k1: torch.Tensor,
+ k2: torch.Tensor,
+ R1: Union[float, torch.Tensor],
+ R2: Union[float, torch.Tensor],
+ fnn12: torch.Tensor,
ORIENTATION_THR: float,
SCALE_RATE_THR: float,
SEARCH_EXP: float,
MIN_INLIERS: float,
-) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Assign keypoints to seed points.
This checks both the distance and the agreement of the local transformation
@@ -190,7 +192,7 @@ def extract_neighborhood_sets(
# count how many keypoints ended up in each neighborhood
numn1 = torch.sum(local_neighs_mask, dim=1)
- # and only keep the ones that have enough points
+ # and only keep the torch.ones that have enough points
valid_seeds = numn1 >= MIN_INLIERS
local_neighs_mask = local_neighs_mask[valid_seeds, :]
@@ -201,14 +203,14 @@ def extract_neighborhood_sets(
def extract_local_patterns(
- fnn12: Tensor,
- fnn_to_seed_local_consistency_map_corr: Tensor,
- k1: Tensor,
- k2: Tensor,
- im1seeds: Tensor,
- im2seeds: Tensor,
- scores: Tensor,
-) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
+ fnn12: torch.Tensor,
+ fnn_to_seed_local_consistency_map_corr: torch.Tensor,
+ k1: torch.Tensor,
+ k2: torch.Tensor,
+ im1seeds: torch.Tensor,
+ im2seeds: torch.Tensor,
+ scores: torch.Tensor,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Prepare local neighborhoods around each seed for the parallel RANSACs.
This involves two steps: 1) Collect
@@ -243,7 +245,7 @@ def extract_local_patterns(
# first get an indexing representation of the assignments:
# - ransidx holds the index of the seed for each assignment
# - tokp1 holds the index of the keypoint in image I_1 for each assignment
- ransidx, tokp1 = where(fnn_to_seed_local_consistency_map_corr)
+ ransidx, tokp1 = torch.where(fnn_to_seed_local_consistency_map_corr)
# - and of course tokp2 holds the index of the corresponding keypoint in image I_2
tokp2 = fnn12[tokp1]
@@ -265,39 +267,39 @@ def extract_local_patterns(
def adalam_core(
- k1: Tensor,
- k2: Tensor,
- fnn12: Tensor,
- scores1: Tensor,
+ k1: torch.Tensor,
+ k2: torch.Tensor,
+ fnn12: torch.Tensor,
+ scores1: torch.Tensor,
config: AdalamConfig,
- mnn: Optional[Tensor] = None,
+ mnn: Optional[torch.Tensor] = None,
im1shape: Optional[Tuple[int, int]] = None,
im2shape: Optional[Tuple[int, int]] = None,
- o1: Optional[Tensor] = None,
- o2: Optional[Tensor] = None,
- s1: Optional[Tensor] = None,
- s2: Optional[Tensor] = None,
+ o1: Optional[torch.Tensor] = None,
+ o2: Optional[torch.Tensor] = None,
+ s1: Optional[torch.Tensor] = None,
+ s2: Optional[torch.Tensor] = None,
return_dist: bool = False,
-) -> Union[Tuple[Tensor, Tensor], Tensor]:
+) -> Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""Call the core functionality of AdaLAM, i.e. just outlier filtering.
No sanity check is performed on the inputs.
Args:
k1: keypoint locations in the source image, in pixel coordinates.
- Expected a float32 tensor with shape (num_keypoints_in_source_image, 2).
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source_image, 2).
k2: keypoint locations in the destination image, in pixel coordinates.
- Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).
+ Expected a float32 torch.tensor with shape (num_keypoints_in_destination_image, 2).
fnn12: Initial set of putative matches to be filtered.
The current implementation assumes that these are unfiltered nearest neighbor matches,
so it requires this to be a list of indices a_i such that the source keypoint i is associated to the
destination keypoint a_i. For now to use AdaLAM on different inputs a workaround on the input format is
- required. Expected a long tensor with shape (num_keypoints_in_source_image,).
+ required. Expected a long torch.tensor with shape (num_keypoints_in_source_image,).
scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
config: Adalam configuration.
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on seed
- point selection. Expected a bool tensor with shape (num_keypoints_in_source_image,)
+ point selection. Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted
runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of source
image
@@ -306,16 +308,17 @@ def adalam_core(
destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is
set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
- Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
o2: Same as o1 but for destination.
s1: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
- Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
s2: Same as s1 but for destination.
return_dist: if True, inverse confidence value is also outputted. Default is False
Returns:
- idxs: A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
+ idxs: A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ keypoints in k1 and k2.
dists: inverse confidence ratio.
"""
@@ -329,14 +332,14 @@ def adalam_core(
REFIT = config["refit"]
if isinstance(im1shape, tuple):
- _im1shape = tensor(im1shape, device=k1.device, dtype=k1.dtype)
+ _im1shape = torch.tensor(im1shape, device=k1.device, dtype=k1.dtype)
else:
k1mins = k1.min(dim=0).values
k1maxs = k1.max(dim=0).values
_im1shape = k1maxs - k1mins
if isinstance(im2shape, tuple):
- _im2shape = tensor(im2shape, device=k2.device, dtype=k2.dtype)
+ _im2shape = torch.tensor(im2shape, device=k2.device, dtype=k2.dtype)
else:
k2mins = k2.min(dim=0).values
k2maxs = k2.max(dim=0).values
@@ -375,7 +378,7 @@ def adalam_core(
if rdims.shape[0] == 0:
# No seed point survived. Just output ratio-test matches. This should happen very rarely.
score_mask = scores1 <= 0.95
- absolute_im1idx = where(score_mask)[0]
+ absolute_im1idx = torch.where(score_mask)[0]
if len(absolute_im1idx) > 0:
absolute_im2idx = fnn12[absolute_im1idx]
out_scores = scores1[score_mask].reshape(-1, 1)
@@ -415,7 +418,7 @@ def adalam_core(
final_matches, idxs, counts = torch.unique(final_matches, dim=0, return_inverse=True, return_counts=True)
_, ind_sorted = torch.sort(idxs)
cum_sum = counts.cumsum(0)
- cum_sum = concatenate((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))
+ cum_sum = torch.cat((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))
first_indicies = ind_sorted[cum_sum]
accepted_dist = accepted_dist[first_indicies]
if return_dist:
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index a3995ec2d..13896c289 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -19,12 +19,10 @@ from typing import Any, Dict, Tuple, Union
import torch
-from kornia.core import Tensor
-
from .utils import arange_sequence, batch_2x2_ellipse, batch_2x2_inv, draw_first_k_couples, piecewise_arange
-def stable_sort_residuals(residuals: Tensor, ransidx: Tensor) -> Tuple[Tensor, Tensor]:
+def stable_sort_residuals(residuals: torch.Tensor, ransidx: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Sort residuals."""
logres = torch.log(residuals + 1e-10)
minlogres = torch.min(logres)
@@ -40,8 +38,8 @@ def stable_sort_residuals(residuals: Tensor, ransidx: Tensor) -> Tuple[Tensor, T
def group_sum_and_cumsum(
- scores_mat: Tensor, end_group_idx: Tensor, group_idx: Union[Tensor, slice, None] = None
-) -> Tuple[Tensor, Union[Tensor, None]]:
+ scores_mat: torch.Tensor, end_group_idx: torch.Tensor, group_idx: Union[torch.Tensor, slice, None] = None
+) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]:
"""Calculate cumulative sum over group."""
cumulative_scores = torch.cumsum(scores_mat, dim=1)
ending_cumusums = cumulative_scores[:, end_group_idx]
@@ -61,8 +59,13 @@ def group_sum_and_cumsum(
def confidence_based_inlier_selection(
- residuals: Tensor, ransidx: Tensor, rdims: Tensor, idxoffsets: Tensor, dv: torch.device, min_confidence: Tensor
-) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
+ residuals: torch.Tensor,
+ ransidx: torch.Tensor,
+ rdims: torch.Tensor,
+ idxoffsets: torch.Tensor,
+ dv: torch.device,
+ min_confidence: torch.Tensor,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Select inliers from confidence scores."""
numransacs = rdims.shape[0]
numiters = residuals.shape[0]
@@ -82,8 +85,8 @@ def confidence_based_inlier_selection(
inlier_weights[too_perfect_fits] = 0.0
balanced_rdims, weights_cumsums = group_sum_and_cumsum(inlier_weights, end_rans_indexing, ransidx)
- if not isinstance(weights_cumsums, Tensor):
- raise TypeError("Expected the `weights_cumsums` to be a Tensor!")
+ if not isinstance(weights_cumsums, torch.Tensor):
+ raise TypeError("Expected the `weights_cumsums` to be a torch.Tensor!")
progressive_inl_rates = weights_cumsums.float() / (balanced_rdims.repeat_interleave(rdims, dim=1)).float()
@@ -105,14 +108,14 @@ def confidence_based_inlier_selection(
def sample_padded_inliers(
- xsamples: Tensor,
- ysamples: Tensor,
- inlier_counts: Tensor,
- inl_ransidx: Tensor,
- inl_sampleidx: Tensor,
+ xsamples: torch.Tensor,
+ ysamples: torch.Tensor,
+ inlier_counts: torch.Tensor,
+ inl_ransidx: torch.Tensor,
+ inl_sampleidx: torch.Tensor,
numransacs: int,
dv: torch.device,
-) -> Tuple[Tensor, Tensor]:
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Sample from padded inliers."""
maxinliers = int(torch.max(inlier_counts).item())
dtype = xsamples.dtype
@@ -126,8 +129,13 @@ def sample_padded_inliers(
def ransac(
- xsamples: Tensor, ysamples: Tensor, rdims: Tensor, config: Dict[str, Any], iters: int = 128, refit: bool = True
-) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+ xsamples: torch.Tensor,
+ ysamples: torch.Tensor,
+ rdims: torch.Tensor,
+ config: Dict[str, Any],
+ iters: int = 128,
+ refit: bool = True,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run ransac."""
DET_THR = config["detected_scale_rate_threshold"]
MIN_CONFIDENCE = config["min_confidence"]
@@ -171,7 +179,7 @@ def ransac(
)
# Organize inliers found into a matrix for efficient GPU re-fitting.
- # Cope with the irregular number of inliers per sample by padding with zeros
+ # Cope with the irregular number of inliers per sample by padding with torch.zeros
padded_inlier_x, padded_inlier_y = sample_padded_inliers(
xsamples, ysamples, inl_counts, inl_ransidx, inl_sampleidx, numransacs, dv
)
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index 8209c29b1..7f44060d8 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -20,10 +20,8 @@ from typing import Tuple
import torch
-from kornia.core import Tensor
-
-def arange_sequence(ranges: Tensor) -> Tensor:
+def arange_sequence(ranges: torch.Tensor) -> torch.Tensor:
"""Return a sequence of the ranges specified by the argument.
Example:
@@ -37,7 +35,7 @@ def arange_sequence(ranges: Tensor) -> Tensor:
return complete_ranges[complete_ranges < ranges.unsqueeze(-1)]
-def dist_matrix(d1: Tensor, d2: Tensor, is_normalized: bool = False) -> Tensor:
+def dist_matrix(d1: torch.Tensor, d2: torch.Tensor, is_normalized: bool = False) -> torch.Tensor:
"""Distance between two tensors."""
if is_normalized:
return 2 - 2.0 * d1 @ d2.t()
@@ -49,7 +47,7 @@ def dist_matrix(d1: Tensor, d2: Tensor, is_normalized: bool = False) -> Tensor:
return distmat
-def orientation_diff(o1: Tensor, o2: Tensor) -> Tensor:
+def orientation_diff(o1: torch.Tensor, o2: torch.Tensor) -> torch.Tensor:
"""Orientation difference between two tensors."""
diff = o2 - o1
diff[diff < -180] += 360
@@ -57,7 +55,7 @@ def orientation_diff(o1: Tensor, o2: Tensor) -> Tensor:
return diff
-def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
+def piecewise_arange(piecewise_idxer: torch.Tensor) -> torch.Tensor:
"""Count repeated indices.
Example:
@@ -65,7 +63,7 @@ def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
"""
dv = piecewise_idxer.device
# print(piecewise_idxer)
- uni: Tensor
+ uni: torch.Tensor
uni, counts = torch.unique_consecutive(piecewise_idxer, return_counts=True)
# print(counts)
maxcnt = int(torch.max(counts).item())
@@ -76,7 +74,7 @@ def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
return ranges[tmp]
-def batch_2x2_inv(m: Tensor, check_dets: bool = False) -> Tensor:
+def batch_2x2_inv(m: torch.Tensor, check_dets: bool = False) -> torch.Tensor:
"""Return inverse of batch of 2x2 matrices."""
a = m[..., 0, 0]
b = m[..., 0, 1]
@@ -93,17 +91,17 @@ def batch_2x2_inv(m: Tensor, check_dets: bool = False) -> Tensor:
return minv / det.unsqueeze(-1).unsqueeze(-1)
-def batch_2x2_Q(m: Tensor) -> Tensor:
+def batch_2x2_Q(m: torch.Tensor) -> torch.Tensor:
"""Return Q of batch of 2x2 matrices."""
return batch_2x2_inv(batch_2x2_invQ(m), check_dets=True)
-def batch_2x2_invQ(m: Tensor) -> Tensor:
+def batch_2x2_invQ(m: torch.Tensor) -> torch.Tensor:
"""Return inverse Q of batch of 2x2 matrices."""
return m @ m.transpose(-1, -2)
-def batch_2x2_det(m: Tensor) -> Tensor:
+def batch_2x2_det(m: torch.Tensor) -> torch.Tensor:
"""Return determinant of batch of 2x2 matrices."""
a = m[..., 0, 0]
b = m[..., 0, 1]
@@ -112,7 +110,7 @@ def batch_2x2_det(m: Tensor) -> Tensor:
return a * d - b * c
-def batch_2x2_ellipse(m: Tensor, *, eps: float = 0.0) -> Tuple[Tensor, Tensor]:
+def batch_2x2_ellipse(m: torch.Tensor, *, eps: float = 0.0) -> Tuple[torch.Tensor, torch.Tensor]:
"""Return Eigenvalues and Eigenvectors of batch of 2x2 matrices."""
am = m[..., 0, 0]
bm = m[..., 0, 1]
@@ -149,7 +147,7 @@ def batch_2x2_ellipse(m: Tensor, *, eps: float = 0.0) -> Tuple[Tensor, Tensor]:
return eigenvals, eigenvecs
-def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device) -> Tensor:
+def draw_first_k_couples(k: int, rdims: torch.Tensor, dv: torch.device) -> torch.Tensor:
"""Return first k couples.
Exhaustive search over the first n samples:
@@ -171,8 +169,8 @@ def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device) -> Tensor:
return torch.remainder(idx_sequence.unsqueeze(-1), rdims)
-def random_samples_indices(iters: int, rdims: Tensor, dv: torch.device) -> Tensor:
- """Randomly sample indices of tensor."""
+def random_samples_indices(iters: int, rdims: torch.Tensor, dv: torch.device) -> torch.Tensor:
+ """Randomly sample indices of torch.tensor."""
rands = torch.rand(size=(iters, 2, rdims.shape[0]), device=dv)
scaled_rands = rands * (rdims - 1e-8).float()
rand_samples_rel = scaled_rands.long()
diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.py
index fec6891ac..bd7d34ac8 100644
--- a/kornia/feature/dedode/decoder.py
+++ b/kornia/feature/dedode/decoder.py
@@ -20,8 +20,6 @@ from typing import Any, Optional, Tuple
import torch
from torch import nn
-from kornia.core import Tensor
-
class Decoder(nn.Module):
def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None: # type: ignore[no-untyped-def]
@@ -32,8 +30,8 @@ class Decoder(nn.Module):
self.num_prototypes = num_prototypes
def forward(
- self, features: Tensor, context: Optional[Tensor] = None, scale: Optional[int] = None
- ) -> Tuple[Tensor, Optional[Tensor]]:
+ self, features: torch.Tensor, context: Optional[torch.Tensor] = None, scale: Optional[int] = None
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
if context is not None:
features = torch.cat((features, context), dim=1)
stuff = self.layers[scale](features)
@@ -105,7 +103,7 @@ class ConvRefiner(nn.Module):
conv2 = nn.Conv2d(out_dim, out_dim, 1, 1, 0)
return nn.Sequential(conv1, norm, relu, conv2)
- def forward(self, feats: Tensor) -> Tensor:
+ def forward(self, feats: torch.Tensor) -> torch.Tensor:
_b, _c, _hs, _ws = feats.shape
with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):
x0 = self.block1(feats)
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index aa2c0ad23..ba44700ae 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -19,8 +19,8 @@ from typing import Dict, Literal, Optional, Tuple
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.enhance.normalize import Normalize
from kornia.utils.helpers import map_location_to_cpu
@@ -46,8 +46,8 @@ urls: Dict[str, Dict[str, str]] = {
}
-class DeDoDe(Module):
- r"""Module which detects and/or describes local features in an image using the DeDode method.
+class DeDoDe(nn.Module):
+ r"""nn.Module which detects and/or describes local features in an image using the DeDode method.
See :cite:`edstedt2024dedode` for details.
@@ -81,25 +81,27 @@ class DeDoDe(Module):
def forward(
self,
- images: Tensor,
+ images: torch.Tensor,
n: Optional[int] = 10_000,
apply_imagenet_normalization: bool = True,
pad_if_not_divisible: bool = True,
- ) -> Tuple[Tensor, Tensor, Tensor]:
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Detect and describe keypoints in the input images.
Args:
- images: A tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.
+ images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.
n: The number of keypoints to detect.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
- pad_if_not_divisible: pad image shape if not evenly divisible.
+ pad_if_not_divisible: F.pad image shape if not evenly divisible.
Returns:
- keypoints: A tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,
- unlike `.detect()` function
- scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
- descriptions: A tensor of shape :math:`(B, N, DIM)` containing the descriptions of the detected keypoints.
- DIM is 256 for B and 512 for G.
+ keypoints: A torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,
+ unlike `.detect()` function.
+
+ scores: A torch.tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
+
+ descriptions: A torch.tensor of shape :math:`(B, N, DIM)` containing the descriptions
+ of the detected keypoints. DIM is 256 for B and 512 for G.
"""
if apply_imagenet_normalization:
@@ -109,7 +111,7 @@ class DeDoDe(Module):
if pad_if_not_divisible:
pd_h = 14 - h % 14 if h % 14 > 0 else 0
pd_w = 14 - w % 14 if w % 14 > 0 else 0
- images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)
+ images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)
keypoints, scores = self.detect(images, n=n, apply_imagenet_normalization=False, crop_h=h, crop_w=w)
descriptions = self.describe(images, keypoints, apply_imagenet_normalization=False, crop_h=h, crop_w=w)
return dedode_denormalize_pixel_coordinates(keypoints, H, W), scores, descriptions
@@ -117,27 +119,27 @@ class DeDoDe(Module):
@torch.inference_mode()
def detect(
self,
- images: Tensor,
+ images: torch.Tensor,
n: Optional[int] = 10_000,
apply_imagenet_normalization: bool = True,
pad_if_not_divisible: bool = True,
crop_h: Optional[int] = None,
crop_w: Optional[int] = None,
- ) -> Tuple[Tensor, Tensor]:
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
"""Detect keypoints in the input images.
Args:
- images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.
+ images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the input images.
n: The number of keypoints to detect.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
- pad_if_not_divisible: pad image shape if not evenly divisible.
+ pad_if_not_divisible: F.pad image shape if not evenly divisible.
crop_h: The height of the crop to be used for detection. If None, the full image is used.
crop_w: The width of the crop to be used for detection. If None, the full image is used.
Returns:
- keypoints: A tensor of shape :math:`(B, N, 2)` containing the detected keypoints,
+ keypoints: A torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints,
normalized to the range :math:`[-1, 1]`.
- scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
+ scores: A torch.tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
@@ -147,7 +149,7 @@ class DeDoDe(Module):
h, w = images.shape[2:]
pd_h = 14 - h % 14 if h % 14 > 0 else 0
pd_w = 14 - w % 14 if w % 14 > 0 else 0
- images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)
+ images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)
if apply_imagenet_normalization:
images = self.normalizer(images)
logits = self.detector.forward(images)
@@ -163,24 +165,25 @@ class DeDoDe(Module):
@torch.inference_mode()
def describe(
self,
- images: Tensor,
- keypoints: Optional[Tensor] = None,
+ images: torch.Tensor,
+ keypoints: Optional[torch.Tensor] = None,
apply_imagenet_normalization: bool = True,
crop_h: Optional[int] = None,
crop_w: Optional[int] = None,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Describe keypoints in the input images. If keypoints are not provided, returns the dense descriptors.
Args:
- images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.
- keypoints: An optional tensor of shape :math:`(B, N, 2)` containing the detected keypoints.
+ images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the input images.
+ keypoints: An optional torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
crop_h: The height of the crop to be used for description. If None, the full image is used.
crop_w: The width of the crop to be used for description. If None, the full image is used.
Returns:
- descriptions: A tensor of shape :math:`(B, N, DIM)` containing the descriptions of the detected keypoints.
- If the dense descriptors are requested, the shape is :math:`(B, DIM, H, W)`.
+ descriptions: A torch.tensor of shape :math:`(B, N, DIM)` containing the descriptions
+ of the detected keypoints.
+ If the dense descriptors are requested, the shape is :math:`(B, DIM, H, W)`.
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
@@ -208,7 +211,7 @@ class DeDoDe(Module):
detector_weights: str = "L-C4-v2",
descriptor_weights: str = "G-upright",
amp_dtype: torch.dtype = torch.float16,
- ) -> Module:
+ ) -> nn.Module:
r"""Load a pretrained model.
Args:
diff --git a/kornia/feature/dedode/descriptor.py b/kornia/feature/dedode/descriptor.py
index f84aa21fa..a598c3b47 100644
--- a/kornia/feature/dedode/descriptor.py
+++ b/kornia/feature/dedode/descriptor.py
@@ -15,21 +15,21 @@
# limitations under the License.
#
+import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor
-
-class DeDoDeDescriptor(Module):
- def __init__(self, encoder: Module, decoder: Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
+class DeDoDeDescriptor(nn.Module):
+ def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(*args, **kwargs)
self.encoder = encoder
self.decoder = decoder
def forward(
self,
- images: Tensor,
- ) -> Tensor:
+ images: torch.Tensor,
+ ) -> torch.Tensor:
features, sizes = self.encoder(images)
context = None
scales = self.decoder.scales
diff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.py
index ec9286f8b..9ad5b0390 100644
--- a/kornia/feature/dedode/detector.py
+++ b/kornia/feature/dedode/detector.py
@@ -15,22 +15,21 @@
# limitations under the License.
#
+import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
-
class DeDoDeDetector(nn.Module):
- def __init__(self, encoder: Module, decoder: Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
+ def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(*args, **kwargs)
self.encoder = encoder
self.decoder = decoder
def forward(
self,
- images: Tensor,
- ) -> Tensor:
+ images: torch.Tensor,
+ ) -> torch.Tensor:
dtype = images.dtype
features, sizes = self.encoder(images)
context = None
diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.py
index 93c56fc21..74a43ca27 100644
--- a/kornia/feature/dedode/encoder.py
+++ b/kornia/feature/dedode/encoder.py
@@ -20,12 +20,10 @@ from typing import Any, Optional, Tuple
import torch
from torch import nn
-from kornia.core import Module, Tensor
-
from .vgg import vgg19_bn
-class VGG19(Module):
+class VGG19(nn.Module):
def __init__(self, amp: bool = False, amp_dtype: torch.dtype = torch.float16) -> None:
super().__init__()
self.layers = nn.ModuleList(vgg19_bn().features[:40]) # type: ignore
@@ -33,7 +31,7 @@ class VGG19(Module):
self.amp = amp
self.amp_dtype = amp_dtype
- def forward(self, x: Tensor, **kwargs): # type: ignore[no-untyped-def]
+ def forward(self, x: torch.Tensor, **kwargs): # type: ignore[no-untyped-def]
with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):
feats = []
sizes = []
@@ -45,7 +43,7 @@ class VGG19(Module):
return feats, sizes
-class FrozenDINOv2(Module):
+class FrozenDINOv2(nn.Module):
def __init__(self, amp: bool = True, amp_dtype: torch.dtype = torch.float16, dinov2_weights: Optional[Any] = None):
super().__init__()
if dinov2_weights is None:
@@ -69,7 +67,7 @@ class FrozenDINOv2(Module):
dinov2_vitl14 = dinov2_vitl14.to(self.amp_dtype)
self.dinov2_vitl14 = [dinov2_vitl14] # ugly hack to not show parameters to DDP
- def forward(self, x: Tensor): # type: ignore[no-untyped-def]
+ def forward(self, x: torch.Tensor): # type: ignore[no-untyped-def]
B, _C, H, W = x.shape
if self.dinov2_vitl14[0].device != x.device:
self.dinov2_vitl14[0] = self.dinov2_vitl14[0].to(x.device).to(self.amp_dtype)
@@ -79,7 +77,7 @@ class FrozenDINOv2(Module):
return [features_16.clone()], [(H // 14, W // 14)] # clone from inference mode to use in autograd
-class VGG_DINOv2(Module):
+class VGG_DINOv2(nn.Module):
def __init__(self, vgg_kwargs=None, dinov2_kwargs=None): # type: ignore[no-untyped-def]
if (vgg_kwargs is None) or (dinov2_kwargs is None):
raise ValueError("Input kwargs please")
@@ -87,7 +85,7 @@ class VGG_DINOv2(Module):
self.vgg = VGG19(**vgg_kwargs)
self.frozen_dinov2 = FrozenDINOv2(**dinov2_kwargs)
- def forward(self, x: Tensor) -> Tuple[Tensor, Tuple[int, int]]:
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Tuple[int, int]]:
feats_vgg, sizes_vgg = self.vgg(x)
feat_dinov2, size_dinov2 = self.frozen_dinov2(x)
return feats_vgg + feat_dinov2, sizes_vgg + size_dinov2
diff --git a/kornia/feature/dedode/transformer/layers/drop_path.py b/kornia/feature/dedode/transformer/layers/drop_path.py
index 4d5574c31..f5c7ba7aa 100644
--- a/kornia/feature/dedode/transformer/layers/drop_path.py
+++ b/kornia/feature/dedode/transformer/layers/drop_path.py
@@ -26,10 +26,11 @@
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
from typing import Optional
-from kornia.core import Module, Tensor
+import torch
+from torch import nn
-def drop_path(x: Tensor, drop_prob: Optional[float] = 0.0, training: bool = False) -> Tensor:
+def drop_path(x: torch.Tensor, drop_prob: Optional[float] = 0.0, training: bool = False) -> torch.Tensor:
"""Apply stochastic depth sampling."""
if drop_prob is None:
drop_path = 0.0
@@ -44,12 +45,12 @@ def drop_path(x: Tensor, drop_prob: Optional[float] = 0.0, training: bool = Fals
return output
-class DropPath(Module):
+class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return drop_path(x, self.drop_prob, self.training)
diff --git a/kornia/feature/dedode/utils.py b/kornia/feature/dedode/utils.py
index 925606359..5608e65f3 100644
--- a/kornia/feature/dedode/utils.py
+++ b/kornia/feature/dedode/utils.py
@@ -20,13 +20,14 @@ from typing import Optional, Tuple, Union
import torch
import torch.nn.functional as F
-from kornia.core import Tensor
-
@torch.no_grad()
def sample_keypoints(
- scoremap: Tensor, num_samples: Optional[int] = 10_000, return_scoremap: bool = True, increase_coverage: bool = True
-) -> Union[Tensor, Tuple[Tensor, Tensor]]:
+ scoremap: torch.Tensor,
+ num_samples: Optional[int] = 10_000,
+ return_scoremap: bool = True,
+ increase_coverage: bool = True,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Sample keypoints from provided candidates."""
device = scoremap.device
dtype = scoremap.dtype
diff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.py
index bea6eda0b..cf3194795 100644
--- a/kornia/feature/dedode/vgg.py
+++ b/kornia/feature/dedode/vgg.py
@@ -20,12 +20,10 @@ from typing import Any, Dict, List, Optional, Union, cast
import torch
from torch import nn
-from kornia.core import Module
-
class VGG(nn.Module):
def __init__(
- self, features: Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5
+ self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5
) -> None:
super().__init__()
self.features = features
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index 296db7aec..444726a1c 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -20,8 +20,6 @@ from typing import Callable, Dict, List, Optional, Type
import torch
from torch import nn
-from kornia.core import Module, Tensor, concatenate, stack
-
urls: Dict[str, str] = {}
urls["defmo_encoder"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt"
urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt"
@@ -50,7 +48,7 @@ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, d
)
-class Bottleneck(Module):
+class Bottleneck(nn.Module):
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
@@ -64,11 +62,11 @@ class Bottleneck(Module):
inplanes: int,
planes: int,
stride: int = 1,
- downsample: Optional[Module] = None,
+ downsample: Optional[nn.Module] = None,
groups: int = 1,
base_width: int = 64,
dilation: int = 1,
- norm_layer: Optional[Callable[..., Module]] = None,
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
) -> None:
super().__init__()
if norm_layer is None:
@@ -85,7 +83,7 @@ class Bottleneck(Module):
self.downsample = downsample
self.stride = stride
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
identity = x
out = self.conv1(x)
@@ -108,7 +106,7 @@ class Bottleneck(Module):
return out
-class ResNet(Module):
+class ResNet(nn.Module):
def __init__(
self,
block: Type[Bottleneck],
@@ -118,7 +116,7 @@ class ResNet(Module):
groups: int = 1,
width_per_group: int = 64,
replace_stride_with_dilation: Optional[List[bool]] = None,
- norm_layer: Optional[Callable[..., Module]] = None,
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
) -> None:
super().__init__()
if norm_layer is None:
@@ -156,11 +154,11 @@ class ResNet(Module):
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
- # so that the residual branch starts with zeros, and each residual block behaves like an identity.
+ # so that the residual branch starts with torch.zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
- if isinstance(m, Bottleneck) and isinstance(m.bn3.weight, Tensor):
+ if isinstance(m, Bottleneck) and isinstance(m.bn3.weight, torch.Tensor):
nn.init.constant_(m.bn3.weight, 0)
def _make_layer(
@@ -198,7 +196,7 @@ class ResNet(Module):
return nn.Sequential(*layers)
- def _forward_impl(self, x: Tensor) -> Tensor:
+ def _forward_impl(self, x: torch.Tensor) -> torch.Tensor:
# See note [TorchScript super()]
x = self.conv1(x)
x = self.bn1(x)
@@ -216,11 +214,11 @@ class ResNet(Module):
return x
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return self._forward_impl(x)
-class EncoderDeFMO(Module):
+class EncoderDeFMO(nn.Module):
def __init__(self) -> None:
super().__init__()
model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50
@@ -229,11 +227,11 @@ class EncoderDeFMO(Module):
modelc1[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.net = nn.Sequential(modelc1, modelc2)
- def forward(self, input_data: Tensor) -> Tensor:
+ def forward(self, input_data: torch.Tensor) -> torch.Tensor:
return self.net(input_data)
-class RenderingDeFMO(Module):
+class RenderingDeFMO(nn.Module):
def __init__(self) -> None:
super().__init__()
self.tsr_steps: int = 24
@@ -256,7 +254,7 @@ class RenderingDeFMO(Module):
self.net = model
self.times = torch.linspace(0, 1, self.tsr_steps)
- def forward(self, latent: Tensor) -> Tensor:
+ def forward(self, latent: torch.Tensor) -> torch.Tensor:
times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1)
renders = []
for ki in range(times.shape[1]):
@@ -267,16 +265,16 @@ class RenderingDeFMO(Module):
.unsqueeze(-1)
.repeat(1, 1, latent.shape[2], latent.shape[3])
)
- latenti = concatenate((t_tensor, latent), 1)
+ latenti = torch.cat((t_tensor, latent), 1)
result = self.net(latenti)
renders.append(result)
- renders_stacked = stack(renders, 1).contiguous()
+ renders_stacked = torch.stack(renders, 1).contiguous()
renders_stacked[:, :, :4] = torch.sigmoid(renders_stacked[:, :, :4])
return renders_stacked
-class DeFMO(Module):
- """Module that disentangle a fast-moving object from the background and performs deblurring.
+class DeFMO(nn.Module):
+ """nn.Module that disentangle a fast-moving object from the background and performs deblurring.
This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery
of Fast Moving Objects". See :cite:`DeFMO2021` for more details.
@@ -315,7 +313,7 @@ class DeFMO(Module):
self.rendering.load_state_dict(pretrained_dict_ren, strict=True)
self.eval()
- def forward(self, input_data: Tensor) -> Tensor:
+ def forward(self, input_data: torch.Tensor) -> torch.Tensor:
latent = self.encoder(input_data)
x_out = self.rendering(latent)
return x_out
diff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.py
index 8c2db31cf..a4a1530dd 100644
--- a/kornia/feature/disk/_unets/blocks.py
+++ b/kornia/feature/disk/_unets/blocks.py
@@ -23,23 +23,21 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
-
-class TrivialUpsample(Module):
- def forward(self, x: Tensor) -> Tensor:
+class TrivialUpsample(nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
-class TrivialDownsample(Module):
- def forward(self, x: Tensor) -> Tensor:
+class TrivialDownsample(nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.avg_pool2d(x, 2)
class Conv(nn.Sequential):
def __init__(self, in_: int, out_: int, size: int, skip_norm_and_gate: bool = False) -> None:
- norm: Module
- nonl: Module
+ norm: nn.Module
+ nonl: nn.Module
if skip_norm_and_gate:
norm = nn.Sequential()
@@ -59,7 +57,7 @@ class ThinUnetDownBlock(nn.Sequential):
self.in_ = in_
self.out_ = out_
- downsample: Module
+ downsample: nn.Module
if is_first:
downsample = nn.Sequential()
conv = Conv(in_, out_, size, skip_norm_and_gate=True)
@@ -70,7 +68,7 @@ class ThinUnetDownBlock(nn.Sequential):
super().__init__(downsample, conv)
-class ThinUnetUpBlock(Module):
+class ThinUnetUpBlock(nn.Module):
def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5, setup: Any = None) -> None:
super().__init__()
@@ -82,7 +80,7 @@ class ThinUnetUpBlock(Module):
self.upsample = TrivialUpsample()
self.conv = Conv(self.cat_, self.out_, size)
- def forward(self, bot: Tensor, hor: Tensor) -> Tensor:
+ def forward(self, bot: torch.Tensor, hor: torch.Tensor) -> torch.Tensor:
bot_big = self.upsample(bot)
combined = torch.cat([bot_big, hor], dim=1)
diff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.py
index b8926adab..547d17ccb 100644
--- a/kornia/feature/disk/_unets/unet.py
+++ b/kornia/feature/disk/_unets/unet.py
@@ -19,14 +19,13 @@ from __future__ import annotations
from typing import Optional
+import torch
from torch import nn
-from kornia.core import Module, Tensor
-
from .blocks import ThinUnetDownBlock, ThinUnetUpBlock
-class Unet(Module):
+class Unet(nn.Module):
def __init__(
self, in_features: int = 1, up: Optional[list[int]] = None, down: Optional[list[int]] = None, size: int = 5
) -> None:
@@ -59,7 +58,7 @@ class Unet(Module):
for param in self.parameters():
self.n_params += param.numel()
- def forward(self, inp: Tensor) -> Tensor:
+ def forward(self, inp: torch.Tensor) -> torch.Tensor:
if inp.size(1) != self.in_features:
fmt = "Expected {} feature channels in input, got {}"
msg = fmt.format(self.in_features, inp.size(1))
@@ -70,7 +69,7 @@ class Unet(Module):
raise ValueError(
f"Input image shape must be divisible by {input_size_divisor} (got {inp.size()}). "
"This is not inherent to DISK, but to the U-Net architecture used in pretrained models. "
- "Please pad if necessary."
+ "Please F.pad if necessary."
)
features = [inp]
diff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.py
index 7f9b8a441..ab7340d50 100644
--- a/kornia/feature/disk/detector.py
+++ b/kornia/feature/disk/detector.py
@@ -22,12 +22,10 @@ from typing import Optional
import torch
import torch.nn.functional as F
-from kornia.core import Tensor
-
from .structs import Keypoints
-def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor:
+def nms(signal: torch.Tensor, window_size: int = 5, cutoff: float = 0.0) -> torch.Tensor:
"""Apply non-maximum suppression."""
if window_size % 2 != 1:
raise ValueError(f"window_size has to be odd, got {window_size}")
@@ -45,7 +43,7 @@ def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor:
def heatmap_to_keypoints(
- heatmap: Tensor, n: Optional[int] = None, window_size: int = 5, score_threshold: float = 0.0
+ heatmap: torch.Tensor, n: Optional[int] = None, window_size: int = 5, score_threshold: float = 0.0
) -> list[Keypoints]:
"""Inference-time nms-based detection protocol."""
heatmap = heatmap.squeeze(1)
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index ec380f8b8..de5635108 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -20,16 +20,16 @@ from __future__ import annotations
from typing import Optional
import torch
-
-from kornia.core import Module, Tensor
+import torch.nn.functional as F
+from torch import nn
from ._unets import Unet
from .detector import heatmap_to_keypoints
from .structs import DISKFeatures
-class DISK(Module):
- r"""Module which detects and described local features in an image using the DISK method.
+class DISK(nn.Module):
+ r"""nn.Module which detects and described local features in an image using the DISK method.
See :cite:`tyszkiewicz2020disk` for details.
@@ -39,7 +39,8 @@ class DISK(Module):
desc_dim: The dimension of the descriptor.
unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK
so this is only useful when using a custom checkpoint trained using the code released with the paper.
- The unet should take as input a tensor of shape :math:`(B, C, H, W)` and output a tensor of shape
+ The unet should take as input a torch.tensor of shape :math:`(B, C, H, W)` and output
+ a torch.tensor of shape
:math:`(B, \mathrm{desc\_dim} + 1, H, W)`.
Example:
@@ -49,7 +50,7 @@ class DISK(Module):
"""
- def __init__(self, desc_dim: int = 128, unet: None | Module = None) -> None:
+ def __init__(self, desc_dim: int = 128, unet: None | nn.Module = None) -> None:
super().__init__()
self.desc_dim = desc_dim
@@ -58,7 +59,7 @@ class DISK(Module):
unet = Unet(in_features=3, size=5, down=[16, 32, 64, 64, 64], up=[64, 64, 64, desc_dim + 1])
self.unet = unet
- def heatmap_and_dense_descriptors(self, images: Tensor) -> tuple[Tensor, Tensor]:
+ def heatmap_and_dense_descriptors(self, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Return the heatmap and the dense descriptors.
.. image:: _static/img/DISK.png
@@ -68,7 +69,7 @@ class DISK(Module):
Returns:
A tuple of dense detection scores and descriptors.
- Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, where
+ Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, torch.where
:math:`D` is the descriptor dimension.
"""
@@ -86,7 +87,7 @@ class DISK(Module):
def forward(
self,
- images: Tensor,
+ images: torch.Tensor,
n: Optional[int] = None,
window_size: int = 5,
score_threshold: float = 0.0,
@@ -111,7 +112,7 @@ class DISK(Module):
h, w = images.shape[2:]
pd_h = 16 - h % 16 if h % 16 > 0 else 0
pd_w = 16 - w % 16 if w % 16 > 0 else 0
- images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)
+ images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)
heatmaps, descriptors = self.heatmap_and_dense_descriptors(images)
if pad_if_not_divisible:
@@ -131,8 +132,8 @@ class DISK(Module):
r"""Load a pretrained model.
Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints
- only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and
- is less precise but detects keypoints everywhere where they are matchable. The difference is especially
+ only torch.where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and
+ is less precise but detects keypoints everywhere torch.where they are matchable. The difference is especially
pronounced on thin structures and on edges of objects.
Args:
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 944acb3c6..c23fdedae 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -18,12 +18,11 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Union
+import torch
import torch.nn.functional as F
-from kornia.core import Device, Tensor
-
@dataclass
class DISKFeatures:
@@ -32,38 +31,38 @@ class DISKFeatures:
Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched.
Args:
- keypoints: Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints.
- descriptors: Tensor of shape :math:`(N, D)`, where :math:`D` is the descriptor dimension.
- detection_scores: Tensor of shape :math:`(N,)` where the detection score can be interpreted as
+ keypoints: torch.Tensor of shape :math:`(N, 2)`, torch.where :math:`N` is the number of keypoints.
+ descriptors: torch.Tensor of shape :math:`(N, D)`, torch.where :math:`D` is the descriptor dimension.
+ detection_scores: torch.Tensor of shape :math:`(N,)` torch.where the detection score can be interpreted as
the log-probability of keeping a keypoint after it has been proposed (see the paper
section *Method β†’ Feature distribution* for details).
"""
- keypoints: Tensor
- descriptors: Tensor
- detection_scores: Tensor
+ keypoints: torch.Tensor
+ descriptors: torch.Tensor
+ detection_scores: torch.Tensor
@property
def n(self) -> int:
return self.keypoints.shape[0]
@property
- def device(self) -> Device:
+ def device(self) -> Union[str, torch.device, None]:
return self.keypoints.device
@property
- def x(self) -> Tensor:
+ def x(self) -> torch.Tensor:
"""Accesses the x coordinates of keypoints (along image width)."""
return self.keypoints[:, 0]
@property
- def y(self) -> Tensor:
+ def y(self) -> torch.Tensor:
"""Accesses the y coordinates of keypoints (along image height)."""
return self.keypoints[:, 1]
def to(self, *args: Any, **kwargs: Any) -> DISKFeatures:
- """Call :func:`torch.Tensor.to` on each tensor to move the keypoints, descriptors and detection scores to
+ """Call :func:`torch.Tensor.to` on each torch.tensor to move the keypoints, descriptors and detection scores to
the specified device and/or data type.
Args:
@@ -88,11 +87,11 @@ class Keypoints:
After construction, merge_with_descriptors is used to select corresponding descriptors from unet output.
"""
- xys: Tensor
- detection_logp: Tensor
+ xys: torch.Tensor
+ detection_logp: torch.Tensor
- def merge_with_descriptors(self, descriptors: Tensor) -> DISKFeatures:
- """Select descriptors from a dense `descriptors` tensor, at locations given by `self.xys`."""
+ def merge_with_descriptors(self, descriptors: torch.Tensor) -> DISKFeatures:
+ """Select descriptors from a dense `descriptors` torch.tensor, at locations given by `self.xys`."""
dtype = descriptors.dtype
x, y = self.xys.T
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 5fda81ca1..cdf45faaa 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -20,15 +20,13 @@ from typing import Dict
import torch
from torch import nn
-from kornia.core import Module, Parameter, Tensor, tensor, zeros
-
urls: Dict[str, str] = {}
urls["liberty"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth" # pylint: disable
urls["notredame"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth" # pylint: disable
urls["yosemite"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable
-class FilterResponseNorm2d(Module):
+class FilterResponseNorm2d(nn.Module):
r"""Feature Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence
in the Training of Deep Neural Networks', see :cite:`FRN2019` for more details.
@@ -69,12 +67,12 @@ class FilterResponseNorm2d(Module):
self.is_bias = is_bias
self.is_scale = is_scale
- self.weight = Parameter(torch.ones(1, num_features, 1, 1), requires_grad=True)
- self.bias = Parameter(zeros(1, num_features, 1, 1), requires_grad=True)
+ self.weight = nn.Parameter(torch.ones(1, num_features, 1, 1), requires_grad=True)
+ self.bias = nn.Parameter(torch.zeros(1, num_features, 1, 1), requires_grad=True)
if is_eps_leanable:
- self.eps = Parameter(tensor(1), requires_grad=True)
+ self.eps = nn.Parameter(torch.tensor(1), requires_grad=True)
else:
- self.register_buffer("eps", tensor([eps]))
+ self.register_buffer("eps", torch.tensor([eps]))
self.reset_parameters()
def reset_parameters(self) -> None:
@@ -86,7 +84,7 @@ class FilterResponseNorm2d(Module):
def extra_repr(self) -> str:
return "num_features={num_features}, eps={init_eps}".format(**self.__dict__)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
# Compute the mean norm of activations per channel.
nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)
@@ -101,7 +99,7 @@ class FilterResponseNorm2d(Module):
return x
-class TLU(Module):
+class TLU(nn.Module):
r"""TLU layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep
Neural Networks, see :cite:`FRN2019` for more details. :math:`{\tau}` is learnable per channel.
@@ -124,7 +122,7 @@ class TLU(Module):
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau."""
super().__init__()
self.num_features = num_features
- self.tau = Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
+ self.tau = nn.Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
self.reset_parameters()
def reset_parameters(self) -> None:
@@ -134,12 +132,12 @@ class TLU(Module):
def extra_repr(self) -> str:
return "num_features={num_features}".format(**self.__dict__)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.max(x, self.tau)
-class HyNet(Module):
- r"""Module, which computes HyNet descriptors of given grayscale patches of 32x32.
+class HyNet(nn.Module):
+ r"""nn.Module, which computes HyNet descriptors of given grayscale patches of 32x32.
This is based on the original code from paper
"HyNet: Learning Local Descriptor with Hybrid Similarity Measure and Triplet Loss".
@@ -232,7 +230,7 @@ class HyNet(Module):
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 9330aedba..d22e00ca4 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -16,13 +16,13 @@
#
import warnings
-from typing import ClassVar, Dict, List, Optional, Tuple
+from typing import ClassVar, Dict, List, Optional, Tuple, Union
import torch
+from torch import nn
from kornia.color import rgb_to_grayscale
from kornia.constants import pi
-from kornia.core import Device, Module, Tensor, concatenate, deg2rad
from kornia.core.check import KORNIA_CHECK_LAF
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
@@ -45,8 +45,12 @@ from .siftdesc import SIFTDescriptor
def get_laf_descriptors(
- img: Tensor, lafs: Tensor, patch_descriptor: Module, patch_size: int = 32, grayscale_descriptor: bool = True
-) -> Tensor:
+ img: torch.Tensor,
+ lafs: torch.Tensor,
+ patch_descriptor: nn.Module,
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True,
+) -> torch.Tensor:
r"""Get local descriptors, corresponding to LAFs (keypoints).
Args:
@@ -58,29 +62,29 @@ def get_laf_descriptors(
grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image.
Returns:
- Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+ Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
"""
KORNIA_CHECK_LAF(lafs)
patch_descriptor = patch_descriptor.to(img)
patch_descriptor.eval()
- timg: Tensor = img
+ timg: torch.Tensor = img
if lafs.shape[1] == 0:
- warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty tensor", stacklevel=1)
+ warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.tensor", stacklevel=1)
return torch.empty(lafs.shape[0], lafs.shape[1], 128, dtype=lafs.dtype, device=lafs.device)
if grayscale_descriptor and img.size(1) == 3:
timg = rgb_to_grayscale(img)
- patches: Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)
- # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ patches: torch.Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)
+ # Descriptor accepts standard torch.tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
B, N, CH, H, W = patches.size()
return patch_descriptor(patches.view(B * N, CH, H, W)).view(B, N, -1)
-class LAFDescriptor(Module):
- r"""Module to get local descriptors, corresponding to LAFs (keypoints).
+class LAFDescriptor(nn.Module):
+ r"""nn.Module to get local descriptors, corresponding to LAFs (keypoints).
Internally uses :func:`~kornia.feature.get_laf_descriptors`.
@@ -93,7 +97,10 @@ class LAFDescriptor(Module):
"""
def __init__(
- self, patch_descriptor_module: Optional[Module] = None, patch_size: int = 32, grayscale_descriptor: bool = True
+ self,
+ patch_descriptor_module: Optional[nn.Module] = None,
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True,
) -> None:
super().__init__()
if patch_descriptor_module is None:
@@ -110,7 +117,7 @@ class LAFDescriptor(Module):
f"grayscale_descriptor='{self.grayscale_descriptor})"
)
- def forward(self, img: Tensor, lafs: Tensor) -> Tensor:
+ def forward(self, img: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:
r"""Three stage local feature detection.
First the location and scale of interest points are determined by
@@ -121,14 +128,14 @@ class LAFDescriptor(Module):
lafs: local affine frames :math:`(B,N,2,3)`.
Returns:
- Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+ Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
"""
return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor)
-class LocalFeature(Module):
- """Module, which combines local feature detector and descriptor.
+class LocalFeature(nn.Module):
+ """nn.Module, which combines local feature detector and descriptor.
Args:
detector: the detection module.
@@ -137,7 +144,7 @@ class LocalFeature(Module):
"""
- def __init__(self, detector: Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:
+ def __init__(self, detector: nn.Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:
super().__init__()
self.detector = detector
self.descriptor = descriptor
@@ -145,18 +152,20 @@ class LocalFeature(Module):
raise ValueError(f"Scaling coef should be >= 0, got {scaling_coef}")
self.scaling_coef = scaling_coef
- def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
+ def forward(
+ self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run forward.
Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
- mask: a mask with weights where to apply the response function.
+ mask: a mask with weights torch.where to apply the response function.
The shape must be the same as the input image.
Returns:
- Detected local affine frames with shape :math:`(B,N,2,3)`.
- Response function values for corresponding lafs with shape :math:`(B,N,1)`.
- - Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+ - Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
"""
lafs, responses = self.detector(img, mask)
@@ -178,7 +187,7 @@ class SIFTFeature(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
config: Optional[Detector_config] = None,
) -> None:
patch_size: int = 41
@@ -212,7 +221,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
) -> None:
if device is None:
device = torch.device("cpu")
@@ -240,7 +249,7 @@ class GFTTAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
config: Optional[Detector_config] = None,
) -> None:
if device is None:
@@ -265,7 +274,7 @@ class HesAffNetHardNet(LocalFeature):
self,
num_features: int = 2048,
upright: bool = False,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
config: Optional[Detector_config] = None,
) -> None:
if device is None:
@@ -290,7 +299,7 @@ class KeyNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
scale_laf: float = 1.0,
) -> None:
if device is None:
@@ -311,7 +320,7 @@ class KeyNetAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Optional[Device] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
scale_laf: float = 1.0,
) -> None:
if device is None:
@@ -327,15 +336,15 @@ class KeyNetAffNetHardNet(LocalFeature):
super().__init__(detector, descriptor, scale_laf)
-class LocalFeatureMatcher(Module):
- r"""Module, which finds correspondences between two images based on local features.
+class LocalFeatureMatcher(nn.Module):
+ r"""nn.Module, which finds correspondences between two images based on local features.
Args:
local_feature: Local feature detector. See :class:`~kornia.feature.GFTTAffNetHardNet`.
matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`.
Returns:
- Dict[str, Tensor]: Dictionary with image correspondences and confidence scores.
+ Dict[str, torch.Tensor]: Dictionary with image correspondences and confidence scores.
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
@@ -348,18 +357,18 @@ class LocalFeatureMatcher(Module):
"""
- def __init__(self, local_feature: Module, matcher: Module) -> None:
+ def __init__(self, local_feature: nn.Module, matcher: nn.Module) -> None:
super().__init__()
self.local_feature = local_feature
self.matcher = matcher
self.eval()
- def extract_features(self, image: Tensor, mask: Optional[Tensor] = None) -> Dict[str, Tensor]:
+ def extract_features(self, image: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
"""Extract features from simple image."""
lafs0, resps0, descs0 = self.local_feature(image, mask)
return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
- def no_match_output(self, device: Device, dtype: torch.dtype) -> Dict[str, Tensor]:
+ def no_match_output(self, device: Union[str, torch.device, None], dtype: torch.dtype) -> Dict[str, torch.Tensor]:
return {
"keypoints0": torch.empty(0, 2, device=device, dtype=dtype),
"keypoints1": torch.empty(0, 2, device=device, dtype=dtype),
@@ -369,7 +378,7 @@ class LocalFeatureMatcher(Module):
"batch_indexes": torch.empty(0, device=device, dtype=torch.long),
}
- def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
+ def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""Run forward.
Args:
@@ -394,26 +403,26 @@ class LocalFeatureMatcher(Module):
if ("lafs0" not in data.keys()) or ("descriptors0" not in data.keys()):
# One can supply pre-extracted local features
- feats_dict0: Dict[str, Tensor] = self.extract_features(data["image0"])
+ feats_dict0: Dict[str, torch.Tensor] = self.extract_features(data["image0"])
lafs0, descs0 = feats_dict0["lafs"], feats_dict0["descriptors"]
else:
lafs0, descs0 = data["lafs0"], data["descriptors0"]
if ("lafs1" not in data.keys()) or ("descriptors1" not in data.keys()):
- feats_dict1: Dict[str, Tensor] = self.extract_features(data["image1"])
+ feats_dict1: Dict[str, torch.Tensor] = self.extract_features(data["image1"])
lafs1, descs1 = feats_dict1["lafs"], feats_dict1["descriptors"]
else:
lafs1, descs1 = data["lafs1"], data["descriptors1"]
- keypoints0: Tensor = get_laf_center(lafs0)
- keypoints1: Tensor = get_laf_center(lafs1)
+ keypoints0: torch.Tensor = get_laf_center(lafs0)
+ keypoints1: torch.Tensor = get_laf_center(lafs1)
- out_keypoints0: List[Tensor] = []
- out_keypoints1: List[Tensor] = []
- out_confidence: List[Tensor] = []
- out_batch_indexes: List[Tensor] = []
- out_lafs0: List[Tensor] = []
- out_lafs1: List[Tensor] = []
+ out_keypoints0: List[torch.Tensor] = []
+ out_keypoints1: List[torch.Tensor] = []
+ out_confidence: List[torch.Tensor] = []
+ out_batch_indexes: List[torch.Tensor] = []
+ out_lafs0: List[torch.Tensor] = []
+ out_lafs1: List[torch.Tensor] = []
for batch_idx in range(num_image_pairs):
dists, idxs = self.matcher(descs0[batch_idx], descs1[batch_idx])
@@ -437,12 +446,12 @@ class LocalFeatureMatcher(Module):
return self.no_match_output(data["image0"].device, data["image0"].dtype)
return {
- "keypoints0": concatenate(out_keypoints0, dim=0).view(-1, 2),
- "keypoints1": concatenate(out_keypoints1, dim=0).view(-1, 2),
- "lafs0": concatenate(out_lafs0, dim=0).view(1, -1, 2, 3),
- "lafs1": concatenate(out_lafs1, dim=0).view(1, -1, 2, 3),
- "confidence": concatenate(out_confidence, dim=0).view(-1),
- "batch_indexes": concatenate(out_batch_indexes, dim=0).view(-1),
+ "keypoints0": torch.cat(out_keypoints0, dim=0).view(-1, 2),
+ "keypoints1": torch.cat(out_keypoints1, dim=0).view(-1, 2),
+ "lafs0": torch.cat(out_lafs0, dim=0).view(1, -1, 2, 3),
+ "lafs1": torch.cat(out_lafs1, dim=0).view(1, -1, 2, 3),
+ "confidence": torch.cat(out_confidence, dim=0).view(-1),
+ "batch_indexes": torch.cat(out_batch_indexes, dim=0).view(-1),
}
@@ -481,13 +490,13 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
def forward(
self,
- desc1: Tensor,
- desc2: Tensor,
- lafs1: Tensor,
- lafs2: Tensor,
+ desc1: torch.Tensor,
+ desc2: torch.Tensor,
+ lafs1: torch.Tensor,
+ lafs2: torch.Tensor,
hw1: Optional[Tuple[int, int]] = None,
hw2: Optional[Tuple[int, int]] = None,
- ) -> Tuple[Tensor, Tensor]:
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
"""Run forward.
Args:
@@ -500,8 +509,8 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
"""
if (desc1.shape[0] < 2) or (desc2.shape[0] < 2):
@@ -521,9 +530,9 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
hw2_ = keypoints2.max(dim=1)[0].squeeze().flip(0)
else:
hw2_ = torch.tensor(hw2, device=dev)
- ori0 = deg2rad(get_laf_orientation(lafs1).reshape(1, -1))
+ ori0 = torch.deg2rad(get_laf_orientation(lafs1).reshape(1, -1))
ori0[ori0 < 0] += 2.0 * pi
- ori1 = deg2rad(get_laf_orientation(lafs2).reshape(1, -1))
+ ori1 = torch.deg2rad(get_laf_orientation(lafs2).reshape(1, -1))
ori1[ori1 < 0] += 2.0 * pi
input_dict = {
"image0": {
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index b22a0a29e..8837f8ef0 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -22,7 +22,6 @@ import torch.nn.functional as F
from torch import nn
from typing_extensions import TypedDict
-from kornia.core import Module, Tensor, concatenate
from kornia.filters import SpatialGradient
from kornia.geometry.transform import pyrdown
@@ -48,7 +47,7 @@ keynet_default_config: KeyNet_conf = {
KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
-class _FeatureExtractor(Module):
+class _FeatureExtractor(nn.Module):
"""Helper class for KeyNet.
It loads both, the handcrafted and learnable blocks
@@ -60,20 +59,20 @@ class _FeatureExtractor(Module):
self.hc_block = _HandcraftedBlock()
self.lb_block = _LearnableBlock()
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
x_hc = self.hc_block(x)
x_lb = self.lb_block(x_hc)
return x_lb
-class _HandcraftedBlock(Module):
+class _HandcraftedBlock(nn.Module):
"""Helper class for KeyNet, it defines the handcrafted filters within the Key.Net handcrafted block."""
def __init__(self) -> None:
super().__init__()
self.spatial_gradient = SpatialGradient("sobel", 1)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
sobel = self.spatial_gradient(x)
dx, dy = sobel[:, :, 0, :, :], sobel[:, :, 1, :, :]
@@ -83,7 +82,7 @@ class _HandcraftedBlock(Module):
sobel_dy = self.spatial_gradient(dy)
dyy = sobel_dy[:, :, 1, :, :]
- hc_feats = concatenate([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], 1)
+ hc_feats = torch.cat([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], 1)
return hc_feats
@@ -101,7 +100,7 @@ class _LearnableBlock(nn.Sequential):
self.conv1 = _KeyNetConvBlock()
self.conv2 = _KeyNetConvBlock()
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv2(self.conv1(self.conv0(x)))
return x
@@ -125,7 +124,7 @@ def _KeyNetConvBlock(
)
-class KeyNet(Module):
+class KeyNet(nn.Module):
"""Key.Net model definition -- local feature detector (response function).
This is based on the original code
@@ -168,16 +167,16 @@ class KeyNet(Module):
self.load_state_dict(pretrained_dict["state_dict"], strict=True)
self.eval()
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
"""X - input image."""
shape_im = x.shape
- feats: List[Tensor] = [self.feature_extractor(x)]
+ feats: List[torch.Tensor] = [self.feature_extractor(x)]
for _ in range(1, self.num_levels):
x = pyrdown(x, factor=1.2)
feats_i = self.feature_extractor(x)
feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode="bilinear")
feats.append(feats_i)
- scores = self.last_conv(concatenate(feats, 1))
+ scores = self.last_conv(torch.cat(feats, 1))
return scores
@@ -206,8 +205,8 @@ class KeyNetDetector(MultiResolutionDetector):
pretrained: bool = False,
num_features: int = 2048,
keynet_conf: KeyNet_conf = keynet_default_config,
- ori_module: Optional[Module] = None,
- aff_module: Optional[Module] = None,
+ ori_module: Optional[nn.Module] = None,
+ aff_module: Optional[nn.Module] = None,
) -> None:
model = KeyNet(pretrained, keynet_conf)
super().__init__(model, num_features, keynet_conf["Detector_conf"], ori_module, aff_module)
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 3a66bd977..41aacafef 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -21,14 +21,13 @@ from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, cos, sin, stack, tensor, zeros
from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
-from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg
+from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
-def get_laf_scale(LAF: Tensor) -> Tensor:
+def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
"""Return a scale of the LAFs.
Args:
@@ -48,7 +47,7 @@ def get_laf_scale(LAF: Tensor) -> Tensor:
return out.abs().sqrt()
-def get_laf_center(LAF: Tensor) -> Tensor:
+def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
"""Return a center (keypoint) of the LAFs.
The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.
@@ -69,7 +68,7 @@ def get_laf_center(LAF: Tensor) -> Tensor:
return out
-def get_laf_orientation(LAF: Tensor) -> Tensor:
+def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
"""Return orientation of the LAFs, in degrees.
Args:
@@ -85,10 +84,10 @@ def get_laf_orientation(LAF: Tensor) -> Tensor:
"""
KORNIA_CHECK_LAF(LAF)
angle_rad = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])
- return rad2deg(angle_rad).unsqueeze(-1)
+ return torch.rad2deg(angle_rad).unsqueeze(-1)
-def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
+def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
"""Apply additional rotation to the LAFs.
Compared to `set_laf_orientation`, the resulting rotation is original LAF orientation plus angles_degrees.
@@ -109,7 +108,7 @@ def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
return out_laf
-def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
+def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
"""Change the orientation of the LAFs.
Args:
@@ -126,7 +125,9 @@ def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
return rotate_laf(LAF, angles_degrees - ori)
-def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: Optional[Tensor] = None) -> Tensor:
+def laf_from_center_scale_ori(
+ xy: torch.Tensor, scale: Optional[torch.Tensor] = None, ori: Optional[torch.Tensor] = None
+) -> torch.Tensor:
"""Create a LAF from keypoint center, scale and orientation.
Useful to create kornia LAFs from OpenCV keypoints.
@@ -147,22 +148,22 @@ def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: O
if scale is None:
scale = torch.ones(B, N, 1, 1, device=device, dtype=dtype)
if ori is None:
- ori = zeros(B, N, 1, device=device, dtype=dtype)
+ ori = torch.zeros(B, N, 1, device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(scale, ["B", "N", "1", "1"])
KORNIA_CHECK_SHAPE(ori, ["B", "N", "1"])
- unscaled_laf = concatenate([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
+ unscaled_laf = torch.cat([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
laf = scale_laf(unscaled_laf, scale)
return laf
-def scale_laf(laf: Tensor, scale_coef: Union[float, Tensor]) -> Tensor:
+def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:
"""Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.
So the center, shape and orientation of the local feature stays the same, but the region area changes.
Args:
laf: :math:`(B, N, 2, 3)`
- scale_coef: broadcastable tensor or float.
+ scale_coef: broadcastable torch.tensor or float.
Returns:
LAF :math:`(B, N, 2, 3)`
@@ -173,14 +174,14 @@ def scale_laf(laf: Tensor, scale_coef: Union[float, Tensor]) -> Tensor:
>>> output = scale_laf(input, scale) # BxNx2x3
"""
- if not isinstance(scale_coef, (float, Tensor)):
- raise TypeError(f"scale_coef should be float or Tensor. Got {type(scale_coef)}")
+ if not isinstance(scale_coef, (float, torch.Tensor)):
+ raise TypeError(f"scale_coef should be float or torch.Tensor. Got {type(scale_coef)}")
KORNIA_CHECK_LAF(laf)
centerless_laf = laf[:, :, :2, :2]
- return concatenate([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
+ return torch.cat([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
-def make_upright(laf: Tensor, eps: float = 1e-9) -> Tensor:
+def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""Rectify the affine matrix, so that it becomes upright.
Args:
@@ -201,19 +202,19 @@ def make_upright(laf: Tensor, eps: float = 1e-9) -> Tensor:
# The function is equivalent to doing 2x2 SVD and resetting rotation
# matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.
b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + eps
- laf1_ell = concatenate([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)
- laf2_ell = concatenate(
+ laf1_ell = torch.cat([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)
+ laf2_ell = torch.cat(
[
((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] + laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)),
(det / b2a2).contiguous(),
],
dim=3,
)
- laf_unit_scale = concatenate([concatenate([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
+ laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
return scale_laf(laf_unit_scale, scale)
-def ellipse_to_laf(ells: Tensor) -> Tensor:
+def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
"""Convert ellipse regions to LAF format.
Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected
@@ -222,7 +223,7 @@ def ellipse_to_laf(ells: Tensor) -> Tensor:
See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m
Args:
- ells: tensor :math:`(B, N, 5)` of ellipses in Oxford format [x y a b c].
+ ells: torch.tensor :math:`(B, N, 5)` of ellipses in Oxford format [x y a b c].
Returns:
LAF :math:`(B, N, 2, 3)`
@@ -235,8 +236,8 @@ def ellipse_to_laf(ells: Tensor) -> Tensor:
KORNIA_CHECK_SHAPE(ells, ["B", "N", "5"])
B, N, _ = ells.shape
# Previous implementation was incorrectly using Cholesky decomp as matrix sqrt
- # ell_shape = concatenate([concatenate([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
- # concatenate([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
+ # ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
+ # torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
# out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)
# We will calculate 2x2 matrix square root via special case formula
@@ -250,12 +251,12 @@ def ellipse_to_laf(ells: Tensor) -> Tensor:
a12 = torch.zeros_like(a11)
a22 = ells[..., 4:5].abs().sqrt()
a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9)
- A = stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()
- out = concatenate([A, ells[..., :2].view(B, N, 2, 1)], dim=3)
+ A = torch.stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()
+ out = torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3)
return out
-def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
+def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
"""Convert LAFs to boundary points of the regions + center.
Used for local features visualization, see visualize_laf function.
@@ -265,29 +266,29 @@ def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
n_pts: number of points to output.
Returns:
- tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
+ torch.tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
"""
KORNIA_CHECK_LAF(LAF)
B, N, _, _ = LAF.size()
- pts = concatenate(
+ pts = torch.cat(
[
- sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
- cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
+ torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
+ torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
torch.ones(n_pts - 1, 1),
],
dim=1,
)
# Add origin to draw also the orientation
- pts = concatenate([tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
+ pts = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
pts = pts.to(LAF.device).to(LAF.dtype)
- aux = tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
- HLAF = concatenate([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
+ aux = torch.tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
+ HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)
return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
-def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]:
+def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]:
"""Return list for drawing LAFs (local features).
Args:
@@ -312,8 +313,8 @@ def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[
return (pts_np[..., 0].tolist(), pts_np[..., 1].tolist())
-def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
- """De-normalize LAFs from scale to image scale.
+def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
+ """De-F.normalize LAFs from scale to image scale.
The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.
@@ -344,7 +345,7 @@ def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
return coef.expand_as(LAF) * LAF
-def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
+def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
"""Normalize LAFs to [0,1] scale from pixel scale.
See below:
@@ -375,11 +376,11 @@ def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
return coef.expand_as(LAF) * LAF
-def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int = 32) -> Tensor:
+def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor:
"""Generate affine grid.
Args:
- img: image tensor of shape :math:`(B, CH, H, W)`.
+ img: image torch.tensor of shape :math:`(B, CH, H, W)`.
LAF: laf with shape :math:`(B, N, 2, 3)`.
PS: patch size to be extracted.
@@ -402,9 +403,9 @@ def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int =
def extract_patches_simple(
- img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
-) -> Tensor:
- """Extract patches defined by LAFs from image tensor.
+ img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> torch.Tensor:
+ """Extract patches defined by LAFs from image torch.tensor.
No smoothing applied, huge aliasing (better use extract_patches_from_pyramid).
@@ -434,13 +435,13 @@ def extract_patches_simple(
img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
)
)
- return concatenate(out, dim=0).view(B, N, ch, PS, PS)
+ return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
def extract_patches_from_pyramid(
- img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
-) -> Tensor:
- """Extract patches defined by LAFs from image tensor.
+ img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> torch.Tensor:
+ """Extract patches defined by LAFs from image torch.tensor.
Patches are extracted from appropriate pyramid level.
@@ -489,7 +490,7 @@ def extract_patches_from_pyramid(
return out
-def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor:
+def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:
"""Check if the LAF is touching or partly outside the image boundary.
Returns the mask of LAFs, which are fully inside the image, i.e. valid.
@@ -513,7 +514,7 @@ def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor:
return good_lafs_mask
-def laf_to_three_points(laf: Tensor) -> Tensor:
+def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:
"""Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector,
LAF-y unit vector.
@@ -525,11 +526,11 @@ def laf_to_three_points(laf: Tensor) -> Tensor:
""" # noqa:D205
KORNIA_CHECK_LAF(laf)
- three_pts = stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
+ three_pts = torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
return three_pts
-def laf_from_three_points(threepts: Tensor) -> Tensor:
+def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:
"""Convert three points to local affine frame.
Order is (0,0), (0, 1), (1, 0).
@@ -541,19 +542,21 @@ def laf_from_three_points(threepts: Tensor) -> Tensor:
laf :math:`(B, N, 2, 3)`.
"""
- laf = stack([threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1)
+ laf = torch.stack(
+ [threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1
+ )
return laf
-def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor:
+def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:
r"""Apply perspective transformations to a set of local affine frames (LAFs).
Args:
- trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`.
- lafs_1: tensor of lafs of shape :math:`(B, N, 2, 3)`.
+ trans_01: torch.tensor for perspective transformations of shape :math:`(B, 3, 3)`.
+ lafs_1: torch.tensor of lafs of shape :math:`(B, N, 2, 3)`.
Returns:
- tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.
+ torch.tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.
Examples:
>>> rng = torch.manual_seed(0)
@@ -591,10 +594,10 @@ def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor:
"""
KORNIA_CHECK_LAF(lafs_1)
if not torch.is_tensor(trans_01):
- raise TypeError("Input type is not a Tensor")
+ raise TypeError("Input type is not a torch.Tensor")
if not trans_01.device == lafs_1.device:
- raise TypeError("Tensor must be in the same device")
+ raise TypeError("torch.Tensor must be in the same device")
if not trans_01.shape[0] == lafs_1.shape[0]:
raise ValueError("Input batch size must be the same for both tensors")
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 8bdacc1cc..79c3b87ce 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -25,21 +25,6 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import (
- Module,
- ModuleList,
- Tensor,
- arange,
- concatenate,
- cos,
- einsum,
- ones,
- ones_like,
- sin,
- stack,
- where,
- zeros,
-)
from kornia.core.check import KORNIA_CHECK
from kornia.feature.laf import laf_to_three_points, scale_laf
from kornia.utils._compat import custom_fwd
@@ -61,8 +46,8 @@ def math_clamp(x, min_, max_): # type: ignore
@custom_fwd(cast_inputs=torch.float32)
-def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor:
- """Normalize tensor of keypoints."""
+def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
+ """Normalize torch.tensor of keypoints."""
if isinstance(size, torch.Size):
size = torch.tensor(size)[None]
shift = size.float().to(kpts) / 2
@@ -71,30 +56,30 @@ def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor:
return kpts
-def pad_to_length(x: Tensor, length: int) -> Tuple[Tensor, Tensor]:
- """Pad tensor to desired length."""
+def pad_to_length(x: torch.Tensor, length: int) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Pad torch.tensor to desired length."""
if length <= x.shape[-2]:
- return x, ones_like(x[..., :1], dtype=torch.bool)
- pad = ones(*x.shape[:-2], length - x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
- y = concatenate([x, pad], dim=-2)
- mask = zeros(*y.shape[:-1], 1, dtype=torch.bool, device=x.device)
+ return x, torch.ones_like(x[..., :1], dtype=torch.bool)
+ pad_tensor = torch.ones(*x.shape[:-2], length - x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
+ y = torch.cat([x, pad_tensor], dim=-2)
+ mask = torch.zeros(*y.shape[:-1], 1, dtype=torch.bool, device=x.device)
mask[..., : x.shape[-2], :] = True
return y, mask
-def rotate_half(x: Tensor) -> Tensor:
+def rotate_half(x: torch.Tensor) -> torch.Tensor:
"""Apply half rotation."""
x = x.unflatten(-1, (-1, 2))
x1, x2 = x.unbind(dim=-1)
- return stack((-x2, x1), dim=-1).flatten(start_dim=-2)
+ return torch.stack((-x2, x1), dim=-1).flatten(start_dim=-2)
-def apply_cached_rotary_emb(freqs: Tensor, t: Tensor) -> Tensor:
+def apply_cached_rotary_emb(freqs: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""Apply rotary embedding."""
return (t * freqs[0]) + (rotate_half(t) * freqs[1])
-class LearnableFourierPositionalEncoding(Module):
+class LearnableFourierPositionalEncoding(nn.Module):
def __init__(self, M: int, dim: int, F_dim: Optional[int] = None, gamma: float = 1.0) -> None:
super().__init__()
F_dim = F_dim if F_dim is not None else dim
@@ -102,20 +87,20 @@ class LearnableFourierPositionalEncoding(Module):
self.Wr = nn.Linear(M, F_dim // 2, bias=False)
nn.init.normal_(self.Wr.weight.data, mean=0, std=self.gamma**-2)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Encode position vector."""
projected = self.Wr(x)
- cosines, sines = cos(projected), sin(projected)
- emb = stack([cosines, sines], 0).unsqueeze(-3)
+ cosines, sines = torch.cos(projected), torch.sin(projected)
+ emb = torch.stack([cosines, sines], 0).unsqueeze(-3)
return emb.repeat_interleave(2, dim=-1)
-class TokenConfidence(Module):
+class TokenConfidence(nn.Module):
def __init__(self, dim: int) -> None:
super().__init__()
self.token = nn.Sequential(nn.Linear(dim, 1), nn.Sigmoid())
- def forward(self, desc0: Tensor, desc1: Tensor) -> Tuple[Tensor, Tensor]:
+ def forward(self, desc0: torch.Tensor, desc1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Get confidence tokens."""
dtype = self.token[0].weight.dtype
orig_dtype = desc0.dtype
@@ -125,7 +110,7 @@ class TokenConfidence(Module):
)
-class Attention(Module):
+class Attention(nn.Module):
def __init__(self, allow_flash: bool) -> None:
super().__init__()
if allow_flash and not FLASH_AVAILABLE:
@@ -140,7 +125,9 @@ class Attention(Module):
if self.has_sdp:
torch.backends.cuda.enable_flash_sdp(allow_flash)
- def forward(self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None) -> Tensor:
+ def forward(
+ self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
if self.enable_flash and q.device.type == "cuda":
# use torch 2.0 scaled_dot_product_attention with flash
if self.has_sdp:
@@ -150,7 +137,7 @@ class Attention(Module):
else:
KORNIA_CHECK(mask is None)
q, k, v = (x.transpose(-2, -3).contiguous() for x in [q, k, v])
- m = self.flash_(q.half(), stack([k, v], 2).half())
+ m = self.flash_(q.half(), torch.stack([k, v], 2).half())
return m.transpose(-2, -3).to(q.dtype).clone()
elif self.has_sdp:
args = [x.contiguous() for x in [q, k, v]]
@@ -158,14 +145,14 @@ class Attention(Module):
return v if mask is None else v.nan_to_num()
else:
s = q.shape[-1] ** -0.5
- sim = einsum("...id,...jd->...ij", q, k) * s
+ sim = torch.einsum("...id,...jd->...ij", q, k) * s
if mask is not None:
sim.masked_fill(~mask, -float("inf"))
attn = F.softmax(sim, -1)
- return einsum("...ij,...jd->...id", attn, v)
+ return torch.einsum("...ij,...jd->...id", attn, v)
-class SelfBlock(Module):
+class SelfBlock(nn.Module):
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.embed_dim = embed_dim
@@ -184,10 +171,10 @@ class SelfBlock(Module):
def forward(
self,
- x: Tensor,
- encoding: Tensor,
- mask: Optional[Tensor] = None,
- ) -> Tensor:
+ x: torch.Tensor,
+ encoding: torch.Tensor,
+ mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
qkv = self.Wqkv(x)
qkv = qkv.unflatten(-1, (self.num_heads, -1, 3)).transpose(1, 2)
q, k, v = qkv[..., 0], qkv[..., 1], qkv[..., 2]
@@ -195,10 +182,10 @@ class SelfBlock(Module):
k = apply_cached_rotary_emb(encoding, k)
context = self.inner_attn(q, k, v, mask=mask)
message = self.out_proj(context.transpose(1, 2).flatten(start_dim=-2))
- return x + self.ffn(concatenate([x, message], -1))
+ return x + self.ffn(torch.cat([x, message], -1))
-class CrossBlock(Module):
+class CrossBlock(nn.Module):
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.heads = num_heads
@@ -219,10 +206,12 @@ class CrossBlock(Module):
else:
self.flash = None # type: ignore
- def map_(self, func: Callable, x0: Tensor, x1: Tensor) -> Tuple[Tensor, Tensor]: # type: ignore
+ def map_(self, func: Callable, x0: torch.Tensor, x1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
return func(x0), func(x1)
- def forward(self, x0: Tensor, x1: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def forward(
+ self, x0: torch.Tensor, x1: torch.Tensor, mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
qk0, qk1 = self.map_(self.to_qk, x0, x1)
v0, v1 = self.map_(self.to_v, x0, x1)
qk0, qk1, v0, v1 = (t.unflatten(-1, (self.heads, -1)).transpose(1, 2) for t in (qk0, qk1, v0, v1))
@@ -231,23 +220,23 @@ class CrossBlock(Module):
m1 = self.flash(qk1, qk0, v0, mask.transpose(-1, -2) if mask is not None else None)
else:
qk0, qk1 = qk0 * self.scale**0.5, qk1 * self.scale**0.5
- sim = einsum("bhid, bhjd -> bhij", qk0, qk1)
+ sim = torch.einsum("bhid, bhjd -> bhij", qk0, qk1)
if mask is not None:
sim = sim.masked_fill(~mask, -float("inf"))
attn01 = F.softmax(sim, dim=-1)
attn10 = F.softmax(sim.transpose(-2, -1).contiguous(), dim=-1)
- m0 = einsum("bhij, bhjd -> bhid", attn01, v1)
- m1 = einsum("bhji, bhjd -> bhid", attn10.transpose(-2, -1), v0)
+ m0 = torch.einsum("bhij, bhjd -> bhid", attn01, v1)
+ m1 = torch.einsum("bhji, bhjd -> bhid", attn10.transpose(-2, -1), v0)
if mask is not None:
m0, m1 = m0.nan_to_num(), m1.nan_to_num()
m0, m1 = self.map_(lambda t: t.transpose(1, 2).flatten(start_dim=-2), m0, m1)
m0, m1 = self.map_(self.to_out, m0, m1)
- x0 = x0 + self.ffn(concatenate([x0, m0], -1))
- x1 = x1 + self.ffn(concatenate([x1, m1], -1))
+ x0 = x0 + self.ffn(torch.cat([x0, m0], -1))
+ x1 = x1 + self.ffn(torch.cat([x1, m1], -1))
return x0, x1
-class TransformerLayer(Module):
+class TransformerLayer(nn.Module):
def __init__(self, *args, **kwargs): # type: ignore
super().__init__()
self.self_attn = SelfBlock(*args, **kwargs)
@@ -255,13 +244,13 @@ class TransformerLayer(Module):
def forward(
self,
- desc0: Tensor,
- desc1: Tensor,
- encoding0: Tensor,
- encoding1: Tensor,
- mask0: Optional[Tensor] = None,
- mask1: Optional[Tensor] = None,
- ) -> Tensor:
+ desc0: torch.Tensor,
+ desc1: torch.Tensor,
+ encoding0: torch.Tensor,
+ encoding1: torch.Tensor,
+ mask0: Optional[torch.Tensor] = None,
+ mask1: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
if mask0 is not None and mask1 is not None:
return self.masked_forward(desc0, desc1, encoding0, encoding1, mask0, mask1)
else:
@@ -271,8 +260,14 @@ class TransformerLayer(Module):
# This part is compiled and allows padding inputs
def masked_forward(
- self, desc0: Tensor, desc1: Tensor, encoding0: Tensor, encoding1: Tensor, mask0: Tensor, mask1: Tensor
- ) -> Tensor:
+ self,
+ desc0: torch.Tensor,
+ desc1: torch.Tensor,
+ encoding0: torch.Tensor,
+ encoding1: torch.Tensor,
+ mask0: torch.Tensor,
+ mask1: torch.Tensor,
+ ) -> torch.Tensor:
mask = mask0 & mask1.transpose(-1, -2)
mask0 = mask0 & mask0.transpose(-1, -2)
mask1 = mask1 & mask1.transpose(-1, -2)
@@ -281,7 +276,7 @@ class TransformerLayer(Module):
return self.cross_attn(desc0, desc1, mask)
-def sigmoid_log_double_softmax(sim: Tensor, z0: Tensor, z1: Tensor) -> Tensor:
+def sigmoid_log_double_softmax(sim: torch.Tensor, z0: torch.Tensor, z1: torch.Tensor) -> torch.Tensor:
"""Create the log assignment matrix from logits and similarity."""
b, m, n = sim.shape
certainties = F.logsigmoid(z0) + F.logsigmoid(z1).transpose(1, 2)
@@ -294,48 +289,48 @@ def sigmoid_log_double_softmax(sim: Tensor, z0: Tensor, z1: Tensor) -> Tensor:
return scores
-class MatchAssignment(Module):
+class MatchAssignment(nn.Module):
def __init__(self, dim: int) -> None:
super().__init__()
self.dim = dim
self.matchability = nn.Linear(dim, 1, bias=True)
self.final_proj = nn.Linear(dim, dim, bias=True)
- def forward(self, desc0: Tensor, desc1: Tensor) -> Tuple[Tensor, Tensor]:
+ def forward(self, desc0: torch.Tensor, desc1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Build assignment matrix from descriptors."""
mdesc0, mdesc1 = self.final_proj(desc0), self.final_proj(desc1)
_, _, d = mdesc0.shape
mdesc0, mdesc1 = mdesc0 / d**0.25, mdesc1 / d**0.25
- sim = einsum("bmd,bnd->bmn", mdesc0, mdesc1)
+ sim = torch.einsum("bmd,bnd->bmn", mdesc0, mdesc1)
z0 = self.matchability(desc0)
z1 = self.matchability(desc1)
scores = sigmoid_log_double_softmax(sim, z0, z1)
return scores, sim
- def get_matchability(self, desc: Tensor) -> Tensor:
+ def get_matchability(self, desc: torch.Tensor) -> torch.Tensor:
return torch.sigmoid(self.matchability(desc)).squeeze(-1)
-def filter_matches(scores: Tensor, th: float) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+def filter_matches(scores: torch.Tensor, th: float) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Obtain matches from a log assignment matrix [Bx M+1 x N+1]."""
max0, max1 = scores[:, :-1, :-1].max(2), scores[:, :-1, :-1].max(1)
m0, m1 = max0.indices, max1.indices
- indices0 = arange(m0.shape[1], device=m0.device)[None]
- indices1 = arange(m1.shape[1], device=m1.device)[None]
+ indices0 = torch.arange(m0.shape[1], device=m0.device)[None]
+ indices1 = torch.arange(m1.shape[1], device=m1.device)[None]
mutual0 = indices0 == m1.gather(1, m0)
mutual1 = indices1 == m0.gather(1, m1)
max0_exp = max0.values.exp()
zero = max0_exp.new_tensor(0)
- mscores0 = where(mutual0, max0_exp, zero)
- mscores1 = where(mutual1, mscores0.gather(1, m1), zero)
+ mscores0 = torch.where(mutual0, max0_exp, zero)
+ mscores1 = torch.where(mutual1, mscores0.gather(1, m1), zero)
valid0 = mutual0 & (mscores0 > th)
valid1 = mutual1 & valid0.gather(1, m1)
- m0 = where(valid0, m0, -1)
- m1 = where(valid1, m1, -1)
+ m0 = torch.where(valid0, m0, -1)
+ m1 = torch.where(valid1, m1, -1)
return m0, m1, mscores0, mscores1
-class LightGlue(Module):
+class LightGlue(nn.Module):
default_conf: ClassVar[Dict[str, Any]] = {
"name": "lightglue", # just for interfacing
"input_dim": 256, # input descriptor dimension (autoselected from weights)
@@ -439,12 +434,12 @@ class LightGlue(Module):
)
h, n, d = conf.num_heads, conf.n_layers, conf.descriptor_dim
- self.transformers = ModuleList([TransformerLayer(d, h, conf.flash) for _ in range(n)])
- self.log_assignment = ModuleList([MatchAssignment(d) for _ in range(n)])
- self.token_confidence = ModuleList([TokenConfidence(d) for _ in range(n - 1)])
+ self.transformers = nn.ModuleList([TransformerLayer(d, h, conf.flash) for _ in range(n)])
+ self.log_assignment = nn.ModuleList([MatchAssignment(d) for _ in range(n)])
+ self.token_confidence = nn.ModuleList([TokenConfidence(d) for _ in range(n - 1)])
self.register_buffer(
"confidence_thresholds",
- Tensor([self.confidence_threshold(i) for i in range(self.conf.n_layers)]),
+ torch.Tensor([self.confidence_threshold(i) for i in range(self.conf.n_layers)]),
)
state_dict = None
if features is not None:
@@ -535,10 +530,10 @@ class LightGlue(Module):
KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore
KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore
if self.conf.add_scale_ori:
- kpts0 = concatenate([kpts0] + [data0[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
+ kpts0 = torch.cat([kpts0] + [data0[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
if self.conf.scale_coef != 1.0:
kpts0[..., -2] = kpts0[..., -2] * self.conf.scale_coef
- kpts1 = concatenate([kpts1] + [data1[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
+ kpts1 = torch.cat([kpts1] + [data1[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
if self.conf.scale_coef != 1.0:
kpts1[..., -2] = kpts1[..., -2] * self.conf.scale_coef
elif self.conf.add_laf:
@@ -546,7 +541,7 @@ class LightGlue(Module):
laf1 = scale_laf(data1["lafs"], self.conf.scale_coef)
laf0 = laf_to_three_points(laf0)
laf1 = laf_to_three_points(laf1)
- kpts0 = concatenate(
+ kpts0 = torch.cat(
[
kpts0,
normalize_keypoints(laf0[..., 0], size0).clone().to(kpts0.dtype),
@@ -554,7 +549,7 @@ class LightGlue(Module):
],
-1,
)
- kpts1 = concatenate(
+ kpts1 = torch.cat(
[
kpts1,
normalize_keypoints(laf1[..., 0], size1).clone().to(kpts1.dtype),
@@ -593,11 +588,11 @@ class LightGlue(Module):
do_point_pruning = self.conf.width_confidence > 0 and not do_compile
pruning_th = self.pruning_min_kpts(device)
if do_point_pruning:
- ind0 = arange(0, m, device=device)[None]
- ind1 = arange(0, n, device=device)[None]
+ ind0 = torch.arange(0, m, device=device)[None]
+ ind1 = torch.arange(0, n, device=device)[None]
# We store the index of the layer at which pruning is detected.
- prune0 = ones_like(ind0)
- prune1 = ones_like(ind1)
+ prune0 = torch.ones_like(ind0)
+ prune1 = torch.ones_like(ind1)
token0, token1 = None, None
for i in range(self.conf.n_layers):
desc0, desc1 = self.transformers[i](desc0, desc1, encoding0, encoding1, mask0=mask0, mask1=mask1)
@@ -611,7 +606,7 @@ class LightGlue(Module):
if do_point_pruning and desc0.shape[-2] > pruning_th:
scores0 = self.log_assignment[i].get_matchability(desc0)
prunemask0 = self.get_pruning_mask(token0, scores0, i) # type: ignore
- keep0 = where(prunemask0)[1]
+ keep0 = torch.where(prunemask0)[1]
ind0 = ind0.index_select(1, keep0)
desc0 = desc0.index_select(1, keep0)
encoding0 = encoding0.index_select(-2, keep0)
@@ -619,7 +614,7 @@ class LightGlue(Module):
if do_point_pruning and desc1.shape[-2] > pruning_th:
scores1 = self.log_assignment[i].get_matchability(desc1)
prunemask1 = self.get_pruning_mask(token1, scores1, i) # type: ignore
- keep1 = where(prunemask1)[1]
+ keep1 = torch.where(prunemask1)[1]
ind1 = ind1.index_select(1, keep1)
desc1 = desc1.index_select(1, keep1)
encoding1 = encoding1.index_select(-2, keep1)
@@ -631,28 +626,28 @@ class LightGlue(Module):
matches, mscores = [], []
for k in range(b):
valid = m0[k] > -1
- m_indices_0 = where(valid)[0]
+ m_indices_0 = torch.where(valid)[0]
m_indices_1 = m0[k][valid]
if do_point_pruning:
m_indices_0 = ind0[k, m_indices_0]
m_indices_1 = ind1[k, m_indices_1]
- matches.append(stack([m_indices_0, m_indices_1], -1))
+ matches.append(torch.stack([m_indices_0, m_indices_1], -1))
mscores.append(mscores0[k][valid])
# TODO: Remove when hloc switches to the compact format.
if do_point_pruning:
m0_ = torch.full((b, m), -1, device=m0.device, dtype=m0.dtype)
m1_ = torch.full((b, n), -1, device=m1.device, dtype=m1.dtype)
- m0_[:, ind0] = where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0)))
- m1_[:, ind1] = where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0)))
- mscores0_ = zeros((b, m), device=mscores0.device)
- mscores1_ = zeros((b, n), device=mscores1.device)
+ m0_[:, ind0] = torch.where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0)))
+ m1_[:, ind1] = torch.where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0)))
+ mscores0_ = torch.zeros((b, m), device=mscores0.device)
+ mscores1_ = torch.zeros((b, n), device=mscores1.device)
mscores0_[:, ind0] = mscores0
mscores1_[:, ind1] = mscores1
m0, m1, mscores0, mscores1 = m0_, m1_, mscores0_, mscores1_
else:
- prune0 = ones_like(mscores0) * self.conf.n_layers
- prune1 = ones_like(mscores1) * self.conf.n_layers
+ prune0 = torch.ones_like(mscores0) * self.conf.n_layers
+ prune1 = torch.ones_like(mscores1) * self.conf.n_layers
pred = {
"log_assignment": scores,
@@ -674,7 +669,7 @@ class LightGlue(Module):
threshold = 0.8 + 0.1 * math.exp(-4.0 * layer_index / self.conf.n_layers)
return min(max(threshold, 0), 1)
- def get_pruning_mask(self, confidences: Tensor, scores: Tensor, layer_index: int) -> Tensor:
+ def get_pruning_mask(self, confidences: torch.Tensor, scores: torch.Tensor, layer_index: int) -> torch.Tensor:
"""Mask points which should be removed."""
keep = scores > (1 - self.conf.width_confidence)
if confidences is not None: # Low-confidence points are never pruned.
@@ -683,13 +678,13 @@ class LightGlue(Module):
def check_if_stop(
self,
- confidences0: Tensor,
- confidences1: Tensor,
+ confidences0: torch.Tensor,
+ confidences1: torch.Tensor,
layer_index: int,
num_points: int,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Evaluate stopping condition."""
- confidences = concatenate([confidences0, confidences1], -1)
+ confidences = torch.cat([confidences0, confidences1], -1)
threshold = self.confidence_thresholds[layer_index]
ratio_confident = 1.0 - (confidences < threshold).float().sum() / num_points
return ratio_confident > self.conf.depth_confidence
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 9df1a7602..458f9a62c 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -17,11 +17,10 @@
from __future__ import annotations
-from typing import ClassVar
+from typing import ClassVar, Union
import torch
-from kornia.core import Device, Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE
from .utils import download_onnx_from_url, normalize_keypoints
@@ -49,7 +48,7 @@ class OnnxLightGlue:
weights: Pretrained weights, or a path to your own exported ONNX model. Available pretrained weights
are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``. `Note that FP16 requires CUDA.`
Defaults to ``'disk_fp16'`` if ``device`` is CUDA, and ``'disk'`` if CPU.
- device: Device to run inference on.
+ device: Union[str, torch.device, None] to run inference on.
"""
@@ -62,7 +61,7 @@ class OnnxLightGlue:
required_data_keys: ClassVar[list[str]] = ["image0", "image1"]
- def __init__(self, weights: str | None = None, device: Device = "cpu") -> None:
+ def __init__(self, weights: str | None = None, device: Union[str, torch.device, None] = "cpu") -> None:
KORNIA_CHECK(ort is not None, "onnxruntime is not installed.")
KORNIA_CHECK(np is not None, "numpy is not installed.")
@@ -91,10 +90,10 @@ class OnnxLightGlue:
self.session = ort.InferenceSession(weights, providers=providers)
- def __call__(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]:
+ def __call__(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
return self.forward(data)
- def forward(self, data: dict[str, dict[str, Tensor]]) -> dict[str, Tensor]:
+ def forward(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
r"""Match keypoints and descriptors between two images.
The output contains the matches (the indices of the matching keypoint pairs between the first and second image)
@@ -179,7 +178,7 @@ class OnnxLightGlue:
matches, mscores = binding.get_outputs()
# TODO: The following is an unnecessary copy. Replace with a better solution when torch supports
- # constructing a tensor from a data pointer, or when ORT supports converting to torch tensor.
+ # constructing a torch.tensor from a data pointer, or when ORT supports converting to torch torch.tensor.
# https://github.com/microsoft/onnxruntime/issues/15963
outputs = {
"matches": torch.from_dlpack(matches.numpy()).to(self.device),
diff --git a/kornia/feature/lightglue_onnx/utils/keypoints.py b/kornia/feature/lightglue_onnx/utils/keypoints.py
index 504b8d8cc..10f62e9b6 100644
--- a/kornia/feature/lightglue_onnx/utils/keypoints.py
+++ b/kornia/feature/lightglue_onnx/utils/keypoints.py
@@ -19,13 +19,11 @@ from __future__ import annotations
import torch
-from kornia.core import Tensor, tensor
-
-def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor:
- """Normalize tensor of keypoints."""
+def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
+ """Normalize torch.tensor of keypoints."""
if isinstance(size, torch.Size):
- size = tensor(size)[None]
+ size = torch.tensor(size)[None]
shift = size.float().to(kpts) / 2
scale = size.max(1).values.float().to(kpts) / 2
kpts = (kpts - shift[:, None]) / scale[:, None, None]
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index 166e25589..5f3e12c8d 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -17,11 +17,10 @@
from typing import Any, Dict, List, Type, Union
+import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
-
def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
"""1x1 convolution without padding."""
@@ -33,7 +32,7 @@ def conv3x3(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
-class BasicBlock(Module):
+class BasicBlock(nn.Module):
def __init__(self, in_planes: int, planes: int, stride: int = 1) -> None:
super().__init__()
self.conv1 = conv3x3(in_planes, planes, stride)
@@ -47,7 +46,7 @@ class BasicBlock(Module):
else:
self.downsample = nn.Sequential(conv1x1(in_planes, planes, stride=stride), nn.BatchNorm2d(planes))
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
y = x
y = self.relu(self.bn1(self.conv1(y)))
y = self.bn2(self.conv2(y))
@@ -107,7 +106,7 @@ class ResNetFPN_8_2(nn.Module):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
- def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential:
+ def _make_layer(self, block: Union[Type[BasicBlock], nn.Module], dim: int, stride: int = 1) -> nn.Sequential:
layer1 = block(self.in_planes, dim, stride=stride)
layer2 = block(dim, dim, stride=1)
layers = (layer1, layer2)
@@ -115,7 +114,7 @@ class ResNetFPN_8_2(nn.Module):
self.in_planes = dim
return nn.Sequential(*layers)
- def forward(self, x: Tensor) -> List[Tensor]:
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
# ResNet Backbone
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
@@ -187,7 +186,7 @@ class ResNetFPN_16_4(nn.Module):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
- def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential:
+ def _make_layer(self, block: Union[Type[BasicBlock], nn.Module], dim: int, stride: int = 1) -> nn.Sequential:
layer1 = block(self.in_planes, dim, stride=stride)
layer2 = block(dim, dim, stride=1)
layers = (layer1, layer2)
@@ -195,7 +194,7 @@ class ResNetFPN_16_4(nn.Module):
self.in_planes = dim
return nn.Sequential(*layers)
- def forward(self, x: Tensor) -> List[Tensor]:
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
# ResNet Backbone
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 72f1db9fc..b182af7f8 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -20,8 +20,8 @@ from __future__ import annotations
from typing import Any, Optional
import torch
+from torch import nn
-from kornia.core import Module, Tensor
from kornia.geometry import resize
from .backbone import build_backbone
@@ -67,8 +67,8 @@ default_cfg = {
}
-class LoFTR(Module):
- r"""Module, which finds correspondences between two images.
+class LoFTR(nn.Module):
+ r"""nn.Module, which finds correspondences between two images.
This is based on the original code from paper "LoFTR: Detector-Free Local
Feature Matching with Transformers". See :cite:`LoFTR2021` for more details.
@@ -118,7 +118,7 @@ class LoFTR(Module):
self.load_state_dict(pretrained_dict["state_dict"])
self.eval()
- def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]:
+ def forward(self, data: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
"""Run forward.
Args:
@@ -138,7 +138,7 @@ class LoFTR(Module):
"""
# 1. Local Feature CNN
- _data: dict[str, Tensor | int | torch.Size] = {
+ _data: dict[str, torch.Tensor | int | torch.Size] = {
"bs": data["image0"].size(0),
"hw0_i": data["image0"].shape[2:],
"hw1_i": data["image1"].shape[2:],
@@ -196,13 +196,13 @@ class LoFTR(Module):
"mconf": "confidence",
"b_ids": "batch_indexes",
}
- out: dict[str, Tensor] = {}
+ out: dict[str, torch.Tensor] = {}
for k, v in rename_keys.items():
_d = _data[k]
- if isinstance(_d, Tensor):
+ if isinstance(_d, torch.Tensor):
out[v] = _d
else:
- raise TypeError(f"Expected Tensor for item `{k}`. Gotcha {type(_d)}")
+ raise TypeError(f"Expected torch.Tensor for item `{k}`. Gotcha {type(_d)}")
return out
def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index 06ce46b11..477098fc8 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -21,10 +21,8 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
-
-class FinePreprocess(Module):
+class FinePreprocess(nn.Module):
def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
@@ -47,8 +45,13 @@ class FinePreprocess(Module):
nn.init.kaiming_normal_(p, mode="fan_out", nonlinearity="relu")
def forward(
- self, feat_f0: Tensor, feat_f1: Tensor, feat_c0: Tensor, feat_c1: Tensor, data: Dict[str, Any]
- ) -> Tuple[Tensor, Tensor]:
+ self,
+ feat_f0: torch.Tensor,
+ feat_f1: torch.Tensor,
+ feat_c0: torch.Tensor,
+ feat_c1: torch.Tensor,
+ data: Dict[str, Any],
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
W = self.W
stride = data["hw0_f"][0] // data["hw0_c"][0]
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index a4eafe4de..d086695ba 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -24,17 +24,17 @@ transformers/blob/master/fast_transformers/attention/linear_attention.py.
from typing import Optional
import torch
+import torch.nn.functional as F
+from torch import nn
from torch.nn import Dropout
-from kornia.core import Module, Tensor
-
-def elu_feature_map(x: Tensor) -> Tensor:
+def elu_feature_map(x: torch.Tensor) -> torch.Tensor:
"""Apply elu activation."""
return torch.nn.functional.elu(x) + 1
-class LinearAttention(Module):
+class LinearAttention(nn.Module):
def __init__(self, eps: float = 1e-6) -> None:
super().__init__()
self.feature_map = elu_feature_map
@@ -42,12 +42,12 @@ class LinearAttention(Module):
def forward(
self,
- queries: Tensor,
- keys: Tensor,
- values: Tensor,
- q_mask: Optional[Tensor] = None,
- kv_mask: Optional[Tensor] = None,
- ) -> Tensor:
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ q_mask: Optional[torch.Tensor] = None,
+ kv_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Multi-Head linear attention proposed in "Transformers are RNNs".
Args:
@@ -80,7 +80,7 @@ class LinearAttention(Module):
return queried_values.contiguous()
-class FullAttention(Module):
+class FullAttention(nn.Module):
def __init__(self, use_dropout: bool = False, attention_dropout: float = 0.1) -> None:
super().__init__()
self.use_dropout = use_dropout
@@ -88,12 +88,12 @@ class FullAttention(Module):
def forward(
self,
- queries: Tensor,
- keys: Tensor,
- values: Tensor,
- q_mask: Optional[Tensor] = None,
- kv_mask: Optional[Tensor] = None,
- ) -> Tensor:
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ q_mask: Optional[torch.Tensor] = None,
+ kv_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Multi-head scaled dot-product attention, a.k.a full attention.
Args:
@@ -114,7 +114,7 @@ class FullAttention(Module):
# Compute the attention and the weighted average
softmax_temp = 1.0 / queries.size(3) ** 0.5 # sqrt(D)
- A = torch.softmax(softmax_temp * QK, dim=2)
+ A = F.softmax(softmax_temp * QK, dim=2)
if self.use_dropout:
A = self.dropout(A)
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index bea9e97bb..8dbc30a64 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -23,12 +23,10 @@ from typing import Any, Literal, Optional
import torch
from torch import nn
-from kornia.core import Module, Tensor
-
from .linear_attention import FullAttention, LinearAttention
-class LoFTREncoderLayer(Module):
+class LoFTREncoderLayer(nn.Module):
def __init__(self, d_model: int, nhead: int, attention: Optional[Literal["linear"]] = "linear") -> None:
super().__init__()
@@ -52,8 +50,12 @@ class LoFTREncoderLayer(Module):
self.norm2 = nn.LayerNorm(d_model)
def forward(
- self, x: Tensor, source: Tensor, x_mask: Optional[Tensor] = None, source_mask: Optional[Tensor] = None
- ) -> Tensor:
+ self,
+ x: torch.Tensor,
+ source: torch.Tensor,
+ x_mask: Optional[torch.Tensor] = None,
+ source_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""Run forward.
Args:
@@ -81,7 +83,7 @@ class LoFTREncoderLayer(Module):
return x + message
-class LocalFeatureTransformer(Module):
+class LocalFeatureTransformer(nn.Module):
"""A Local Feature Transformer (LoFTR) module."""
def __init__(self, config: dict[str, Any]) -> None:
@@ -101,8 +103,12 @@ class LocalFeatureTransformer(Module):
nn.init.xavier_uniform_(p)
def forward(
- self, feat0: Tensor, feat1: Tensor, mask0: None | Tensor = None, mask1: None | Tensor = None
- ) -> tuple[Tensor, Tensor]:
+ self,
+ feat0: torch.Tensor,
+ feat1: torch.Tensor,
+ mask0: None | torch.Tensor = None,
+ mask1: None | torch.Tensor = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
"""Run forward.
Args:
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 66c862e61..baf87691b 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -21,12 +21,10 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
-
INF = 1e9
-def mask_border(m: Tensor, b: int, v: Union[Tensor, float, bool]) -> None:
+def mask_border(m: torch.Tensor, b: int, v: Union[torch.Tensor, float, bool]) -> None:
"""Mask borders with value.
Args:
@@ -47,7 +45,9 @@ def mask_border(m: Tensor, b: int, v: Union[Tensor, float, bool]) -> None:
m[:, :, :, :, -b:] = v
-def mask_border_with_padding(m: Tensor, bd: int, v: Union[Tensor, float, bool], p_m0: Tensor, p_m1: Tensor) -> None:
+def mask_border_with_padding(
+ m: torch.Tensor, bd: int, v: Union[torch.Tensor, float, bool], p_m0: torch.Tensor, p_m1: torch.Tensor
+) -> None:
"""Apply masking to a padded boarder."""
if bd <= 0:
return
@@ -66,7 +66,7 @@ def mask_border_with_padding(m: Tensor, bd: int, v: Union[Tensor, float, bool],
m[b_idx, :, :, :, w1 - bd :] = v
-def compute_max_candidates(p_m0: Tensor, p_m1: Tensor) -> Tensor:
+def compute_max_candidates(p_m0: torch.Tensor, p_m1: torch.Tensor) -> torch.Tensor:
"""Compute the max candidates of all pairs within a batch.
Args:
@@ -80,7 +80,7 @@ def compute_max_candidates(p_m0: Tensor, p_m1: Tensor) -> Tensor:
return max_cand
-class CoarseMatching(Module):
+class CoarseMatching(nn.Module):
def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
self.config = config
@@ -109,11 +109,11 @@ class CoarseMatching(Module):
def forward(
self,
- feat_c0: Tensor,
- feat_c1: Tensor,
- data: Dict[str, Tensor],
- mask_c0: Optional[Tensor] = None,
- mask_c1: Optional[Tensor] = None,
+ feat_c0: torch.Tensor,
+ feat_c1: torch.Tensor,
+ data: Dict[str, torch.Tensor],
+ mask_c0: Optional[torch.Tensor] = None,
+ mask_c1: Optional[torch.Tensor] = None,
) -> None:
"""Run forward.
@@ -137,7 +137,7 @@ class CoarseMatching(Module):
"""
_, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)
- # normalize
+ # F.normalize
feat_c0, feat_c1 = (feat / feat.shape[-1] ** 0.5 for feat in [feat_c0, feat_c1])
if self.match_type == "dual_softmax":
@@ -173,7 +173,7 @@ class CoarseMatching(Module):
data.update(**self.get_coarse_match(conf_matrix, data))
@torch.no_grad()
- def get_coarse_match(self, conf_matrix: Tensor, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
+ def get_coarse_match(self, conf_matrix: torch.Tensor, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""Get corase matching.
Args:
@@ -228,7 +228,7 @@ class CoarseMatching(Module):
mconf = conf_matrix[b_ids, i_ids, j_ids]
# 4. Random sampling of training samples for fine-level LoFTR
- # (optional) pad samples with gt coarse-level matches
+ # (optional) F.pad samples with gt coarse-level matches
if self.training:
# NOTE:
# The sampling is performed across all pairs in a batch without manually balancing
@@ -241,7 +241,7 @@ class CoarseMatching(Module):
num_matches_train = int(num_matches_train)
num_matches_pred = len(b_ids)
if self.train_pad_num_gt_min >= num_matches_train:
- msg = "min-num-gt-pad should be less than num-train-matches"
+ msg = "min-num-gt-F.pad should be less than num-train-matches"
raise ValueError(msg)
# pred_indices is to select from prediction
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 23ffbc1c0..72d92f1a7 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -21,19 +21,20 @@ import math
from typing import Any
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor
from kornia.geometry.subpix import dsnt
from kornia.utils.grid import create_meshgrid
-class FineMatching(Module):
+class FineMatching(nn.Module):
"""FineMatching with s2d paradigm."""
def __init__(self) -> None:
super().__init__()
- def forward(self, feat_f0: Tensor, feat_f1: Tensor, data: dict[str, Any]) -> None:
+ def forward(self, feat_f0: torch.Tensor, feat_f1: torch.Tensor, data: dict[str, Any]) -> None:
"""Run forward.
Args:
@@ -69,7 +70,7 @@ class FineMatching(Module):
feat_f0_picked = feat_f0[:, WW // 2, :]
sim_matrix = torch.einsum("mc,mrc->mr", feat_f0_picked, feat_f1)
softmax_temp = 1.0 / C**0.5
- heatmap = torch.softmax(softmax_temp * sim_matrix, dim=1).view(-1, W, W)
+ heatmap = F.softmax(softmax_temp * sim_matrix, dim=1).view(-1, W, W)
# compute coordinates from heatmap
coords_normalized = dsnt.spatial_expectation2d(heatmap[None], True)[0] # [M, 2]
@@ -88,7 +89,7 @@ class FineMatching(Module):
self.get_fine_match(coords_normalized, data)
@torch.no_grad()
- def get_fine_match(self, coords_normed: Tensor, data: dict[str, Any]) -> None:
+ def get_fine_match(self, coords_normed: torch.Tensor, data: dict[str, Any]) -> None:
W, _, _, scale = self.W, self.WW, self.C, self.scale
# mkpts0_f and mkpts1_f
diff --git a/kornia/feature/loftr/utils/geometry.py b/kornia/feature/loftr/utils/geometry.py
index 2676d7206..70f1ed058 100644
--- a/kornia/feature/loftr/utils/geometry.py
+++ b/kornia/feature/loftr/utils/geometry.py
@@ -19,13 +19,16 @@ from typing import Tuple
import torch
-from kornia.core import Tensor
-
@torch.no_grad()
def warp_kpts(
- kpts0: Tensor, depth0: Tensor, depth1: Tensor, T_0to1: Tensor, K0: Tensor, K1: Tensor
-) -> Tuple[Tensor, Tensor]:
+ kpts0: torch.Tensor,
+ depth0: torch.Tensor,
+ depth1: torch.Tensor,
+ T_0to1: torch.Tensor,
+ K0: torch.Tensor,
+ K1: torch.Tensor,
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Warp kpts0 from I0 to I1 with depth, K and Rt Also check covisibility and depth consistency.
Depth is consistent if relative error < 0.2 (hard-coded).
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index 727d70870..a1c623782 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -19,14 +19,13 @@ import math
from typing import Tuple
import torch
+from torch import nn
-from kornia.core import Module, Tensor, cos, sin, zeros
-
-class PositionEncodingSine(Module):
+class PositionEncodingSine(nn.Module):
"""A sinusoidal position encoding that generalized to 2-dimensional images."""
- pe: Tensor
+ pe: torch.Tensor
def __init__(self, d_model: int, max_shape: Tuple[int, int] = (256, 256), temp_bug_fix: bool = True) -> None:
"""Construct sinusoidal positional encoding.
@@ -47,13 +46,13 @@ class PositionEncodingSine(Module):
pe = self._create_position_encoding(max_shape)
self.register_buffer("pe", pe, persistent=False) # [1, C, H, W]
- def _create_position_encoding(self, max_shape: Tuple[int, int]) -> Tensor:
+ def _create_position_encoding(self, max_shape: Tuple[int, int]) -> torch.Tensor:
"""Create a position encoding from scratch.
For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
should be (H//8, W//8).
"""
- pe = zeros((self.d_model, *max_shape))
+ pe = torch.zeros((self.d_model, *max_shape))
y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)
x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)
if self.temp_bug_fix:
@@ -65,10 +64,10 @@ class PositionEncodingSine(Module):
torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / self.d_model // 2)
)
div_term = div_term[:, None, None] # [C//4, 1, 1]
- pe[0::4, :, :] = sin(x_position * div_term)
- pe[1::4, :, :] = cos(x_position * div_term)
- pe[2::4, :, :] = sin(y_position * div_term)
- pe[3::4, :, :] = cos(y_position * div_term)
+ pe[0::4, :, :] = torch.sin(x_position * div_term)
+ pe[1::4, :, :] = torch.cos(x_position * div_term)
+ pe[2::4, :, :] = torch.sin(y_position * div_term)
+ pe[3::4, :, :] = torch.cos(y_position * div_term)
return pe.unsqueeze(0)
def update_position_encoding_size(self, max_shape: Tuple[int, int]) -> None:
@@ -79,7 +78,7 @@ class PositionEncodingSine(Module):
"""
self.pe = self._create_position_encoding(max_shape).to(self.pe.device)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Run forward.
Args:
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index b06a1903c..ad914608f 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -21,7 +21,6 @@ from typing import Any
import torch
-from kornia.core import Tensor
from kornia.utils import create_meshgrid
from .geometry import warp_kpts
@@ -29,7 +28,7 @@ from .geometry import warp_kpts
# Coarse-Level supervision
@torch.no_grad()
-def mask_pts_at_padded_regions(grid_pt: Tensor, mask: Tensor) -> Tensor:
+def mask_pts_at_padded_regions(grid_pt: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""For megadepth dataset, zero-padding exists in images."""
n, h, w = mask.shape
mask = mask.reshape(n, h * w).unsqueeze(-1).repeat(1, 1, 2)
@@ -94,7 +93,7 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
nearest_index0 = w_pt1_c_round[..., 0] + w_pt1_c_round[..., 1] * w0
# corner case: out of boundary
- def out_bound_mask(pt: Tensor, w: Tensor, h: Tensor) -> Tensor:
+ def out_bound_mask(pt: torch.Tensor, w: torch.Tensor, h: torch.Tensor) -> torch.Tensor:
return (pt[..., 0] < 0) + (pt[..., 0] >= w) + (pt[..., 1] < 0) + (pt[..., 1] >= h)
nearest_index1[out_bound_mask(w_pt0_c_round, w1, h1)] = 0
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 1a082668f..fb76e34bc 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -18,8 +18,9 @@
from typing import Any, ClassVar, Dict, List, Optional, Tuple
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center
from kornia.feature.steerers import DiscreteSteerer
@@ -28,7 +29,7 @@ from kornia.utils.helpers import is_mps_tensor_safe
from .adalam import get_adalam_default_config, match_adalam
-def _cdist(d1: Tensor, d2: Tensor) -> Tensor:
+def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:
r"""Manual `torch.cdist` for M1."""
if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)):
return torch.cdist(d1, d2)
@@ -44,13 +45,15 @@ def _get_default_fginn_params() -> Dict[str, Any]:
return config
-def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None) -> Tensor:
+def _get_lazy_distance_matrix(
+ desc1: torch.Tensor, desc2: torch.Tensor, dm_: Optional[torch.Tensor] = None
+) -> torch.Tensor:
"""Check validity of provided distance matrix, or calculates L2-distance matrix if dm is not provided.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
- dm_: Tensor containing the distances from each descriptor in desc1
+ dm_: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
"""
@@ -62,12 +65,12 @@ def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor
return dm
-def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
+def _no_match(dm: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Output empty tensors.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
"""
dists = torch.empty(0, 1, device=dm.device, dtype=dm.dtype)
@@ -75,7 +78,9 @@ def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
return dists, idxs
-def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+def match_nn(
+ desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None
+) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Find nearest neighbors in desc2 for each vector in desc1.
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
@@ -83,12 +88,12 @@ def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -98,11 +103,13 @@ def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple
distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)
match_dists, idxs_in_2 = torch.min(distance_matrix, dim=1)
idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
- matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
+ matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+def match_mnn(
+ desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find mutual nearest neighbors in desc2 for each vector in desc1.
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
@@ -110,13 +117,13 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tupl
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
- where 0 <= B3 <= min(B1, B2)
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
+ torch.where 0 <= B3 <= min(B1, B2)
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -131,16 +138,18 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tupl
if distance_matrix.size(0) <= distance_matrix.size(1):
mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms]
- matches_idxs = concatenate([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], 1)[mutual_nns]
+ matches_idxs = torch.cat([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], 1)[mutual_nns]
match_dists = match_dists[mutual_nns]
else:
mutual_nns = minsize_idxs == idxs_in_2[idxs_in_1][:ms]
- matches_idxs = concatenate([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], 1)[mutual_nns]
+ matches_idxs = torch.cat([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], 1)[mutual_nns]
match_dists = match_dists2[mutual_nns]
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+def match_snn(
+ desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find nearest neighbors in desc2 for each vector in desc1.
The method satisfies first to second nearest neighbor distance <= th.
@@ -151,13 +160,13 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
th: distance ratio threshold.
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- where 0 <= B3 <= B1.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ torch.where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -174,11 +183,13 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor
return _no_match(distance_matrix)
idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]
idxs_in_2 = idxs_in_2[:, 0][mask]
- matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
+ matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+def match_smnn(
+ desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.95, dm: Optional[torch.Tensor] = None
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find mutual nearest neighbors in desc2 for each vector in desc1.
the method satisfies first to second nearest neighbor distance <= th.
@@ -189,13 +200,13 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tens
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
th: distance ratio threshold.
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` torch.where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -234,15 +245,15 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tens
def match_fginn(
- desc1: Tensor,
- desc2: Tensor,
- lafs1: Tensor,
- lafs2: Tensor,
+ desc1: torch.Tensor,
+ desc2: torch.Tensor,
+ lafs1: torch.Tensor,
+ lafs2: torch.Tensor,
th: float = 0.8,
spatial_th: float = 10.0,
mutual: bool = False,
- dm: Optional[Tensor] = None,
-) -> Tuple[Tensor, Tensor]:
+ dm: Optional[torch.Tensor] = None,
+) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find nearest neighbors in desc2 for each vector in desc1.
The method satisfies first to second nearest neighbor distance <= th,
@@ -260,13 +271,13 @@ def match_fginn(
th: distance ratio threshold.
spatial_th: minimal distance in pixels to 2nd nearest neighbor.
mutual: also perform mutual nearest neighbor check
- dm: Tensor containing the distances from each descriptor in desc1
+ dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- where 0 <= B3 <= B1.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ torch.where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -301,7 +312,7 @@ def match_fginn(
return _no_match(distance_matrix)
idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]
idxs_in_2 = idxs_in_2[mask]
- matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
+ matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2)
if not mutual: # returning 1-way matches
@@ -311,8 +322,8 @@ def match_fginn(
return match_dists[good_mask], matches_idxs[good_mask]
-class DescriptorMatcher(Module):
- """Module version of matching functions.
+class DescriptorMatcher(nn.Module):
+ """nn.Module version of matching functions.
See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
:func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
@@ -332,7 +343,7 @@ class DescriptorMatcher(Module):
self.match_mode = _match_mode
self.th = th
- def forward(self, desc1: Tensor, desc2: Tensor) -> Tuple[Tensor, Tensor]:
+ def forward(self, desc1: torch.Tensor, desc2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Run forward.
Args:
@@ -341,8 +352,8 @@ class DescriptorMatcher(Module):
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
"""
if self.match_mode == "nn":
@@ -358,7 +369,7 @@ class DescriptorMatcher(Module):
return out
-class DescriptorMatcherWithSteerer(Module):
+class DescriptorMatcherWithSteerer(nn.Module):
"""Matching that is invariant under rotations, using Steerers.
Args:
@@ -367,7 +378,7 @@ class DescriptorMatcherWithSteerer(Module):
steer_mode: can be `global`, `local`.
`global` means that the we output matches from the global rotation with most matches.
`local` means that we output matches from a distance matrix
- where the distance between each descriptor pair is the minimal over rotations.
+ torch.where the distance between each descriptor pair is the minimal over rotations.
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
WARNING: using steer_mode `global` with match_mode `nn` will lead to bad results
since `nn` doesn't generate different amount of matches depending on goodness of fit.
@@ -424,7 +435,9 @@ class DescriptorMatcherWithSteerer(Module):
self.match_mode = _match_mode
self.th = th
- def matching_function(self, d1: Tensor, d2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def matching_function(
+ self, d1: torch.Tensor, d2: torch.Tensor, dm: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
if self.match_mode == "nn":
return match_nn(d1, d2, dm=dm)
elif self.match_mode == "mnn":
@@ -438,25 +451,25 @@ class DescriptorMatcherWithSteerer(Module):
def forward(
self,
- desc1: Tensor,
- desc2: Tensor,
+ desc1: torch.Tensor,
+ desc2: torch.Tensor,
normalize: bool = False,
subset_size: Optional[int] = None,
- ) -> Tuple[Tensor, Tensor, Optional[int]]:
+ ) -> Tuple[torch.Tensor, torch.Tensor, Optional[int]]:
"""Run forward.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
- normalize: bool to decide whether to normalize descriptors to unit norm.
+ normalize: bool to decide whether to F.normalize descriptors to unit norm.
subset_size: If set, the subset size to use for determining optimal
number of rotations. Smaller subset size leads to faster but less
accurate matching. Only used when `self.steer_mode` is `"global"`.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
- Number of global rotations from desc1 to desc2, in terms of `self.steerer_order`
(will be `None` if `self.steer_mode` is `local`).
@@ -464,8 +477,8 @@ class DescriptorMatcherWithSteerer(Module):
rot1to2 = None
if normalize:
- desc1 = torch.nn.functional.normalize(desc1, dim=-1)
- desc2 = torch.nn.functional.normalize(desc2, dim=-1)
+ desc1 = F.normalize(desc1, dim=-1)
+ desc2 = F.normalize(desc2, dim=-1)
if self.steer_mode == "global":
if subset_size is not None:
@@ -503,8 +516,8 @@ class DescriptorMatcherWithSteerer(Module):
return dist, idx, rot1to2
-class GeometryAwareDescriptorMatcher(Module):
- """Module version of matching functions.
+class GeometryAwareDescriptorMatcher(nn.Module):
+ """nn.Module version of matching functions.
See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
:func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
@@ -517,7 +530,7 @@ class GeometryAwareDescriptorMatcher(Module):
known_modes: ClassVar[List[str]] = ["fginn", "adalam"]
- def __init__(self, match_mode: str = "fginn", params: Optional[Dict[str, Tensor]] = None) -> None:
+ def __init__(self, match_mode: str = "fginn", params: Optional[Dict[str, torch.Tensor]] = None) -> None:
super().__init__()
_match_mode: str = match_mode.lower()
if _match_mode not in self.known_modes:
@@ -525,7 +538,9 @@ class GeometryAwareDescriptorMatcher(Module):
self.match_mode = _match_mode
self.params = params or {}
- def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]:
+ def forward(
+ self, desc1: torch.Tensor, desc2: torch.Tensor, lafs1: torch.Tensor, lafs2: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
"""Run forward.
Args:
@@ -536,8 +551,8 @@ class GeometryAwareDescriptorMatcher(Module):
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+ - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
"""
if self.match_mode == "fginn":
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index d22a3db5a..84e962536 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -22,7 +22,6 @@ import torch.nn.functional as F
from torch import nn
from kornia.constants import pi
-from kornia.core import Tensor, cos, sin, tensor, zeros
from kornia.filters import GaussianBlur2d, SpatialGradient
from kornia.geometry.conversions import cart2pol
from kornia.utils import create_meshgrid
@@ -40,7 +39,7 @@ urls: Dict[str, str] = {
}
-def get_grid_dict(patch_size: int = 32) -> Dict[str, Tensor]:
+def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
r"""Get cartesian and polar parametrizations of grid."""
kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
x = kgrid[0, :, :, 0]
@@ -50,7 +49,7 @@ def get_grid_dict(patch_size: int = 32) -> Dict[str, Tensor]:
return grid_dict
-def get_kron_order(d1: int, d2: int) -> Tensor:
+def get_kron_order(d1: int, d2: int) -> torch.Tensor:
r"""Get order for doing kronecker product."""
grid_d1, grid_d2 = torch.meshgrid(torch.arange(d1), torch.arange(d2), indexing="ij")
kron_order = torch.stack([grid_d1, grid_d2], dim=2).reshape(-1, 2)
@@ -58,11 +57,11 @@ def get_kron_order(d1: int, d2: int) -> Tensor:
class MKDGradients(nn.Module):
- r"""Module, which computes gradients of given patches, stacked as [magnitudes, orientations].
+ r"""nn.Module, which computes gradients of given patches, stacked as [magnitudes, orientations].
Given gradients $g_x$, $g_y$ with respect to $x$, $y$ respectively,
- $\mathbox{mags} = $\sqrt{g_x^2 + g_y^2 + eps}$
- - $\mathbox{oris} = $\mbox{tan}^{-1}(\nicefrac{g_y}{g_x})$.
+ - $\mathbox{oris} = $\mbox{torch.tan}^{-1}(\nicefrac{g_y}{g_x})$.
Args:
patch_size: Input patch size in pixels.
@@ -87,9 +86,9 @@ class MKDGradients(nn.Module):
self.grad = SpatialGradient(mode="diff", order=1, normalized=False)
- def forward(self, x: Tensor) -> Tensor:
- if not isinstance(x, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not isinstance(x, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not len(x.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}")
# Modify 'diff' gradient. Before we had lambda function, but it is not jittable
@@ -104,7 +103,7 @@ class MKDGradients(nn.Module):
class VonMisesKernel(nn.Module):
- r"""Module, which computes parameters of Von Mises kernel given coefficients, and embeds given patches.
+ r"""nn.Module, which computes parameters of Von Mises kernel given coefficients, and embeds given patches.
Args:
patch_size: Input patch size in pixels.
@@ -131,7 +130,7 @@ class VonMisesKernel(nn.Module):
super().__init__()
self.patch_size = patch_size
- b_coeffs = tensor(coeffs)
+ b_coeffs = torch.tensor(coeffs)
self.register_buffer("coeffs", b_coeffs)
# Compute parameters.
@@ -143,7 +142,7 @@ class VonMisesKernel(nn.Module):
emb0 = torch.ones([1, 1, patch_size, patch_size])
frange = torch.arange(n) + 1
frange = frange.reshape(-1, 1, 1)
- weights = zeros([2 * n + 1])
+ weights = torch.zeros([2 * n + 1])
weights[: n + 1] = torch.sqrt(b_coeffs)
weights[n + 1 :] = torch.sqrt(b_coeffs[1:])
weights = weights.reshape(-1, 1, 1)
@@ -151,20 +150,20 @@ class VonMisesKernel(nn.Module):
self.register_buffer("frange", frange)
self.register_buffer("weights", weights)
- def forward(self, x: Tensor) -> Tensor:
- if not isinstance(x, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not isinstance(x, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not len(x.shape) == 4 or x.shape[1] != 1:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}")
- if not isinstance(self.emb0, Tensor):
- raise TypeError(f"Emb0 type is not a Tensor. Got {type(x)}")
+ if not isinstance(self.emb0, torch.Tensor):
+ raise TypeError(f"Emb0 type is not a torch.Tensor. Got {type(x)}")
emb0 = self.emb0.to(x).repeat(x.size(0), 1, 1, 1)
frange = self.frange.to(x) * x
- emb1 = cos(frange)
- emb2 = sin(frange)
+ emb1 = torch.cos(frange)
+ emb2 = torch.sin(frange)
embedding = torch.cat([emb0, emb1, emb2], dim=1)
embedding = self.weights * embedding
return embedding
@@ -174,7 +173,7 @@ class VonMisesKernel(nn.Module):
class EmbedGradients(nn.Module):
- r"""Module that computes gradient embedding, weighted by sqrt of magnitudes of given patches.
+ r"""nn.Module that computes gradient embedding, weighted by sqrt of magnitudes of given patches.
Args:
patch_size: Input patch size in pixels.
@@ -209,14 +208,14 @@ class EmbedGradients(nn.Module):
_, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1])
self.register_buffer("phi", phi)
- def emb_mags(self, mags: Tensor) -> Tensor:
+ def emb_mags(self, mags: torch.Tensor) -> torch.Tensor:
"""Embed square roots of magnitudes with eps for numerical reasons."""
mags = torch.sqrt(mags + self.eps)
return mags
- def forward(self, grads: Tensor) -> Tensor:
- if not isinstance(grads, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(grads)}")
+ def forward(self, grads: torch.Tensor) -> torch.Tensor:
+ if not isinstance(grads, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(grads)}")
if not len(grads.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx2xHxW. Got: {grads.shape}")
mags = grads[:, :1, :, :]
@@ -230,7 +229,7 @@ class EmbedGradients(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, relative={self.relative})"
-def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, Tensor]) -> Tensor:
+def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Compute embeddings for cartesian and polar parametrizations."""
factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
if kernel_type == "cart":
@@ -262,7 +261,7 @@ def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, Tensor]) -> Tens
class ExplicitSpacialEncoding(nn.Module):
- r"""Module that computes explicit cartesian or polar embedding.
+ r"""nn.Module that computes explicit cartesian or polar embedding.
Args:
kernel_type: Parametrization of kernel ``'polar'`` or ``'cart'``.
@@ -329,25 +328,25 @@ class ExplicitSpacialEncoding(nn.Module):
self.register_buffer("emb2", emb2)
self.register_buffer("idx1", idx1)
- def get_gmask(self, sigma: float) -> Tensor:
+ def get_gmask(self, sigma: float) -> torch.Tensor:
"""Compute Gaussian mask."""
norm_rho = self.grid["rho"] / self.grid["rho"].max()
gmask = torch.exp(-1 * norm_rho**2 / sigma**2)
return gmask
- def init_kron(self) -> Tuple[Tensor, Tensor]:
+ def init_kron(self) -> Tuple[torch.Tensor, torch.Tensor]:
"""Initialize helper variables to calculate kronecker."""
kron = get_kron_order(self.in_dims, self.d_emb)
- _emb = torch.jit.annotate(Tensor, self.emb)
+ _emb = torch.jit.annotate(torch.Tensor, self.emb)
emb2 = torch.index_select(_emb, 1, kron[:, 1])
return emb2, kron[:, 0]
- def forward(self, x: Tensor) -> Tensor:
- if not isinstance(x, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not isinstance(x, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
raise ValueError(f"Invalid input shape, we expect Bx{self.in_dims}xHxW. Got: {x.shape}")
- idx1 = torch.jit.annotate(Tensor, self.idx1)
+ idx1 = torch.jit.annotate(torch.Tensor, self.idx1)
emb1 = torch.index_select(x, 1, idx1)
output = emb1 * self.emb2
output = output.sum(dim=(2, 3))
@@ -368,7 +367,7 @@ class ExplicitSpacialEncoding(nn.Module):
class Whitening(nn.Module):
- r"""Module, performs supervised or unsupervised whitening.
+ r"""nn.Module, performs supervised or unsupervised whitening.
This is based on the paper "Understanding and Improving Kernel Local Descriptors".
See :cite:`mukundan2019understanding` for more details.
@@ -406,7 +405,7 @@ class Whitening(nn.Module):
def __init__(
self,
xform: str,
- whitening_model: Union[Dict[str, Dict[str, Tensor]], None],
+ whitening_model: Union[Dict[str, Dict[str, torch.Tensor]], None],
in_dims: int,
output_dims: int = 128,
keval: int = 40,
@@ -425,14 +424,14 @@ class Whitening(nn.Module):
self.output_dims = output_dims
# Initialize identity transform.
- self.mean = nn.Parameter(zeros(in_dims), requires_grad=True)
+ self.mean = nn.Parameter(torch.zeros(in_dims), requires_grad=True)
self.evecs = nn.Parameter(torch.eye(in_dims)[:, :output_dims], requires_grad=True)
self.evals = nn.Parameter(torch.ones(in_dims)[:output_dims], requires_grad=True)
if whitening_model is not None:
self.load_whitening_parameters(whitening_model)
- def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, Tensor]]) -> None:
+ def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
algo = "lw" if self.xform == "lw" else "pca"
wh_model = whitening_model[algo]
self.mean.data = wh_model["mean"]
@@ -467,9 +466,9 @@ class Whitening(nn.Module):
m = -0.5 * self.t
self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))
- def forward(self, x: Tensor) -> Tensor:
- if not isinstance(x, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not isinstance(x, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not len(x.shape) == 2:
raise ValueError(f"Invalid input shape, we expect NxD. Got: {x.shape}")
x = x - self.mean # Center the data.
@@ -482,7 +481,7 @@ class Whitening(nn.Module):
class MKDDescriptor(nn.Module):
- r"""Module that computes Multiple Kernel local descriptors.
+ r"""nn.Module that computes Multiple Kernel local descriptors.
This is based on the paper "Understanding and Improving Kernel Local Descriptors".
See :cite:`mukundan2019understanding` for more details.
@@ -562,9 +561,9 @@ class MKDDescriptor(nn.Module):
self.odims = self.output_dims
self.eval()
- def forward(self, patches: Tensor) -> Tensor:
- if not isinstance(patches, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(patches)}")
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ if not isinstance(patches, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(patches)}")
if not len(patches.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {patches.shape}")
# Extract gradients.
@@ -580,7 +579,7 @@ class MKDDescriptor(nn.Module):
# Concatenate.
y = torch.cat(features, dim=1)
- # l2-normalize.
+ # l2-F.normalize.
y = F.normalize(y, dim=1)
# Whiten descriptors.
@@ -634,5 +633,5 @@ class SimpleKD(nn.Module):
self.features = nn.Sequential(smoothing, gradients, ori, ese, wh)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.features(x)
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index ec367db5b..bc8fc8e5f 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -18,8 +18,8 @@
from typing import Optional, Union
import torch
+from torch import nn
-from kornia.core import Module, Tensor, tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters import gaussian_blur2d, spatial_gradient
@@ -28,7 +28,7 @@ def _get_kernel_size(sigma: float) -> int:
ksize = int(2.0 * 4.0 * sigma + 1.0)
# matches OpenCV, but may cause padding problem for small images
- # PyTorch does not allow to pad more than original size.
+ # PyTorch does not allow to F.pad more than original size.
# Therefore there is a hack in forward function
if ksize % 2 == 0:
@@ -37,8 +37,11 @@ def _get_kernel_size(sigma: float) -> int:
def harris_response(
- input: Tensor, k: Union[Tensor, float] = 0.04, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None
-) -> Tensor:
+ input: torch.Tensor,
+ k: Union[torch.Tensor, float] = 0.04,
+ grads_mode: str = "sobel",
+ sigmas: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
r"""Compute the Harris cornerness function.
.. image:: _static/img/harris_response.png
@@ -48,7 +51,7 @@ def harris_response(
.. math::
R = max(0, det(M) - k \cdot trace(M)^2)
- where:
+ torch.where:
.. math::
M = \sum_{(x,y) \in W}
@@ -96,26 +99,26 @@ def harris_response(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
- if not isinstance(sigmas, Tensor):
- raise TypeError(f"sigmas type is not a Tensor. Got {type(sigmas)}")
+ if not isinstance(sigmas, torch.Tensor):
+ raise TypeError(f"sigmas type is not a torch.Tensor. Got {type(sigmas)}")
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
raise ValueError(f"Invalid sigmas shape, we expect B == input.size(0). Got: {sigmas.shape}")
- gradients: Tensor = spatial_gradient(input, grads_mode)
- dx: Tensor = gradients[:, :, 0]
- dy: Tensor = gradients[:, :, 1]
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode)
+ dx: torch.Tensor = gradients[:, :, 0]
+ dy: torch.Tensor = gradients[:, :, 1]
- # compute the structure tensor M elements
+ # compute the structure torch.tensor M elements
- dx2: Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
- dy2: Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
- dxy: Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
+ dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
+ dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
- det_m: Tensor = dx2 * dy2 - dxy * dxy
- trace_m: Tensor = dx2 + dy2
+ det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
+ trace_m: torch.Tensor = dx2 + dy2
# compute the response map
- scores: Tensor = det_m - k * (trace_m**2)
+ scores: torch.Tensor = det_m - k * (trace_m**2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -123,7 +126,9 @@ def harris_response(
return scores
-def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None) -> Tensor:
+def gftt_response(
+ input: torch.Tensor, grads_mode: str = "sobel", sigmas: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Compute the Shi-Tomasi cornerness function.
.. image:: _static/img/gftt_response.png
@@ -133,7 +138,7 @@ def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Ten
.. math::
R = min(eig(M))
- where:
+ torch.where:
.. math::
M = \sum_{(x,y) \in W}
@@ -176,21 +181,21 @@ def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Ten
# TODO: Recompute doctest
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- gradients: Tensor = spatial_gradient(input, grads_mode)
- dx: Tensor = gradients[:, :, 0]
- dy: Tensor = gradients[:, :, 1]
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode)
+ dx: torch.Tensor = gradients[:, :, 0]
+ dy: torch.Tensor = gradients[:, :, 1]
- dx2: Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
- dy2: Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
- dxy: Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
+ dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
+ dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
- det_m: Tensor = dx2 * dy2 - dxy * dxy
- trace_m: Tensor = dx2 + dy2
+ det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
+ trace_m: torch.Tensor = dx2 + dy2
- e1: Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))
- e2: Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))
+ e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))
+ e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))
- scores: Tensor = torch.min(e1, e2)
+ scores: torch.Tensor = torch.min(e1, e2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -198,7 +203,9 @@ def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Ten
return scores
-def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None) -> Tensor:
+def hessian_response(
+ input: torch.Tensor, grads_mode: str = "sobel", sigmas: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Compute the absolute of determinant of the Hessian matrix.
.. image:: _static/img/hessian_response.png
@@ -208,7 +215,7 @@ def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[
.. math::
R = det(H)
- where:
+ torch.where:
.. math::
M = \sum_{(x,y) \in W}
@@ -256,18 +263,18 @@ def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
- if not isinstance(sigmas, Tensor):
- raise TypeError(f"sigmas type is not a Tensor. Got {type(sigmas)}")
+ if not isinstance(sigmas, torch.Tensor):
+ raise TypeError(f"sigmas type is not a torch.Tensor. Got {type(sigmas)}")
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
raise ValueError(f"Invalid sigmas shape, we expect B == input.size(0). Got: {sigmas.shape}")
- gradients: Tensor = spatial_gradient(input, grads_mode, 2)
- dxx: Tensor = gradients[:, :, 0]
- dxy: Tensor = gradients[:, :, 1]
- dyy: Tensor = gradients[:, :, 2]
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode, 2)
+ dxx: torch.Tensor = gradients[:, :, 0]
+ dxy: torch.Tensor = gradients[:, :, 1]
+ dyy: torch.Tensor = gradients[:, :, 2]
- scores: Tensor = dxx * dyy - dxy**2
+ scores: torch.Tensor = dxx * dyy - dxy**2
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -275,11 +282,11 @@ def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[
return scores
-def dog_response(input: Tensor) -> Tensor:
+def dog_response(input: torch.Tensor) -> torch.Tensor:
r"""Compute the Difference-of-Gaussian response.
Args:
- input: a given the gaussian 5d tensor :math:`(B, C, D, H, W)`.
+ input: a given the gaussian 5d torch.tensor :math:`(B, C, D, H, W)`.
Return:
the response map per channel with shape :math:`(B, C, D-1, H, W)`.
@@ -290,13 +297,13 @@ def dog_response(input: Tensor) -> Tensor:
return input[:, :, 1:] - input[:, :, :-1]
-def dog_response_single(input: Tensor, sigma1: float = 1.0, sigma2: float = 1.6) -> Tensor:
+def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float = 1.6) -> torch.Tensor:
r"""Compute the Difference-of-Gaussian response.
.. image:: _static/img/dog_response_single.png
Args:
- input: a given the gaussian 4d tensor :math:`(B, C, H, W)`.
+ input: a given the gaussian 4d torch.tensor :math:`(B, C, H, W)`.
sigma1: lower gaussian sigma
sigma2: bigger gaussian sigma
@@ -312,8 +319,8 @@ def dog_response_single(input: Tensor, sigma1: float = 1.0, sigma2: float = 1.6)
return g2 - g1
-class BlobDoG(Module):
- r"""Module that calculates Difference-of-Gaussians blobs.
+class BlobDoG(nn.Module):
+ r"""nn.Module that calculates Difference-of-Gaussians blobs.
See
:func: `~kornia.feature.dog_response` for details.
@@ -325,12 +332,12 @@ class BlobDoG(Module):
def __repr__(self) -> str:
return self.__class__.__name__
- def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
return dog_response(input)
-class BlobDoGSingle(Module):
- r"""Module that calculates Difference-of-Gaussians blobs.
+class BlobDoGSingle(nn.Module):
+ r"""nn.Module that calculates Difference-of-Gaussians blobs.
.. image:: _static/img/dog_response_single.png
@@ -345,24 +352,24 @@ class BlobDoGSingle(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}, sigma1={self.sigma1}, sigma2={self.sigma2})"
- def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
return dog_response_single(input, self.sigma1, self.sigma2)
-class CornerHarris(Module):
- r"""Module that calculates Harris corners.
+class CornerHarris(nn.Module):
+ r"""nn.Module that calculates Harris corners.
.. image:: _static/img/harris_response.png
See :func:`~kornia.feature.harris_response` for details.
"""
- k: Tensor
+ k: torch.Tensor
- def __init__(self, k: Union[float, Tensor], grads_mode: str = "sobel") -> None:
+ def __init__(self, k: Union[float, torch.Tensor], grads_mode: str = "sobel") -> None:
super().__init__()
if isinstance(k, float):
- self.register_buffer("k", tensor(k))
+ self.register_buffer("k", torch.tensor(k))
else:
self.register_buffer("k", k)
self.grads_mode: str = grads_mode
@@ -370,12 +377,12 @@ class CornerHarris(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(k={self.k}, grads_mode={self.grads_mode})"
- def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
return harris_response(input, self.k, self.grads_mode, sigmas)
-class CornerGFTT(Module):
- r"""Module that calculates Shi-Tomasi corners.
+class CornerGFTT(nn.Module):
+ r"""nn.Module that calculates Shi-Tomasi corners.
.. image:: _static/img/gftt_response.png
@@ -389,12 +396,12 @@ class CornerGFTT(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
- def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
return gftt_response(input, self.grads_mode, sigmas)
-class BlobHessian(Module):
- r"""Module that calculates Hessian blobs.
+class BlobHessian(nn.Module):
+ r"""nn.Module that calculates Hessian blobs.
.. image:: _static/img/hessian_response.png
@@ -408,5 +415,5 @@ class BlobHessian(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
- def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
return hessian_response(input, self.grads_mode, sigmas)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 195969785..76f7589e3 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -16,13 +16,13 @@
#
import math
-from typing import List, Optional, Tuple
+from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
+from torch import nn
from typing_extensions import TypedDict
-from kornia.core import Device, Module, Tensor, concatenate, eye, tensor, where, zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.subpix import ConvSoftArgmax3d, NonMaximaSuppression2d
from kornia.geometry.transform import ScalePyramid, pyrdown, resize
@@ -32,19 +32,19 @@ from .orientation import PassLAF
from .responses import BlobHessian
-def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -> Tensor:
+def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:
r"""Auxiliary function for ScaleSpaceDetector.
Converts scale level index from ConvSoftArgmax3d to the actual
scale, using the sigmas from the ScalePyramid output.
Args:
- max_coords: tensor [BxNx3].
- sigmas: tensor [BxNxD], D >= 1
+ max_coords: torch.tensor [BxNx3].
+ sigmas: torch.tensor [BxNxD], D >= 1
num_levels: number of levels in the scale index.
Returns:
- tensor [BxNx3].
+ torch.tensor [BxNx3].
"""
# depth (scale) in coord_max is represented as (float) index, not the scale yet.
@@ -56,21 +56,21 @@ def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -
B, N, _ = max_coords.shape
scale_coords = max_coords[:, :, 0].contiguous().view(-1, 1, 1, 1)
# Replace the scale_x_y
- out = concatenate(
+ out = torch.cat(
[sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1), max_coords[:, :, 1:]], 2
)
return out
-def _create_octave_mask(mask: Tensor, octave_shape: List[int]) -> Tensor:
+def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:
r"""Downsample a mask based on the given octave shape."""
mask_shape = octave_shape[-2:]
mask_octave = F.interpolate(mask, mask_shape, mode="bilinear", align_corners=False)
return mask_octave.unsqueeze(1)
-class ScaleSpaceDetector(Module):
- r"""Module for differentiable local feature detection.
+class ScaleSpaceDetector(nn.Module):
+ r"""nn.Module for differentiable local feature detection.
As close as possible to classical local feature detectors
like Harris, Hessian-Affine or SIFT (DoG).
@@ -103,11 +103,11 @@ class ScaleSpaceDetector(Module):
self,
num_features: int = 500,
mr_size: float = 6.0,
- scale_pyr_module: Optional[Module] = None,
- resp_module: Optional[Module] = None,
- nms_module: Optional[Module] = None,
- ori_module: Optional[Module] = None,
- aff_module: Optional[Module] = None,
+ scale_pyr_module: Optional[nn.Module] = None,
+ resp_module: Optional[nn.Module] = None,
+ nms_module: Optional[nn.Module] = None,
+ ori_module: Optional[nn.Module] = None,
+ aff_module: Optional[nn.Module] = None,
minima_are_also_good: bool = False,
scale_space_response: bool = False,
) -> None:
@@ -148,13 +148,15 @@ class ScaleSpaceDetector(Module):
f"aff={self.aff.__repr__()})"
)
- def detect(self, img: Tensor, num_feats: int, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- dev: Device = img.device
+ def detect(
+ self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ dev: Union[str, torch.device, None] = img.device
dtype: torch.dtype = img.dtype
- sigmas: List[Tensor]
+ sigmas: List[torch.Tensor]
sp, sigmas, _ = self.scale_pyr(img)
- all_responses: List[Tensor] = []
- all_lafs: List[Tensor] = []
+ all_responses: List[torch.Tensor] = []
+ all_lafs: List[torch.Tensor] = []
px_size = 0.5 if self.scale_pyr.double_image else 1.0
for oct_idx, octave in enumerate(sp):
sigmas_oct = sigmas[oct_idx]
@@ -169,16 +171,16 @@ class ScaleSpaceDetector(Module):
# We want nms for scale responses, so reorder to (B, CH, L, H, W)
oct_resp = oct_resp.permute(0, 2, 1, 3, 4)
# 3rd extra level is required for DoG only
- if isinstance(self.scale_pyr.extra_levels, Tensor) and self.scale_pyr.extra_levels % 2 != 0:
+ if isinstance(self.scale_pyr.extra_levels, torch.Tensor) and self.scale_pyr.extra_levels % 2 != 0:
oct_resp = oct_resp[:, :, :-1]
if mask is not None:
- oct_mask: Tensor = _create_octave_mask(mask, oct_resp.shape)
+ oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)
oct_resp = oct_mask * oct_resp
# Differentiable nms
- coord_max: Tensor
- response_max: Tensor
+ coord_max: torch.Tensor
+ response_max: torch.Tensor
coord_max, response_max = self.nms(oct_resp)
if self.minima_are_also_good:
coord_min, response_min = self.nms(-oct_resp)
@@ -200,21 +202,21 @@ class ScaleSpaceDetector(Module):
# Converts scale level index from ConvSoftArgmax3d to the actual scale, using the sigmas
- if isinstance(self.scale_pyr.n_levels, Tensor):
+ if isinstance(self.scale_pyr.n_levels, torch.Tensor):
num_levels = int(self.scale_pyr.n_levels.item())
elif isinstance(self.scale_pyr.n_levels, int):
num_levels = self.scale_pyr.n_levels
else:
raise TypeError(
- "Expected the scale pyramid module to have `n_levels` as a Tensor or int."
+ "Expected the scale pyramid module to have `n_levels` as a torch.Tensor or int."
f"Gotcha {type(self.scale_pyr.n_levels)}"
)
max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct, num_levels)
# Create local affine frames (LAFs)
- rotmat = eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
- current_lafs = concatenate(
+ rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
+ current_lafs = torch.cat(
[
self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,
max_coords_best[:, :, 1:3].view(B, N, 2, 1),
@@ -234,13 +236,13 @@ class ScaleSpaceDetector(Module):
px_size *= 2
# Sort and keep best n
- responses = concatenate(all_responses, 1)
- lafs = concatenate(all_lafs, 1)
+ responses = torch.cat(all_responses, 1)
+ lafs = torch.cat(all_lafs, 1)
responses, idxs = torch.topk(responses, k=num_feats, dim=1)
lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))
return responses, lafs
- def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Three stage local feature detection.
First the location and scale of interest points are determined by detect function.
@@ -248,7 +250,7 @@ class ScaleSpaceDetector(Module):
Args:
img: image to extract features with shape [BxCxHxW]
- mask: a mask with weights where to apply the response function. The shape must be the same as
+ mask: a mask with weights torch.where to apply the response function. The shape must be the same as
the input image.
Returns:
@@ -276,7 +278,7 @@ def get_default_detector_config() -> Detector_config:
return _DEFAULT_DETECTOR_CONFIG.copy()
-class MultiResolutionDetector(Module):
+class MultiResolutionDetector(nn.Module):
"""Multi-scale feature detector, based on code from KeyNet. Can be used with any response function.
This is based on the original code from paper
@@ -296,11 +298,11 @@ class MultiResolutionDetector(Module):
def __init__(
self,
- model: Module,
+ model: nn.Module,
num_features: int = 2048,
config: Optional[Detector_config] = None,
- ori_module: Optional[Module] = None,
- aff_module: Optional[Module] = None,
+ ori_module: Optional[nn.Module] = None,
+ aff_module: Optional[nn.Module] = None,
) -> None:
super().__init__()
self.model = model
@@ -316,24 +318,24 @@ class MultiResolutionDetector(Module):
self.num_features = num_features
if ori_module is None:
- self.ori: Module = PassLAF()
+ self.ori: nn.Module = PassLAF()
else:
self.ori = ori_module
if aff_module is None:
- self.aff: Module = PassLAF()
+ self.aff: nn.Module = PassLAF()
else:
self.aff = aff_module
- def remove_borders(self, score_map: Tensor, borders: int = 15) -> Tensor:
+ def remove_borders(self, score_map: torch.Tensor, borders: int = 15) -> torch.Tensor:
"""Remove the borders of the image to avoid detections on the corners."""
mask = torch.zeros_like(score_map)
mask[:, :, borders:-borders, borders:-borders] = 1
return mask * score_map
def detect_features_on_single_level(
- self, level_img: Tensor, num_kp: int, factor: Tuple[float, float]
- ) -> Tuple[Tensor, Tensor]:
+ self, level_img: torch.Tensor, num_kp: int, factor: Tuple[float, float]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
det_map = self.nms(self.remove_borders(self.model(level_img)))
device = level_img.device
dtype = level_img.dtype
@@ -342,16 +344,18 @@ class MultiResolutionDetector(Module):
scores_sorted, indices = torch.sort(scores, descending=True)
- indices = indices[where(scores_sorted > 0.0)]
+ indices = indices[torch.where(scores_sorted > 0.0)]
yx = yx[:, indices[:num_kp]].t()
current_kp_num = len(yx)
- xy_projected = yx.view(1, current_kp_num, 2).flip(2) * tensor(factor, device=device, dtype=dtype)
+ xy_projected = yx.view(1, current_kp_num, 2).flip(2) * torch.tensor(factor, device=device, dtype=dtype)
scale_factor = 0.5 * (factor[0] + factor[1])
scale = scale_factor * self.mr_size * torch.ones(1, current_kp_num, 1, 1, device=device, dtype=dtype)
- lafs = laf_from_center_scale_ori(xy_projected, scale, zeros(1, current_kp_num, 1, device=device, dtype=dtype))
+ lafs = laf_from_center_scale_ori(
+ xy_projected, scale, torch.zeros(1, current_kp_num, 1, device=device, dtype=dtype)
+ )
return scores_sorted[:num_kp], lafs
- def detect(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def detect(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
# Compute points per level
num_features_per_level: List[float] = []
tmp = 0.0
@@ -366,8 +370,8 @@ class MultiResolutionDetector(Module):
_, _, h, w = img.shape
img_up = img
cur_img = img
- all_responses: List[Tensor] = []
- all_lafs: List[Tensor] = []
+ all_responses: List[torch.Tensor] = []
+ all_lafs: List[torch.Tensor] = []
# Extract features from the upper levels
for idx_level in range(self.num_upscale_levels):
nf = num_features_per_level[len(num_features_per_level) - self.num_pyramid_levels - 1 - (idx_level + 1)]
@@ -396,20 +400,20 @@ class MultiResolutionDetector(Module):
num_points_level = int(num_features_per_level[idx_level])
if idx_level > 0 or (self.num_upscale_levels > 0):
nf2 = [num_features_per_level[a] for a in range(0, idx_level + 1 + self.num_upscale_levels)]
- res_points = tensor(nf2).sum().item()
+ res_points = torch.tensor(nf2).sum().item()
num_points_level = int(res_points)
cur_scores, cur_lafs = self.detect_features_on_single_level(cur_img, num_points_level, factor)
all_responses.append(cur_scores.view(1, -1))
all_lafs.append(cur_lafs)
- responses = concatenate(all_responses, 1)
- lafs = concatenate(all_lafs, 1)
+ responses = torch.cat(all_responses, 1)
+ lafs = torch.cat(all_lafs, 1)
if lafs.shape[1] > self.num_features:
responses, idxs = torch.topk(responses, k=self.num_features, dim=1)
lafs = torch.gather(lafs, 1, idxs[..., None, None].expand(-1, -1, 2, 3))
return responses, lafs
- def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Three stage local feature detection.
First the location and scale of interest points are determined by detect function.
@@ -418,7 +422,7 @@ class MultiResolutionDetector(Module):
Args:
img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
because the number of detections is different on each image.
- mask: a mask with weights where to apply the response function. The shape must be the same as
+ mask: a mask with weights torch.where to apply the response function. The shape must be the same as
the input image.
Returns:
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 2f888ab2c..e3b2a6f04 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -19,15 +19,15 @@ import math
from typing import Tuple
import torch
+import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor, concatenate, eye, normalize
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
-def _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:
+def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
"""Return neigh2channels conv kernel."""
numel: int = kd * ky * kx
@@ -42,15 +42,15 @@ def _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:
cache = _get_reshape_kernel._eye_cache # type: ignore[attr-defined]
res = cache.get(numel)
if res is None:
- res = eye(numel)
+ res = torch.eye(numel)
cache[numel] = res
return res.view(numel, kd, ky, kx)
else:
# fallback to normal allocation for big kernels
- return eye(numel).view(numel, kd, ky, kx)
+ return torch.eye(numel).view(numel, kd, ky, kx)
-def get_sift_pooling_kernel(ksize: int = 25) -> Tensor:
+def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
r"""Return a weighted pooling kernel for SIFT descriptor.
Args:
@@ -90,8 +90,8 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tup
return ksize, stride, pad
-class SIFTDescriptor(Module):
- r"""Module which computes SIFT descriptors of given patches.
+class SIFTDescriptor(nn.Module):
+ r"""nn.Module which computes SIFT descriptors of given patches.
Args:
patch_size: Input patch size in pixels.
@@ -157,13 +157,13 @@ class SIFTDescriptor(Module):
)
self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))
- def get_pooling_kernel(self) -> Tensor:
+ def get_pooling_kernel(self) -> torch.Tensor:
return self.pk.weight.detach()
- def get_weighting_kernel(self) -> Tensor:
+ def get_weighting_kernel(self) -> torch.Tensor:
return self.gk.detach()
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])
B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
@@ -185,7 +185,7 @@ class SIFTDescriptor(Module):
wo0_big = (1.0 - wo1_big_) * mag
wo1_big = wo1_big_ * mag
- ang_bins = concatenate(
+ ang_bins = torch.cat(
[
self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big)
for i in range(0, self.num_ang_bins)
@@ -193,22 +193,22 @@ class SIFTDescriptor(Module):
1,
)
ang_bins = ang_bins.view(B, -1)
- ang_bins = normalize(ang_bins, p=2)
+ ang_bins = F.normalize(ang_bins, p=2)
ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))
- ang_bins = normalize(ang_bins, p=2)
+ ang_bins = F.normalize(ang_bins, p=2)
if self.rootsift:
- ang_bins = torch.sqrt(normalize(ang_bins, p=1) + self.eps)
+ ang_bins = torch.sqrt(F.normalize(ang_bins, p=1) + self.eps)
return ang_bins
def sift_describe(
- input: Tensor,
+ input: torch.Tensor,
patch_size: int = 41,
num_ang_bins: int = 8,
num_spatial_bins: int = 4,
rootsift: bool = True,
clipval: float = 0.2,
-) -> Tensor:
+) -> torch.Tensor:
r"""Compute the sift descriptor.
See
@@ -217,8 +217,8 @@ def sift_describe(
return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)
-class DenseSIFTDescriptor(Module):
- """Module, which computes SIFT descriptor densely over the image.
+class DenseSIFTDescriptor(nn.Module):
+ """nn.Module, which computes SIFT descriptor densely over the image.
Args:
num_ang_bins: Number of angular bins. (8 is default)
@@ -231,7 +231,7 @@ class DenseSIFTDescriptor(Module):
padding: default 0
Returns:
- Tensor: DenseSIFT descriptor of the image
+ torch.Tensor: DenseSIFT descriptor of the image
Shape:
- Input: (B, 1, H, W)
@@ -302,14 +302,14 @@ class DenseSIFTDescriptor(Module):
PoolingConv.weight.data.copy_(self._poolingconv_weight)
self.PoolingConv = PoolingConv
- # Cache pooling kernel tensor for fast return in get_pooling_kernel
+ # Cache pooling kernel torch.tensor for fast return in get_pooling_kernel
self._pooling_kernel = self._bin_pooling_kernel_weight.detach()
- def get_pooling_kernel(self) -> Tensor:
+ def get_pooling_kernel(self) -> torch.Tensor:
# Return the cached detached pooling kernel directly for optimal speed
return self._pooling_kernel
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])
_B, _CH, _W, _H = input.size()
@@ -329,7 +329,7 @@ class DenseSIFTDescriptor(Module):
bo1_big = (bo0_big + 1) % self.num_ang_bins
wo0_big = (1.0 - wo1_big_) * mag
wo1_big = wo1_big_ * mag
- ang_bins = concatenate(
+ ang_bins = torch.cat(
[
self.bin_pooling_kernel(
(bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big
@@ -340,8 +340,8 @@ class DenseSIFTDescriptor(Module):
)
out_no_norm = self.PoolingConv(ang_bins)
- out = normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))
- out = normalize(out, dim=1, p=2)
+ out = F.normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))
+ out = F.normalize(out, dim=1, p=2)
if self.rootsift:
- out = torch.sqrt(normalize(out, p=1) + self.eps)
+ out = torch.sqrt(F.normalize(out, p=1) + self.eps)
return out
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 6cec74c41..306c11146 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -26,8 +26,6 @@ import torch.nn.functional as F
from torch import nn
from torch.nn.functional import pixel_shuffle, softmax
-from kornia.core import Module, Tensor
-
class HourglassConfig(NamedTuple):
depth: int
@@ -35,11 +33,11 @@ class HourglassConfig(NamedTuple):
num_blocks: int
num_classes: int
input_channels: int
- head: Type[Module]
+ head: Type[nn.Module]
# [Hourglass backbone classes]
-class HourglassBackbone(Module):
+class HourglassBackbone(nn.Module):
"""Hourglass network, taken from https://github.com/zhou13/lcnn.
Args:
@@ -58,11 +56,11 @@ class HourglassBackbone(Module):
self.head = MultitaskHead
self.net = hg(HourglassConfig(depth, num_stacks, num_blocks, num_classes, input_channel, head=self.head))
- def forward(self, input_images: Tensor) -> Tensor:
+ def forward(self, input_images: torch.Tensor) -> torch.Tensor:
return self.net(input_images)
-class MultitaskHead(Module):
+class MultitaskHead(nn.Module):
def __init__(self, input_channels: int) -> None:
super().__init__()
@@ -80,13 +78,17 @@ class MultitaskHead(Module):
)
self.heads = nn.ModuleList(heads)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.cat([head(x) for head in self.heads], dim=1)
-class Bottleneck2D(Module):
+class Bottleneck2D(nn.Module):
def __init__(
- self, inplanes: int, planes: int, stride: Union[int, Tuple[int, int]] = 1, downsample: Optional[Module] = None
+ self,
+ inplanes: int,
+ planes: int,
+ stride: Union[int, Tuple[int, int]] = 1,
+ downsample: Optional[nn.Module] = None,
) -> None:
super().__init__()
@@ -100,7 +102,7 @@ class Bottleneck2D(Module):
self.downsample = downsample
self.stride = stride
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = x
out = self.bn1(x)
@@ -123,7 +125,7 @@ class Bottleneck2D(Module):
return out
-class Hourglass(Module):
+class Hourglass(nn.Module):
def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2) -> None:
super().__init__()
self.depth = depth
@@ -131,7 +133,7 @@ class Hourglass(Module):
self.expansion = expansion
self.hg = self._make_hour_glass(block, num_blocks, planes, depth)
- def _make_residual(self, block: Type[Bottleneck2D], num_blocks: int, planes: int) -> Module:
+ def _make_residual(self, block: Type[Bottleneck2D], num_blocks: int, planes: int) -> nn.Module:
layers = []
for _ in range(0, num_blocks):
layers.append(block(planes * self.expansion, planes))
@@ -148,7 +150,7 @@ class Hourglass(Module):
hgl.append(nn.ModuleList(res))
return nn.ModuleList(hgl)
- def _hour_glass_forward(self, n: int, x: Tensor) -> Tensor:
+ def _hour_glass_forward(self, n: int, x: torch.Tensor) -> torch.Tensor:
up1 = self.hg[n - 1][0](x) # type: ignore[index]
low1 = F.max_pool2d(x, 2, stride=2)
low1 = self.hg[n - 1][1](low1) # type: ignore[index]
@@ -162,17 +164,17 @@ class Hourglass(Module):
out = up1 + up2
return out
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return self._hour_glass_forward(self.depth, x)
-class HourglassNet(Module):
+class HourglassNet(nn.Module):
"""Hourglass model from Newell et al ECCV 2016."""
def __init__(
self,
block: Type[Bottleneck2D],
- head: Type[Module],
+ head: Type[nn.Module],
depth: int,
num_stacks: int,
num_blocks: int,
@@ -214,7 +216,7 @@ class HourglassNet(Module):
def _make_residual(
self, block: Type[Bottleneck2D], planes: int, blocks: int, stride: Union[int, Tuple[int, int]] = 1
- ) -> Module:
+ ) -> nn.Module:
downsample = None
if stride != 1 or self.inplanes != planes * self.expansion:
downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes * self.expansion, kernel_size=1, stride=stride))
@@ -227,12 +229,12 @@ class HourglassNet(Module):
return nn.Sequential(*layers)
- def _make_fc(self, inplanes: int, outplanes: int) -> Module:
+ def _make_fc(self, inplanes: int, outplanes: int) -> nn.Module:
bn = nn.BatchNorm2d(inplanes)
conv = nn.Conv2d(inplanes, outplanes, kernel_size=1)
return nn.Sequential(conv, bn, self.relu)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
out = []
x = self.conv1(x)
x = self.bn1(x)
@@ -271,7 +273,7 @@ def hg(cfg: HourglassConfig) -> HourglassNet:
# [Backbone decoders]
-class SuperpointDecoder(Module):
+class SuperpointDecoder(nn.Module):
"""Junction decoder based on the SuperPoint architecture.
Args:
@@ -290,7 +292,7 @@ class SuperpointDecoder(Module):
self.convPb = nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0)
self.grid_size = grid_size
- def forward(self, input_features: Tensor) -> Tensor:
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -300,7 +302,7 @@ class SuperpointDecoder(Module):
return junc_pred
-class PixelShuffleDecoder(Module):
+class PixelShuffleDecoder(nn.Module):
"""Pixel shuffle decoder used to predict the line heatmap.
Args:
@@ -354,7 +356,7 @@ class PixelShuffleDecoder(Module):
return [256, 64, 16]
return [256, 64, 16, 4]
- def forward(self, input_features: Tensor) -> Tensor:
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
# Iterate til output block
out = input_features
for block in self.conv_block_lst[:-1]:
@@ -368,7 +370,7 @@ class PixelShuffleDecoder(Module):
return heatmap
-class SuperpointDescriptor(Module):
+class SuperpointDescriptor(nn.Module):
"""Descriptor decoder based on the SuperPoint arcihtecture.
Args:
@@ -385,7 +387,7 @@ class SuperpointDescriptor(Module):
self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1)
self.convPb = nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)
- def forward(self, input_features: Tensor) -> Tensor:
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -395,7 +397,7 @@ class SuperpointDescriptor(Module):
# [Combination of all previous models in one]
-class SOLD2Net(Module):
+class SOLD2Net(nn.Module):
"""Full network for SOLDΒ².
Args:
@@ -427,7 +429,7 @@ class SOLD2Net(Module):
if "use_descriptor" in self.cfg:
self.descriptor_decoder = SuperpointDescriptor(feat_channel)
- def forward(self, input_images: Tensor) -> Dict[str, Tensor]:
+ def forward(self, input_images: torch.Tensor) -> Dict[str, torch.Tensor]:
# The backbone
features = self.backbone_net(input_images)
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index a275b468a..a70a2750a 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -20,8 +20,8 @@ from typing import Any, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfg
from kornia.geometry.conversions import normalize_pixel_coordinates
@@ -34,8 +34,8 @@ urls: Dict[str, str] = {}
urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth"
-class SOLD2(Module):
- r"""Module, which detects and describe line segments in an image.
+class SOLD2(nn.Module):
+ r"""nn.Module, which detects and describe line segments in an image.
This is based on the original code from the paper "SOLDΒ²: Self-supervised
Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
@@ -93,7 +93,7 @@ class SOLD2(Module):
# Initialize the line matcher
self.line_matcher = WunschLineMatcher(self.config.line_matcher_cfg)
- def forward(self, img: Tensor) -> Dict[str, Any]:
+ def forward(self, img: torch.Tensor) -> Dict[str, Any]:
"""Run forward.
Args:
@@ -128,7 +128,9 @@ class SOLD2(Module):
return outputs
- def match(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor:
+ def match(
+ self, line_seg1: torch.Tensor, line_seg2: torch.Tensor, desc1: torch.Tensor, desc2: torch.Tensor
+ ) -> torch.Tensor:
"""Find the best matches between two sets of line segments and their corresponding descriptors.
Args:
@@ -155,7 +157,7 @@ class SOLD2(Module):
return state_dict
-class WunschLineMatcher(Module):
+class WunschLineMatcher(nn.Module):
"""Class matching two sets of line segments with the Needleman-Wunsch algorithm.
TODO: move it later in kornia.feature.matching
@@ -174,7 +176,9 @@ class WunschLineMatcher(Module):
self.grid_size = self.config.grid_size
self.line_score = self.config.line_score
- def forward(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor:
+ def forward(
+ self, line_seg1: torch.Tensor, line_seg2: torch.Tensor, desc1: torch.Tensor, desc2: torch.Tensor
+ ) -> torch.Tensor:
"""Find the best matches between two sets of line segments and their corresponding descriptors."""
KORNIA_CHECK_SHAPE(line_seg1, ["N", "2", "2"])
KORNIA_CHECK_SHAPE(line_seg2, ["N", "2", "2"])
@@ -222,17 +226,17 @@ class WunschLineMatcher(Module):
return matches
- def sample_line_points(self, line_seg: Tensor) -> Tuple[Tensor, Tensor]:
+ def sample_line_points(self, line_seg: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Regularly sample points along each line segments, with a minimal distance between each point.
Pad the remaining points.
Args:
- line_seg: an Nx2x2 Tensor.
+ line_seg: an Nx2x2 torch.Tensor.
Returns:
- line_points: an N x num_samples x 2 Tensor.
- valid_points: a boolean N x num_samples Tensor.
+ line_points: an N x num_samples x 2 torch.Tensor.
+ valid_points: a boolean N x num_samples torch.Tensor.
"""
_N, _, _ = line_seg.shape
M = self.num_samples
@@ -252,17 +256,17 @@ class WunschLineMatcher(Module):
return pts, valid
- def filter_and_match_lines(self, scores: Tensor) -> Tensor:
+ def filter_and_match_lines(self, scores: torch.Tensor) -> torch.Tensor:
"""Use scores to keep the top k best lines.
Compute the Needleman- Wunsch algorithm on each candidate pairs, and keep the highest score.
Args:
- scores: a (N, M, n, n) Tensor containing the pairwise scores
+ scores: a (N, M, n, n) torch.Tensor containing the pairwise scores
of the elements to match.
Returns:
- matches: a (N) Tensor containing the indices of the best match
+ matches: a (N) torch.Tensor containing the indices of the best match
"""
KORNIA_CHECK_SHAPE(scores, ["M", "N", "n", "n"])
@@ -280,7 +284,7 @@ class WunschLineMatcher(Module):
top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)
# Consider the reversed line segments as well
- top_scores = concatenate([top_scores, torch.flip(top_scores, dims=[-1])], 1)
+ top_scores = torch.cat([top_scores, torch.flip(top_scores, dims=[-1])], 1)
# Compute the line distance matrix with Needleman-Wunsch algo and
# retrieve the closest line neighbor
@@ -292,14 +296,14 @@ class WunschLineMatcher(Module):
matches = topk_lines[torch.arange(n_lines1), matches]
return matches
- def needleman_wunsch(self, scores: Tensor) -> Tensor:
+ def needleman_wunsch(self, scores: torch.Tensor) -> torch.Tensor:
"""Batched implementation of the Needleman-Wunsch algorithm.
The cost of the InDel operation is set to 0 by subtracting the gap
penalty to the scores.
Args:
- scores: a (B, N, M) Tensor containing the pairwise scores
+ scores: a (B, N, M) torch.Tensor containing the pairwise scores
of the elements to match.
"""
KORNIA_CHECK_SHAPE(scores, ["B", "N", "M"])
@@ -315,16 +319,16 @@ class WunschLineMatcher(Module):
j = k - i
up = dp[:, i - 1, j]
left = dp[:, i, j - 1]
- diag = dp[:, i - 1, j - 1] + S[:, i - 1, j - 1]
- dp[:, i, j] = torch.max(torch.max(up, left), diag)
+ torch.diag = dp[:, i - 1, j - 1] + S[:, i - 1, j - 1]
+ dp[:, i, j] = torch.max(torch.max(up, left), torch.diag)
return dp[:, -1, -1]
-def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor:
+def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> torch.Tensor:
"""Convert a list of keypoints into a grid in [-1, 1]Β² that can be used in torch.nn.functional.interpolate.
Args:
- keypoints: a tensor [N, 2] of N keypoints (ij coordinates convention).
+ keypoints: a torch.tensor [N, 2] of N keypoints (ij coordinates convention).
img_size: the original image size (H, W)
"""
@@ -335,8 +339,8 @@ def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor:
return grid_points
-def batched_linspace(start: Tensor, end: Tensor, step: int, dim: int) -> Tensor:
- """Batch version of torch.normalize (similar to the numpy one)."""
+def batched_linspace(start: torch.Tensor, end: torch.Tensor, step: int, dim: int) -> torch.Tensor:
+ """Batch version of torch.F.normalize (similar to the numpy one)."""
intervals = ((end - start) / (step - 1)).unsqueeze(dim)
broadcast_size = [1] * len(intervals.shape)
broadcast_size[dim] = step
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 835803b5f..915270ea3 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -20,8 +20,8 @@ import warnings
from typing import Any, Dict, Optional, Tuple
import torch
+from torch import nn
-from kornia.core import Module, Tensor, concatenate, sin, stack, tensor, where, zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfg
from kornia.geometry.bbox import nms
@@ -33,8 +33,8 @@ urls: Dict[str, str] = {}
urls["wireframe"] = "https://cvg-data.inf.ethz.ch/SOLD2/sold2_wireframe.tar"
-class SOLD2_detector(Module):
- r"""Module, which detects line segments in an image.
+class SOLD2_detector(nn.Module):
+ r"""nn.Module, which detects line segments in an image.
This is based on the original code from the paper "SOLDΒ²: Self-supervised
Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
@@ -94,7 +94,7 @@ class SOLD2_detector(Module):
del state_dict["heatmap_decoder.conv_block_lst.2.bias"]
return state_dict
- def forward(self, img: Tensor) -> Dict[str, Any]:
+ def forward(self, img: torch.Tensor) -> Dict[str, Any]:
"""Run forward.
Args:
@@ -129,7 +129,7 @@ class SOLD2_detector(Module):
class LineSegmentDetectionModule:
- r"""Module extracting line segments from junctions and line heatmaps.
+ r"""nn.Module extracting line segments from junctions and line heatmaps.
Args:
config (LineDetectorCfg): Configuration dataclass containing all settings required for line segment detection.
@@ -175,7 +175,7 @@ class LineSegmentDetectionModule:
self.low_thresh = self.config.heatmap_low_thresh
self.high_thresh = self.config.heatmap_high_thresh
- # Pre-compute the linspace sampler
+ # Pre-compute the torch.linspace sampler
self.torch_sampler = torch.linspace(0, 1, self.num_samples)
# Long line segment suppression configuration
@@ -194,7 +194,7 @@ class LineSegmentDetectionModule:
if self.use_junction_refinement and self.junction_refine_cfg is None:
raise ValueError("[Error] Missing junction refinement config.")
- def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
+ def detect(self, junctions: torch.Tensor, heatmap: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Perform line segment detection."""
KORNIA_CHECK_SHAPE(heatmap, ["H", "W"])
H, W = heatmap.shape
@@ -217,7 +217,7 @@ class LineSegmentDetectionModule:
# Initialize empty line map
num_junctions = len(junctions)
- line_map_pred = zeros([num_junctions, num_junctions], device=device, dtype=torch.int32)
+ line_map_pred = torch.zeros([num_junctions, num_junctions], device=device, dtype=torch.int32)
# Stop if there are not enough junctions
if num_junctions < 2:
@@ -233,8 +233,8 @@ class LineSegmentDetectionModule:
candidate_map = self.candidate_suppression(junctions, candidate_map)
# Fetch the candidates
- candidate_indices = where(candidate_map)
- candidate_index_map = concatenate([candidate_indices[0][..., None], candidate_indices[1][..., None]], -1)
+ candidate_indices = torch.where(candidate_map)
+ candidate_index_map = torch.cat([candidate_indices[0][..., None], candidate_indices[1][..., None]], -1)
# Get the corresponding start and end junctions
candidate_junc_start = junctions[candidate_index_map[:, 0]]
@@ -273,7 +273,7 @@ class LineSegmentDetectionModule:
normalized_seg_length_ = normalized_seg_length[iter_idx * group_size :]
sampled_feat_ = self.detect_local_max(heatmap, cand_h_, cand_w_, H, W, normalized_seg_length_, device)
sampled_feat_lst.append(sampled_feat_)
- sampled_feat = concatenate(sampled_feat_lst, 0)
+ sampled_feat = torch.cat(sampled_feat_lst, 0)
else:
sampled_feat = self.detect_local_max(heatmap, cand_h, cand_w, H, W, normalized_seg_length, device)
@@ -298,7 +298,7 @@ class LineSegmentDetectionModule:
return line_map_pred, junctions, heatmap
- def refine_heatmap(self, heatmap: Tensor, ratio: float = 0.2, valid_thresh: float = 1e-2) -> Tensor:
+ def refine_heatmap(self, heatmap: torch.Tensor, ratio: float = 0.2, valid_thresh: float = 1e-2) -> torch.Tensor:
"""Global heatmap refinement method."""
# Grab the top 10% values
heatmap_values = heatmap[heatmap > valid_thresh]
@@ -310,12 +310,12 @@ class LineSegmentDetectionModule:
def refine_heatmap_local(
self,
- heatmap: Tensor,
+ heatmap: torch.Tensor,
num_blocks: int = 5,
overlap_ratio: float = 0.5,
ratio: float = 0.2,
valid_thresh: float = 2e-3,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Local heatmap refinement method."""
# Get the shape of the heatmap
H, W = heatmap.shape
@@ -324,8 +324,8 @@ class LineSegmentDetectionModule:
w_block = round(W / (1 + (num_blocks - 1) * increase_ratio))
# Iterate through each block
- count_map = zeros(heatmap.shape, dtype=torch.int, device=heatmap.device)
- heatmap_output = zeros(heatmap.shape, dtype=torch.float, device=heatmap.device)
+ count_map = torch.zeros(heatmap.shape, dtype=torch.int, device=heatmap.device)
+ heatmap_output = torch.zeros(heatmap.shape, dtype=torch.float, device=heatmap.device)
for h_idx in range(num_blocks):
for w_idx in range(num_blocks):
# Fetch the heatmap
@@ -345,7 +345,7 @@ class LineSegmentDetectionModule:
return heatmap_output
- def candidate_suppression(self, junctions: Tensor, candidate_map: Tensor) -> Tensor:
+ def candidate_suppression(self, junctions: torch.Tensor, candidate_map: torch.Tensor) -> torch.Tensor:
"""Suppress overlapping long lines in the candidate segments."""
# Define the distance tolerance
dist_tolerance = self.nms_dist_tolerance
@@ -355,7 +355,7 @@ class LineSegmentDetectionModule:
line_dist_map = torch.sum((torch.unsqueeze(junctions, dim=1) - junctions[None, ...]) ** 2, dim=-1) ** 0.5
# Fetch all the "detected lines"
- seg_indexes = where(torch.triu(candidate_map, diagonal=1))
+ seg_indexes = torch.where(torch.triu(candidate_map, diagonal=1))
start_point_idxs = seg_indexes[0]
end_point_idxs = seg_indexes[1]
start_points = junctions[start_point_idxs, :]
@@ -376,7 +376,7 @@ class LineSegmentDetectionModule:
cand_angles = torch.acos(
torch.einsum("bij,bjk->bik", cand_vecs, dir_vecs[..., None]) / cand_vecs_norm[..., None]
)
- cand_dists = cand_vecs_norm[..., None] * sin(cand_angles)
+ cand_dists = cand_vecs_norm[..., None] * torch.sin(cand_angles)
junc_dist_mask = cand_dists <= dist_tolerance
junc_mask = junc_dist_mask * proj_mask
@@ -393,8 +393,14 @@ class LineSegmentDetectionModule:
return candidate_map
def refine_junction_perturb(
- self, junctions: Tensor, line_map: Tensor, heatmap: Tensor, H: int, W: int, device: torch.device
- ) -> Tuple[Tensor, Tensor]:
+ self,
+ junctions: torch.Tensor,
+ line_map: torch.Tensor,
+ heatmap: torch.Tensor,
+ H: int,
+ W: int,
+ device: torch.device,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
"""Refine the line endpoints in a similar way as in LSD."""
# Fetch refinement parameters
if not isinstance(self.junction_refine_cfg, JunctionRefineCfg):
@@ -418,16 +424,14 @@ class LineSegmentDetectionModule:
[perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing="ij"
)
- perturb_tensor = concatenate(
- [h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], -1
- )
+ perturb_tensor = torch.cat([h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], -1)
perturb_tensor_flat = perturb_tensor.view(-1, 2, 2)
# Fetch all the detected lines
- detected_seg_indexes = where(torch.triu(line_map, diagonal=1))
+ detected_seg_indexes = torch.where(torch.triu(line_map, diagonal=1))
start_points = junctions[detected_seg_indexes[0]]
end_points = junctions[detected_seg_indexes[1]]
- line_segments = stack([start_points, end_points], 1)
+ line_segments = torch.stack([start_points, end_points], 1)
line_segment_candidates = line_segments.unsqueeze(dim=1) + perturb_tensor_flat[None]
# Clip the boundaries
@@ -459,24 +463,24 @@ class LineSegmentDetectionModule:
refined_segment_lst.append(segment[max_idx][None])
# Concatenate back to segments
- refined_segments = concatenate(refined_segment_lst, 0)
+ refined_segments = torch.cat(refined_segment_lst, 0)
# Convert back to junctions and line_map
- junctions_new = concatenate([refined_segments[:, 0, :], refined_segments[:, 1, :]], 0)
+ junctions_new = torch.cat([refined_segments[:, 0, :], refined_segments[:, 1, :]], 0)
junctions_new = torch.unique(junctions_new, dim=0)
line_map_new = self.segments_to_line_map(junctions_new, refined_segments)
return junctions_new, line_map_new
- def segments_to_line_map(self, junctions: Tensor, segments: Tensor) -> Tensor:
+ def segments_to_line_map(self, junctions: torch.Tensor, segments: torch.Tensor) -> torch.Tensor:
"""Convert the list of segments to line map."""
# Create empty line map
num_junctions = len(junctions)
- line_map = zeros([num_junctions, num_junctions], device=junctions.device)
+ line_map = torch.zeros([num_junctions, num_junctions], device=junctions.device)
# Get the indices of paired junctions
- _, idx_junc1 = where(torch.all(junctions[None] == segments[:, None, 0], dim=2))
- _, idx_junc2 = where(torch.all(junctions[None] == segments[:, None, 1], dim=2))
+ _, idx_junc1 = torch.where(torch.all(junctions[None] == segments[:, None, 0], dim=2))
+ _, idx_junc2 = torch.where(torch.all(junctions[None] == segments[:, None, 1], dim=2))
# Assign the labels
line_map[idx_junc1, idx_junc2] = 1
@@ -484,7 +488,7 @@ class LineSegmentDetectionModule:
return line_map
- def detect_bilinear(self, heatmap: Tensor, cand_h: Tensor, cand_w: Tensor) -> Tensor:
+ def detect_bilinear(self, heatmap: torch.Tensor, cand_h: torch.Tensor, cand_w: torch.Tensor) -> torch.Tensor:
"""Detect by bilinear sampling."""
# Get the floor and ceiling locations
cand_h_floor = torch.floor(cand_h).to(torch.long)
@@ -504,14 +508,14 @@ class LineSegmentDetectionModule:
def detect_local_max(
self,
- heatmap: Tensor,
- cand_h: Tensor,
- cand_w: Tensor,
+ heatmap: torch.Tensor,
+ cand_h: torch.Tensor,
+ cand_w: torch.Tensor,
H: int,
W: int,
- normalized_seg_length: Tensor,
+ normalized_seg_length: torch.Tensor,
device: torch.device,
- ) -> Tensor:
+ ) -> torch.Tensor:
"""Detect by local maximum search."""
# Compute the distance threshold
dist_thresh = 0.5 * (2**0.5) + self.lambda_radius * normalized_seg_length
@@ -519,14 +523,18 @@ class LineSegmentDetectionModule:
dist_thresh = torch.repeat_interleave(dist_thresh[..., None], self.num_samples, dim=-1)
# Compute the candidate points
- cand_points = concatenate([cand_h[..., None], cand_w[..., None]], -1)
+ cand_points = torch.cat([cand_h[..., None], cand_w[..., None]], -1)
cand_points_round = torch.round(cand_points) # N x 64 x 2
# Construct local patches 9x9 = 81
- patch_mask = zeros([int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device)
- patch_center = tensor([[self.local_patch_radius, self.local_patch_radius]], device=device, dtype=torch.float32)
- H_patch_points, W_patch_points = where(patch_mask >= 0)
- patch_points = concatenate([H_patch_points[..., None], W_patch_points[..., None]], -1)
+ patch_mask = torch.zeros(
+ [int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device
+ )
+ patch_center = torch.tensor(
+ [[self.local_patch_radius, self.local_patch_radius]], device=device, dtype=torch.float32
+ )
+ H_patch_points, W_patch_points = torch.where(patch_mask >= 0)
+ patch_points = torch.cat([H_patch_points[..., None], W_patch_points[..., None]], -1)
# Fetch the circle region
patch_center_dist = torch.sqrt(torch.sum((patch_points - patch_center) ** 2, dim=-1))
patch_points = patch_points[patch_center_dist <= self.local_patch_radius, :]
@@ -541,7 +549,7 @@ class LineSegmentDetectionModule:
# Get all points => num_points_center x num_patch_points x 2
points_H = torch.clamp(patch_points_shifted[:, :, :, 0], min=0, max=H - 1).to(torch.long)
points_W = torch.clamp(patch_points_shifted[:, :, :, 1], min=0, max=W - 1).to(torch.long)
- points = concatenate([points_H[..., None], points_W[..., None]], -1)
+ points = torch.cat([points_H[..., None], points_W[..., None]], -1)
# Sample the feature (N x 64 x 81)
sampled_feat = heatmap[points[:, :, :, 0], points[:, :, :, 1]]
@@ -555,22 +563,22 @@ class LineSegmentDetectionModule:
return sampled_feat_lmax
-def line_map_to_segments(junctions: Tensor, line_map: Tensor) -> Tensor:
- """Convert a junction connectivity map to a Nx2x2 tensor of segments."""
- junc_loc1, junc_loc2 = where(torch.triu(line_map))
- segments = stack([junctions[junc_loc1], junctions[junc_loc2]], 1)
+def line_map_to_segments(junctions: torch.Tensor, line_map: torch.Tensor) -> torch.Tensor:
+ """Convert a junction connectivity map to a Nx2x2 torch.tensor of segments."""
+ junc_loc1, junc_loc2 = torch.where(torch.triu(line_map))
+ segments = torch.stack([junctions[junc_loc1], junctions[junc_loc2]], 1)
return segments
-def prob_to_junctions(prob: Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> Tensor:
+def prob_to_junctions(prob: torch.Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> torch.Tensor:
"""Extract junctions from a probability map, apply NMS, and extract the top k candidates."""
# Extract the junctions
- junctions = stack(where(prob >= prob_thresh), -1).float()
+ junctions = torch.stack(torch.where(prob >= prob_thresh), -1).float()
if len(junctions) == 0:
return junctions
# Perform NMS
- boxes = concatenate([junctions - dist / 2, junctions + dist / 2], 1)
+ boxes = torch.cat([junctions - dist / 2, junctions + dist / 2], 1)
scores = prob[prob >= prob_thresh]
remainings = nms(boxes, scores, 0.001)
junctions = junctions[remainings]
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index 990b31275..7a9acabac 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -18,17 +18,17 @@
import math
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor
-
-class DiscreteSteerer(Module):
- """Module for discrete rotation steerers.
+class DiscreteSteerer(nn.Module):
+ """nn.Module for discrete rotation steerers.
A steerer rotates keypoint descriptions in latent space as if they were obtained from rotated images.
Args:
- generator: [N, N] tensor where N is the descriptor dimension.
+ generator: [N, N] torch.tensor torch.where N is the descriptor dimension.
Example:
>>> desc = torch.randn(512, 128)
@@ -39,23 +39,23 @@ class DiscreteSteerer(Module):
"""
- def __init__(self, generator: Tensor) -> None:
+ def __init__(self, generator: torch.Tensor) -> None:
super().__init__()
self.generator = torch.nn.Parameter(generator)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.linear(x, self.generator)
def steer_descriptions(
self,
- descriptions: Tensor,
+ descriptions: torch.Tensor,
steerer_power: int = 1,
normalize: bool = False,
- ) -> Tensor:
+ ) -> torch.Tensor:
for _ in range(steerer_power):
descriptions = self.forward(descriptions)
if normalize:
- descriptions = torch.nn.functional.normalize(descriptions, dim=-1)
+ descriptions = F.normalize(descriptions, dim=-1)
return descriptions
@classmethod
@@ -63,9 +63,9 @@ class DiscreteSteerer(Module):
cls,
generator_type: str = "C4",
steerer_order: int = 8,
- ) -> Module:
+ ) -> nn.Module:
r"""Create a steerer for pretrained DeDoDe descriptors int the "C-setting"
- from the paper https://arxiv.org/abs/2312.02152, where descriptors were
+ from the paper https://arxiv.org/abs/2312.02152, torch.where descriptors were
trained for fixed steerers.
Args:
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index d84c06880..e280cf36c 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -19,8 +19,10 @@ from __future__ import annotations
from typing import Optional
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, pad
+import torch
+import torch.nn.functional as F
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import _unpack_2d_ks, get_gaussian_kernel2d
@@ -28,14 +30,14 @@ from .median import _compute_zero_padding
def _bilateral_blur(
- input: Tensor,
- guidance: Optional[Tensor],
+ input: torch.Tensor,
+ guidance: Optional[torch.Tensor],
kernel_size: tuple[int, int] | int,
- sigma_color: float | Tensor,
- sigma_space: tuple[float, float] | Tensor,
+ sigma_color: float | torch.Tensor,
+ sigma_space: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
color_distance_type: str = "l1",
-) -> Tensor:
+) -> torch.Tensor:
"""Single implementation for both Bilateral Filter and Joint Bilateral Filter."""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -48,21 +50,21 @@ def _bilateral_blur(
"guidance and input should have the same batch size and spatial dimensions",
)
- if isinstance(sigma_color, Tensor):
+ if isinstance(sigma_color, torch.Tensor):
KORNIA_CHECK_SHAPE(sigma_color, ["B"])
sigma_color = sigma_color.to(device=input.device, dtype=input.dtype).view(-1, 1, 1, 1, 1)
ky, kx = _unpack_2d_ks(kernel_size)
pad_y, pad_x = _compute_zero_padding(kernel_size)
- padded_input = pad(input, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
+ padded_input = F.pad(input, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
unfolded_input = padded_input.unfold(2, ky, 1).unfold(3, kx, 1).flatten(-2) # (B, C, H, W, Ky x Kx)
if guidance is None:
guidance = input
unfolded_guidance = unfolded_input
else:
- padded_guidance = pad(guidance, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
+ padded_guidance = F.pad(guidance, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
unfolded_guidance = padded_guidance.unfold(2, ky, 1).unfold(3, kx, 1).flatten(-2) # (B, C, H, W, Ky x Kx)
diff = unfolded_guidance - guidance.unsqueeze(-1)
@@ -83,14 +85,14 @@ def _bilateral_blur(
def bilateral_blur(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
- sigma_color: float | Tensor,
- sigma_space: tuple[float, float] | Tensor,
+ sigma_color: float | torch.Tensor,
+ sigma_space: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
color_distance_type: str = "l1",
-) -> Tensor:
- r"""Blur a tensor using a Bilateral filter.
+) -> torch.Tensor:
+ r"""Blur a torch.tensor using a Bilateral filter.
.. image:: _static/img/bilateral_blur.png
@@ -99,7 +101,7 @@ def bilateral_blur(
to the center pixel, but also the difference in intensity or color.
Arguments:
- input: the input tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
Smaller values preserve more edges.
@@ -114,7 +116,7 @@ def bilateral_blur(
Default: ``'l1'``.
Returns:
- the blurred tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.tensor with shape :math:`(B, C, H, W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -127,15 +129,15 @@ def bilateral_blur(
def joint_bilateral_blur(
- input: Tensor,
- guidance: Tensor,
+ input: torch.Tensor,
+ guidance: torch.Tensor,
kernel_size: tuple[int, int] | int,
- sigma_color: float | Tensor,
- sigma_space: tuple[float, float] | Tensor,
+ sigma_color: float | torch.Tensor,
+ sigma_space: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
color_distance_type: str = "l1",
-) -> Tensor:
- r"""Blur a tensor using a Joint Bilateral filter.
+) -> torch.Tensor:
+ r"""Blur a torch.tensor using a Joint Bilateral filter.
.. image:: _static/img/joint_bilateral_blur.png
@@ -144,8 +146,8 @@ def joint_bilateral_blur(
a guidance image. See :func:`bilateral_blur()` for more information.
Arguments:
- input: the input tensor with shape :math:`(B,C,H,W)`.
- guidance: the guidance tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ guidance: the guidance torch.tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
Smaller values preserve more edges.
@@ -159,7 +161,7 @@ def joint_bilateral_blur(
match OpenCV implementation.
Returns:
- the blurred tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.tensor with shape :math:`(B, C, H, W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -173,12 +175,12 @@ def joint_bilateral_blur(
# trick to make mypy not throw errors about difference in .forward() signatures of subclass and superclass
-class _BilateralBlur(Module):
+class _BilateralBlur(nn.Module):
def __init__(
self,
kernel_size: tuple[int, int] | int,
- sigma_color: float | Tensor,
- sigma_space: tuple[float, float] | Tensor,
+ sigma_color: float | torch.Tensor,
+ sigma_space: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
color_distance_type: str = "l1",
) -> None:
@@ -201,7 +203,7 @@ class _BilateralBlur(Module):
class BilateralBlur(_BilateralBlur):
- r"""Blur a tensor using a Bilateral filter.
+ r"""Blur a torch.tensor using a Bilateral filter.
The operator is an edge-preserving image smoothing filter. The weight
for each pixel in a neighborhood is determined not only by its distance
@@ -222,7 +224,7 @@ class BilateralBlur(_BilateralBlur):
Default: ``'l1'``.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -237,14 +239,14 @@ class BilateralBlur(_BilateralBlur):
"""
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return bilateral_blur(
input, self.kernel_size, self.sigma_color, self.sigma_space, self.border_type, self.color_distance_type
)
class JointBilateralBlur(_BilateralBlur):
- r"""Blur a tensor using a Joint Bilateral filter.
+ r"""Blur a torch.tensor using a Joint Bilateral filter.
This operator is almost identical to a Bilateral filter. The only difference
is that the color Gaussian kernel is computed based on another image called
@@ -264,7 +266,7 @@ class JointBilateralBlur(_BilateralBlur):
match OpenCV implementation.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`
@@ -280,7 +282,7 @@ class JointBilateralBlur(_BilateralBlur):
"""
- def forward(self, input: Tensor, guidance: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor, guidance: torch.Tensor) -> torch.Tensor:
return joint_bilateral_blur(
input,
guidance,
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 494d4a630..058d103cb 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -17,8 +17,9 @@
from __future__ import annotations
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK_IS_TENSOR
from .filter import filter2d, filter2d_separable
@@ -26,8 +27,8 @@ from .kernels import _unpack_2d_ks, get_box_kernel1d, get_box_kernel2d
def box_blur(
- input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", separable: bool = False
-) -> Tensor:
+ input: torch.Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", separable: bool = False
+) -> torch.Tensor:
r"""Blur an image using the box filter.
.. image:: _static/img/box_blur.png
@@ -51,7 +52,7 @@ def box_blur(
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred tensor with shape :math:`(B,C,H,W)`.
+ the blurred torch.tensor with shape :math:`(B,C,H,W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/filtering_operators.html>`__.
@@ -77,7 +78,7 @@ def box_blur(
return out
-class BoxBlur(Module):
+class BoxBlur(nn.Module):
r"""Blur an image using the box filter.
The function smooths an image using the kernel:
@@ -99,7 +100,7 @@ class BoxBlur(Module):
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -126,11 +127,11 @@ class BoxBlur(Module):
ky, kx = _unpack_2d_ks(self.kernel_size)
self.register_buffer("kernel_y", get_box_kernel1d(ky))
self.register_buffer("kernel_x", get_box_kernel1d(kx))
- self.kernel_y: Tensor
- self.kernel_x: Tensor
+ self.kernel_y: torch.Tensor
+ self.kernel_x: torch.Tensor
else:
self.register_buffer("kernel", get_box_kernel2d(kernel_size))
- self.kernel: Tensor
+ self.kernel: torch.Tensor
def __repr__(self) -> str:
return (
@@ -140,7 +141,7 @@ class BoxBlur(Module):
f"separable={self.separable})"
)
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
KORNIA_CHECK_IS_TENSOR(input)
if self.separable:
return filter2d_separable(input, self.kernel_x, self.kernel_y, self.border_type)
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index b49a77d60..154d51ae7 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -17,10 +17,10 @@
from __future__ import annotations
+import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, as_tensor, pad, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from .kernels import get_pascal_kernel_2d
@@ -36,7 +36,7 @@ __all__ = [
]
-class BlurPool2D(Module):
+class BlurPool2D(nn.Module):
r"""Compute blur (anti-aliasing) and downsample a given feature map.
See :cite:`zhang2019shiftinvar` for more details.
@@ -47,7 +47,7 @@ class BlurPool2D(Module):
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, where
+ - Output: :math:`(N, C, H_{out}, W_{out})`, torch.where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
@@ -74,12 +74,12 @@ class BlurPool2D(Module):
self.stride = stride
self.kernel = get_pascal_kernel_2d(kernel_size, norm=True)
- def forward(self, input: Tensor) -> Tensor:
- self.kernel = as_tensor(self.kernel, device=input.device, dtype=input.dtype)
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ self.kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _blur_pool_by_kernel2d(input, self.kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)
-class MaxBlurPool2D(Module):
+class MaxBlurPool2D(nn.Module):
r"""Compute pools and blurs and downsample a given feature map.
Equivalent to ```nn.Sequential(nn.MaxPool2d(...), BlurPool2D(...))```
@@ -97,7 +97,7 @@ class MaxBlurPool2D(Module):
- Output: :math:`(B, C, H / stride, W / stride)`
Returns:
- torch.Tensor: the transformed tensor.
+ torch.Tensor: the transformed torch.tensor.
Examples:
>>> import torch.nn as nn
@@ -124,14 +124,14 @@ class MaxBlurPool2D(Module):
self.ceil_mode = ceil_mode
self.kernel = get_pascal_kernel_2d(kernel_size, norm=True)
- def forward(self, input: Tensor) -> Tensor:
- self.kernel = as_tensor(self.kernel, device=input.device, dtype=input.dtype)
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ self.kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _max_blur_pool_by_kernel2d(
input, self.kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode
)
-class EdgeAwareBlurPool2D(Module):
+class EdgeAwareBlurPool2D(nn.Module):
def __init__(
self, kernel_size: tuple[int, int] | int, edge_threshold: float = 1.25, edge_dilation_kernel_size: int = 3
) -> None:
@@ -140,13 +140,13 @@ class EdgeAwareBlurPool2D(Module):
self.edge_threshold = edge_threshold
self.edge_dilation_kernel_size = edge_dilation_kernel_size
- def forward(self, input: Tensor, epsilon: float = 1e-6) -> Tensor:
+ def forward(self, input: torch.Tensor, epsilon: float = 1e-6) -> torch.Tensor:
return edge_aware_blur_pool2d(
input, self.kernel_size, self.edge_threshold, self.edge_dilation_kernel_size, epsilon
)
-def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2) -> Tensor:
+def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride: int = 2) -> torch.Tensor:
r"""Compute blurs and downsample a given feature map.
.. image:: _static/img/blur_pool2d.png
@@ -156,13 +156,13 @@ def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int =
See :cite:`zhang2019shiftinvar` for more details.
Args:
- input: tensor to apply operation to.
+ input: torch.tensor to apply operation to.
kernel_size: the kernel size for max pooling.
stride: stride for pooling.
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, where
+ - Output: :math:`(N, C, H_{out}, W_{out})`, torch.where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
@@ -173,7 +173,7 @@ def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int =
\text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
Returns:
- the transformed tensor.
+ the transformed torch.tensor.
.. note::
This function is tested against https://github.com/adobe/antialiased-cnns.
@@ -196,8 +196,12 @@ def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int =
def max_blur_pool2d(
- input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
-) -> Tensor:
+ input: torch.Tensor,
+ kernel_size: tuple[int, int] | int,
+ stride: int = 2,
+ max_pool_size: int = 2,
+ ceil_mode: bool = False,
+) -> torch.Tensor:
r"""Compute pools and blurs and downsample a given feature map.
.. image:: _static/img/max_blur_pool2d.png
@@ -205,7 +209,7 @@ def max_blur_pool2d(
See :class:`~kornia.filters.MaxBlurPool2D` for details.
Args:
- input: tensor to apply operation to.
+ input: torch.tensor to apply operation to.
kernel_size: the kernel size for max pooling.
stride: stride for pooling.
max_pool_size: the kernel size for max pooling.
@@ -232,7 +236,7 @@ def max_blur_pool2d(
return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)
-def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int) -> Tensor:
+def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: int) -> torch.Tensor:
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
KORNIA_CHECK(
len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
@@ -244,8 +248,8 @@ def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int) -> Tensor
def _max_blur_pool_by_kernel2d(
- input: Tensor, kernel: Tensor, stride: int, max_pool_size: int, ceil_mode: bool
-) -> Tensor:
+ input: torch.Tensor, kernel: torch.Tensor, stride: int, max_pool_size: int, ceil_mode: bool
+) -> torch.Tensor:
"""Compute max_blur_pool by a given :math:`CxC_(out, None)xNxN` kernel."""
KORNIA_CHECK(
len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
@@ -259,13 +263,13 @@ def _max_blur_pool_by_kernel2d(
def edge_aware_blur_pool2d(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
edge_threshold: float = 1.25,
edge_dilation_kernel_size: int = 3,
epsilon: float = 1e-6,
-) -> Tensor:
- r"""Blur the input tensor while maintaining its edges.
+) -> torch.Tensor:
+ r"""Blur the input torch.tensor while maintaining its edges.
Args:
input: the input image to blur with shape :math:`(B, C, H, W)`.
@@ -275,17 +279,17 @@ def edge_aware_blur_pool2d(
epsilon: for numerical stability.
Returns:
- The blurred tensor of shape :math:`(B, C, H, W)`.
+ The blurred torch.tensor of shape :math:`(B, C, H, W)`.
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(edge_threshold > 0.0, f"edge threshold should be positive, but got '{edge_threshold}'")
- input = pad(input, (2, 2, 2, 2), mode="reflect") # pad to avoid artifacts near physical edges
+ input = F.pad(input, (2, 2, 2, 2), mode="reflect") # F.pad to avoid artifacts near physical edges
blurred_input = blur_pool2d(input, kernel_size=kernel_size, stride=1) # blurry version of the input
# calculate the edges (add epsilon to avoid taking the log of 0)
- log_input, log_thresh = (input + epsilon).log2(), (tensor(edge_threshold)).log2()
+ log_input, log_thresh = (input + epsilon).log2(), (torch.tensor(edge_threshold)).log2()
edges_x = log_input[..., :, 4:] - log_input[..., :, :-4]
edges_y = log_input[..., 4:, :] - log_input[..., :-4, :]
edges_x, edges_y = edges_x.mean(dim=-3, keepdim=True), edges_y.mean(dim=-3, keepdim=True)
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index f56cfe2a4..cda6834a2 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -21,10 +21,9 @@ import math
import torch
import torch.nn.functional as F
+from torch import nn
from kornia.color import rgb_to_grayscale
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .gaussian import gaussian_blur2d
@@ -33,20 +32,20 @@ from .sobel import spatial_gradient
def canny(
- input: Tensor,
+ input: torch.Tensor,
low_threshold: float = 0.1,
high_threshold: float = 0.2,
kernel_size: tuple[int, int] | int = (5, 5),
- sigma: tuple[float, float] | Tensor = (1, 1),
+ sigma: tuple[float, float] | torch.Tensor = (1, 1),
hysteresis: bool = True,
eps: float = 1e-6,
-) -> tuple[Tensor, Tensor]:
+) -> tuple[torch.Tensor, torch.Tensor]:
r"""Find edges of the input image and filters them using the Canny algorithm.
.. image:: _static/img/canny.png
Args:
- input: input image tensor with shape :math:`(B,C,H,W)`.
+ input: input image torch.tensor with shape :math:`(B,C,H,W)`.
low_threshold: lower threshold for the hysteresis procedure.
high_threshold: upper threshold for the hysteresis procedure.
kernel_size: the size of the kernel for the gaussian blur.
@@ -89,18 +88,18 @@ def canny(
input = rgb_to_grayscale(input)
# Gaussian filter
- blurred: Tensor = gaussian_blur2d(input, kernel_size, sigma)
+ blurred: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)
# Compute the gradients
- gradients: Tensor = spatial_gradient(blurred, normalized=False)
+ gradients: torch.Tensor = spatial_gradient(blurred, normalized=False)
# Unpack the edges
- gx: Tensor = gradients[:, :, 0]
- gy: Tensor = gradients[:, :, 1]
+ gx: torch.Tensor = gradients[:, :, 0]
+ gy: torch.Tensor = gradients[:, :, 1]
# Compute gradient magnitude and angle
- magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps)
- angle: Tensor = torch.atan2(gy, gx)
+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)
+ angle: torch.Tensor = torch.atan2(gy, gx)
# Radians to degrees and round to nearest 45 degree
# degrees = angle * (180.0 / math.pi)
@@ -108,47 +107,47 @@ def canny(
angle_45 = (angle * (4 / math.pi)).round()
# Non-maximal suppression
- nms_kernels: Tensor = get_canny_nms_kernel(device, dtype)
- nms_magnitude: Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
+ nms_kernels: torch.Tensor = get_canny_nms_kernel(device, dtype)
+ nms_magnitude: torch.Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
# Get the indices for both directions
- positive_idx: Tensor = angle_45 % 8
+ positive_idx: torch.Tensor = angle_45 % 8
positive_idx = positive_idx.long()
- negative_idx: Tensor = (angle_45 + 4) % 8
+ negative_idx: torch.Tensor = (angle_45 + 4) % 8
negative_idx = negative_idx.long()
# Apply the non-maximum suppression to the different directions
- channel_select_filtered_positive: Tensor = torch.gather(nms_magnitude, 1, positive_idx)
- channel_select_filtered_negative: Tensor = torch.gather(nms_magnitude, 1, negative_idx)
+ channel_select_filtered_positive: torch.Tensor = torch.gather(nms_magnitude, 1, positive_idx)
+ channel_select_filtered_negative: torch.Tensor = torch.gather(nms_magnitude, 1, negative_idx)
- channel_select_filtered: Tensor = torch.stack(
+ channel_select_filtered: torch.Tensor = torch.stack(
[channel_select_filtered_positive, channel_select_filtered_negative], 1
)
- is_max: Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
+ is_max: torch.Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
magnitude = magnitude * is_max
# Threshold
- edges: Tensor = F.threshold(magnitude, low_threshold, 0.0)
+ edges: torch.Tensor = F.threshold(magnitude, low_threshold, 0.0)
- low: Tensor = magnitude > low_threshold
- high: Tensor = magnitude > high_threshold
+ low: torch.Tensor = magnitude > low_threshold
+ high: torch.Tensor = magnitude > high_threshold
edges = low * 0.5 + high * 0.5
edges = edges.to(dtype)
# Hysteresis
if hysteresis:
- edges_old: Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)
- hysteresis_kernels: Tensor = get_hysteresis_kernel(device, dtype)
+ edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)
+ hysteresis_kernels: torch.Tensor = get_hysteresis_kernel(device, dtype)
while ((edges_old - edges).abs() != 0).any():
- weak: Tensor = (edges == 0.5).float()
- strong: Tensor = (edges == 1).float()
+ weak: torch.Tensor = (edges == 0.5).float()
+ strong: torch.Tensor = (edges == 1).float()
- hysteresis_magnitude: Tensor = F.conv2d(
+ hysteresis_magnitude: torch.Tensor = F.conv2d(
edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2
)
hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype)
@@ -162,11 +161,11 @@ def canny(
return magnitude, edges
-class Canny(Module):
- r"""Module that finds edges of the input image and filters them using the Canny algorithm.
+class Canny(nn.Module):
+ r"""nn.Module that finds edges of the input image and filters them using the Canny algorithm.
Args:
- input: input image tensor with shape :math:`(B,C,H,W)`.
+ input: input image torch.tensor with shape :math:`(B,C,H,W)`.
low_threshold: lower threshold for the hysteresis procedure.
high_threshold: upper threshold for the hysteresis procedure.
kernel_size: the size of the kernel for the gaussian blur.
@@ -197,7 +196,7 @@ class Canny(Module):
low_threshold: float = 0.1,
high_threshold: float = 0.2,
kernel_size: tuple[int, int] | int = (5, 5),
- sigma: tuple[float, float] | Tensor = (1, 1),
+ sigma: tuple[float, float] | torch.Tensor = (1, 1),
hysteresis: bool = True,
eps: float = 1e-6,
) -> None:
@@ -237,7 +236,7 @@ class Canny(Module):
)
)
- def forward(self, input: Tensor) -> tuple[Tensor, Tensor]:
+ def forward(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
return canny(
input, self.low_threshold, self.high_threshold, self.kernel_size, self.sigma, self.hysteresis, self.eps
)
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 183a3e46f..9032921c3 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -26,8 +26,6 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, concatenate
from kornia.core.check import KORNIA_CHECK
url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
@@ -57,7 +55,7 @@ def weight_init(m: nn.Module) -> None:
torch.nn.init.zeros_(m.bias)
-class CoFusion(Module):
+class CoFusion(nn.Module):
def __init__(self, in_ch: int, out_ch: int) -> None:
super().__init__()
self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)
@@ -67,7 +65,7 @@ class CoFusion(Module):
self.norm_layer1 = nn.GroupNorm(4, 64)
self.norm_layer2 = nn.GroupNorm(4, 64)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
# fusecat = torch.cat(x, dim=1)
attn = self.relu(self.norm_layer1(self.conv1(x)))
attn = self.relu(self.norm_layer2(self.conv2(attn)))
@@ -92,9 +90,9 @@ class _DenseLayer(nn.Sequential):
)
)
- def forward(self, x: list[Tensor]) -> list[Tensor]:
+ def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:
x1, x2 = x[0], x[1]
- x3: Tensor = x1
+ x3: torch.Tensor = x1
for mod in self:
x3 = mod(x3)
return [0.5 * (x3 + x2), x2]
@@ -108,14 +106,14 @@ class _DenseBlock(nn.Sequential):
self.add_module(f"denselayer{(i + 1)}", layer)
input_features = out_features
- def forward(self, x: list[Tensor]) -> list[Tensor]:
+ def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:
x_out = x
for mod in self:
x_out = mod(x_out)
return x_out
-class UpConvBlock(Module):
+class UpConvBlock(nn.Module):
def __init__(self, in_features: int, up_scale: int) -> None:
super().__init__()
self.up_factor = 2
@@ -141,20 +139,20 @@ class UpConvBlock(Module):
def compute_out_features(self, idx: int, up_scale: int) -> int:
return 1 if idx == up_scale - 1 else self.constant_features
- def forward(self, x: Tensor, out_shape: list[int]) -> Tensor:
+ def forward(self, x: torch.Tensor, out_shape: list[int]) -> torch.Tensor:
out = self.features(x)
out = F.interpolate(out, out_shape, mode="bilinear")
return out
-class SingleConvBlock(Module):
+class SingleConvBlock(nn.Module):
def __init__(self, in_features: int, out_features: int, stride: int, use_bs: bool = True) -> None:
super().__init__()
self.use_bn = use_bs
self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)
self.bn = nn.BatchNorm2d(out_features)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
@@ -182,11 +180,11 @@ class DoubleConvBlock(nn.Sequential):
self.add_module("relu2", nn.ReLU(inplace=True))
-class DexiNed(Module):
+class DexiNed(nn.Module):
r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.
Return:
- A list of tensor with the intermediate features which the last element
+ A list of torch.tensor with the intermediate features which the last element
is the edges map with shape :math:`(B,1,H,W)`.
Example:
@@ -246,7 +244,7 @@ class DexiNed(Module):
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
- def get_features(self, x: Tensor) -> list[Tensor]:
+ def get_features(self, x: torch.Tensor) -> list[torch.Tensor]:
# Block 1
block_1 = self.block_1(x)
block_1_side = self.side_1(block_1)
@@ -292,11 +290,11 @@ class DexiNed(Module):
results = [out_1, out_2, out_3, out_4, out_5, out_6]
return results
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
features = self.get_features(x)
- # concatenate multiscale outputs
- block_cat = concatenate(features, 1) # Bx6xHxW
+ # torch.cat multiscale outputs
+ block_cat = torch.cat(features, 1) # Bx6xHxW
block_cat = self.block_cat(block_cat) # Bx1xHxW
return block_cat
diff --git a/kornia/filters/dissolving.py b/kornia/filters/dissolving.py
index 91d95bf8e..0e0b8a9bb 100644
--- a/kornia/filters/dissolving.py
+++ b/kornia/filters/dissolving.py
@@ -19,13 +19,14 @@ import os
from typing import Any
import torch
+from torch import nn
-from kornia.core import ImageModule, Module, Tensor
+from kornia.core import ImageModule
from kornia.core.external import diffusers
class _DissolvingWraper_HF:
- def __init__(self, model: Module, num_ddim_steps: int = 50, is_sdxl: bool = False) -> None:
+ def __init__(self, model: nn.Module, num_ddim_steps: int = 50, is_sdxl: bool = False) -> None:
self.model = model
self.num_ddim_steps = num_ddim_steps
self.is_sdxl = is_sdxl
@@ -33,11 +34,11 @@ class _DissolvingWraper_HF:
self.model.scheduler.set_timesteps(self.num_ddim_steps)
self.total_steps = len(self.model.scheduler.timesteps) # Total number of sampling steps.
self.prompt: str
- self.context: Tensor
- self.pooled_embeddings: Tensor | None = None
- self.add_time_ids: Tensor | None = None
+ self.context: torch.Tensor
+ self.pooled_embeddings: torch.Tensor | None = None
+ self.add_time_ids: torch.Tensor | None = None
- def predict_start_from_noise(self, noise_pred: Tensor, timestep: int, latent: Tensor) -> Tensor:
+ def predict_start_from_noise(self, noise_pred: torch.Tensor, timestep: int, latent: torch.Tensor) -> torch.Tensor:
return (
torch.sqrt(1.0 / self.model.scheduler.alphas_cumprod[timestep]) * latent
- torch.sqrt(1.0 / self.model.scheduler.alphas_cumprod[timestep] - 1) * noise_pred
@@ -137,7 +138,7 @@ class _DissolvingWraper_HF:
# Encode the image to latent using the VAE.
@torch.no_grad()
- def encode_tensor_to_latent(self, image: Tensor) -> Tensor:
+ def encode_tensor_to_latent(self, image: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
image = (image / 0.5 - 1).to(self.model.device)
latents = self.model.vae.encode(image)["latent_dist"].sample()
@@ -145,7 +146,7 @@ class _DissolvingWraper_HF:
return latents
@torch.no_grad()
- def decode_tensor_to_latent(self, latents: Tensor) -> Tensor:
+ def decode_tensor_to_latent(self, latents: torch.Tensor) -> torch.Tensor:
# Perform in-place detach to reduce memory usage and copies
latents = latents.detach()
latents = latents * (1.0 / 0.18215) # Fused division as multiplication (faster)
@@ -158,7 +159,7 @@ class _DissolvingWraper_HF:
return image
@torch.no_grad()
- def one_step_dissolve(self, latent: Tensor, i: int) -> Tensor:
+ def one_step_dissolve(self, latent: torch.Tensor, i: int) -> torch.Tensor:
_, cond_embeddings = self.context.chunk(2)
latent = latent.clone().detach()
# NOTE: This implementation use a reversed timesteps but can reach to
@@ -193,7 +194,7 @@ class _DissolvingWraper_HF:
return pred_x0
@torch.no_grad()
- def dissolve(self, image: Tensor, t: int) -> Tensor:
+ def dissolve(self, image: torch.Tensor, t: int) -> torch.Tensor:
self.init_prompt("")
latent = self.encode_tensor_to_latent(image)
ddim_latents = self.one_step_dissolve(latent, t)
@@ -271,5 +272,5 @@ class StableDiffusionDissolving(ImageModule):
self.model = _DissolvingWraper_HF(self._sdm_model, num_ddim_steps=1000, is_sdxl=is_sdxl)
- def forward(self, input: Tensor, step_number: int) -> Tensor:
+ def forward(self, input: torch.Tensor, step_number: int) -> torch.Tensor:
return self.model.dissolve(input, step_number)
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index f22390452..3ede75183 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -17,9 +17,9 @@
from __future__ import annotations
+import torch
import torch.nn.functional as F
-from kornia.core import Tensor, pad
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import normalize_kernel2d
@@ -53,13 +53,13 @@ def _compute_padding(kernel_size: list[int]) -> list[int]:
def filter2d(
- input: Tensor,
- kernel: Tensor,
+ input: torch.Tensor,
+ kernel: torch.Tensor,
border_type: str = "reflect",
normalized: bool = False,
padding: str = "same",
behaviour: str = "corr",
-) -> Tensor:
+) -> torch.Tensor:
r"""Convolve a tensor with a 2d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -137,7 +137,7 @@ def filter2d(
# pad the input tensor
if padding == "same":
padding_shape: list[int] = _compute_padding([height, width])
- input = pad(input, padding_shape, mode=border_type)
+ input = F.pad(input, padding_shape, mode=border_type)
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
@@ -155,13 +155,13 @@ def filter2d(
def filter2d_separable(
- input: Tensor,
- kernel_x: Tensor,
- kernel_y: Tensor,
+ input: torch.Tensor,
+ kernel_x: torch.Tensor,
+ kernel_y: torch.Tensor,
border_type: str = "reflect",
normalized: bool = False,
padding: str = "same",
-) -> Tensor:
+) -> torch.Tensor:
r"""Convolve a tensor with two 1d kernels, in x and y directions.
The function applies a given kernel to a tensor. The kernel is applied
@@ -209,7 +209,9 @@ def filter2d_separable(
return out
-def filter3d(input: Tensor, kernel: Tensor, border_type: str = "replicate", normalized: bool = False) -> Tensor:
+def filter3d(
+ input: torch.Tensor, kernel: torch.Tensor, border_type: str = "replicate", normalized: bool = False
+) -> torch.Tensor:
r"""Convolve a tensor with a 3d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -293,7 +295,7 @@ def filter3d(input: Tensor, kernel: Tensor, border_type: str = "replicate", norm
# pad the input tensor
depth, height, width = tmp_kernel.shape[-3:]
padding_shape: list[int] = _compute_padding([depth, height, width])
- input_pad = pad(input, padding_shape, mode=border_type)
+ input_pad = F.pad(input, padding_shape, mode=border_type)
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, depth, height, width)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 85789ff3a..d1b43479f 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -19,8 +19,9 @@ from __future__ import annotations
from typing import Any
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils import deprecated
@@ -29,34 +30,34 @@ from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, g
def gaussian_blur2d(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
- sigma: tuple[float, float] | Tensor,
+ sigma: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
separable: bool = True,
-) -> Tensor:
- r"""Create an operator that blurs a tensor using a Gaussian filter.
+) -> torch.Tensor:
+ r"""Create an operator that blurs a torch.tensor using a Gaussian filter.
.. image:: _static/img/gaussian_blur2d.png
- The operator smooths the given tensor with a gaussian kernel by convolving
+ The operator smooths the given torch.tensor with a gaussian kernel by convolving
it to each channel. It supports batched operation.
Arguments:
- input: the input tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Can be an integer or tuple of two integers (height, width).
- sigma: the standard deviation of the kernel. Can be a tuple of two floats or a tensor with shape :math:`(B, 2)`.
- Values must be positive.
+ sigma: the standard deviation of the kernel. Can be a tuple of two floats or a torch.tensor
+ with shape :math:`(B, 2)`. Values must be positive.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
separable: run as composition of two 1d-convolutions. Default: ``True``.
Returns:
- the blurred tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.tensor with shape :math:`(B, C, H, W)`.
Raises:
- RuntimeError: if input is not a 4D tensor.
+ RuntimeError: if input is not a 4D torch.tensor.
RuntimeError: if sigma values are not positive.
RuntimeError: if kernel_size is not a positive odd integer.
@@ -81,7 +82,7 @@ def gaussian_blur2d(
>>> output.shape
torch.Size([2, 4, 5, 5])
- >>> # Using tensor sigma
+ >>> # Using torch.tensor sigma
>>> output = gaussian_blur2d(input, (3, 3), torch.tensor([[1.5, 1.5]]))
>>> output.shape
torch.Size([2, 4, 5, 5])
@@ -92,7 +93,7 @@ def gaussian_blur2d(
_check_kernel_size(kernel_size, min_value=0)
if isinstance(sigma, tuple):
- sigma = tensor([sigma], device=input.device, dtype=input.dtype)
+ sigma = torch.tensor([sigma], device=input.device, dtype=input.dtype)
else:
KORNIA_CHECK_IS_TENSOR(sigma)
sigma = sigma.to(device=input.device, dtype=input.dtype)
@@ -114,10 +115,10 @@ def gaussian_blur2d(
return out
-class GaussianBlur2d(Module):
- r"""Create an operator that blurs a tensor using a Gaussian filter.
+class GaussianBlur2d(nn.Module):
+ r"""Create an operator that blurs a torch.tensor using a Gaussian filter.
- The operator smooths the given tensor with a gaussian kernel by convolving
+ The operator smooths the given torch.tensor with a gaussian kernel by convolving
it to each channel. It supports batched operation.
Arguments:
@@ -129,7 +130,7 @@ class GaussianBlur2d(Module):
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred tensor.
+ the blurred torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -148,7 +149,7 @@ class GaussianBlur2d(Module):
def __init__(
self,
kernel_size: tuple[int, int] | int,
- sigma: tuple[float, float] | Tensor,
+ sigma: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
separable: bool = True,
) -> None:
@@ -167,10 +168,10 @@ class GaussianBlur2d(Module):
f"separable={self.separable})"
)
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type, self.separable)
@deprecated(replace_with="gaussian_blur2d", version="6.9.10")
-def gaussian_blur2d_t(*args: Any, **kwargs: Any) -> Tensor: # noqa: D103
+def gaussian_blur2d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103
return gaussian_blur2d(*args, **kwargs)
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 6c590998e..cba43c990 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -18,10 +18,9 @@
from __future__ import annotations
import torch
+from torch import nn
from torch.nn.functional import interpolate
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .blur import box_blur
@@ -29,8 +28,8 @@ from .kernels import _unpack_2d_ks
def _preprocess_fast_guided_blur(
- guidance: Tensor, input: Tensor, kernel_size: tuple[int, int] | int, subsample: int = 1
-) -> tuple[Tensor, Tensor, tuple[int, int]]:
+ guidance: torch.Tensor, input: torch.Tensor, kernel_size: tuple[int, int] | int, subsample: int = 1
+) -> tuple[torch.Tensor, torch.Tensor, tuple[int, int]]:
ky, kx = _unpack_2d_ks(kernel_size)
if subsample > 1:
s = 1 / subsample
@@ -44,13 +43,13 @@ def _preprocess_fast_guided_blur(
def _guided_blur_grayscale_guidance(
- guidance: Tensor,
- input: Tensor,
+ guidance: torch.Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
- eps: float | Tensor,
+ eps: float | torch.Tensor,
border_type: str = "reflect",
subsample: int = 1,
-) -> Tensor:
+) -> torch.Tensor:
guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)
mean_I = box_blur(guidance_sub, kernel_size, border_type)
@@ -66,7 +65,7 @@ def _guided_blur_grayscale_guidance(
corr_Ip = box_blur(guidance_sub * input_sub, kernel_size, border_type)
cov_Ip = corr_Ip - mean_I * mean_p
- if isinstance(eps, Tensor):
+ if isinstance(eps, torch.Tensor):
eps = eps.view(-1, 1, 1, 1) # N -> NCHW
a = cov_Ip / (var_I + eps)
@@ -83,13 +82,13 @@ def _guided_blur_grayscale_guidance(
def _guided_blur_multichannel_guidance(
- guidance: Tensor,
- input: Tensor,
+ guidance: torch.Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
- eps: float | Tensor,
+ eps: float | torch.Tensor,
border_type: str = "reflect",
subsample: int = 1,
-) -> Tensor:
+) -> torch.Tensor:
guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)
B, C, H, W = guidance_sub.shape
@@ -108,7 +107,7 @@ def _guided_blur_multichannel_guidance(
corr_Ip = box_blur(Ip, kernel_size, border_type).permute(0, 2, 3, 1)
cov_Ip = corr_Ip.reshape(B, H, W, C, -1) - mean_p.unsqueeze(-2) * mean_I.unsqueeze(-1)
- if isinstance(eps, Tensor):
+ if isinstance(eps, torch.Tensor):
_eps = torch.eye(C, device=guidance.device, dtype=guidance.dtype).view(1, 1, 1, C, C) * eps.view(-1, 1, 1, 1, 1)
else:
_eps = guidance.new_full((C,), eps).diag().view(1, 1, 1, C, C)
@@ -123,19 +122,19 @@ def _guided_blur_multichannel_guidance(
mean_b = interpolate(mean_b, scale_factor=subsample, mode="bilinear")
mean_a = mean_a.view(B, C, -1, H * subsample, W * subsample)
- # einsum might not be contiguous, thus mean_b is the first argument
+ # torch.einsum might not be contiguous, thus mean_b is the first argument
return mean_b + torch.einsum("BCHW,BCcHW->BcHW", guidance, mean_a)
def guided_blur(
- guidance: Tensor,
- input: Tensor,
+ guidance: torch.Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] | int,
- eps: float | Tensor,
+ eps: float | torch.Tensor,
border_type: str = "reflect",
subsample: int = 1,
-) -> Tensor:
- r"""Blur a tensor using a Guided filter.
+) -> torch.Tensor:
+ r"""Blur a torch.tensor using a Guided filter.
.. image:: _static/img/guided_blur.png
@@ -143,8 +142,8 @@ def guided_blur(
and :cite:`he2015fast` for details. Guidance and input can have different number of channels.
Arguments:
- guidance: the guidance tensor with shape :math:`(B,C,H,W)`.
- input: the input tensor with shape :math:`(B,C,H,W)`.
+ guidance: the guidance torch.tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
eps: regularization parameter. Smaller values preserve more edges.
border_type: the padding mode to be applied before convolving.
@@ -153,7 +152,7 @@ def guided_blur(
subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
Returns:
- the blurred tensor with same shape as `input` :math:`(B, C, H, W)`.
+ the blurred torch.tensor with same shape as `input` :math:`(B, C, H, W)`.
Examples:
>>> guidance = torch.rand(2, 3, 5, 5)
@@ -179,8 +178,8 @@ def guided_blur(
return _guided_blur_multichannel_guidance(guidance, input, kernel_size, eps, border_type, subsample)
-class GuidedBlur(Module):
- r"""Blur a tensor using a Guided filter.
+class GuidedBlur(nn.Module):
+ r"""Blur a torch.tensor using a Guided filter.
The operator is an edge-preserving image smoothing filter. See :cite:`he2010guided`
and :cite:`he2015fast` for details. Guidance and input can have different number of channels.
@@ -194,7 +193,7 @@ class GuidedBlur(Module):
subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`
@@ -228,5 +227,5 @@ class GuidedBlur(Module):
f"subsample={self.subsample})"
)
- def forward(self, guidance: Tensor, input: Tensor) -> Tensor:
+ def forward(self, guidance: torch.Tensor, input: torch.Tensor) -> torch.Tensor:
return guided_blur(guidance, input, self.kernel_size, self.eps, self.border_type, self.subsample)
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index 470dd3478..03b7982f4 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -20,39 +20,37 @@ from __future__ import annotations
from typing import Any, Union
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
-from kornia.core.check import KORNIA_CHECK
from kornia.utils.image import perform_keep_shape_image
@perform_keep_shape_image
def in_range(
- input: Tensor,
- lower: Union[tuple[Any, ...], Tensor],
- upper: Union[tuple[Any, ...], Tensor],
+ input: torch.Tensor,
+ lower: Union[tuple[Any, ...], torch.Tensor],
+ upper: Union[tuple[Any, ...], torch.Tensor],
return_mask: bool = False,
-) -> Tensor:
- r"""Create a mask indicating whether elements of the input tensor are within the specified range.
+) -> torch.Tensor:
+ r"""Create a mask indicating whether elements of the input torch.tensor are within the specified range.
.. image:: _static/img/in_range.png
- The formula applied for single-channel tensor is:
+ The formula applied for single-channel torch.tensor is:
.. math::
\text{out}(I) = \text{lower}(I) \leq \text{input}(I) \geq \text{upper}(I)
- The formula applied for multi-channel tensor is:
+ The formula applied for multi-channel torch.tensor is:
.. math::
\text{out}(I) = \bigwedge_{c=0}^{C}
\left( \text{lower}_c(I) \leq \text{input}_c(I) \geq \text{upper}_c(I) \right)
- where `C` is the number of channels.
+ torch.where `C` is the number of channels.
Args:
- input: The input tensor to be filtered in the shape of :math:`(*, *, H, W)`.
+ input: The input torch.tensor to be filtered in the shape of :math:`(*, *, H, W)`.
lower: The lower bounds of the filter (inclusive).
upper: The upper bounds of the filter (inclusive).
return_mask: If is true, the filtered mask is returned, otherwise the filtered input image.
@@ -67,13 +65,14 @@ def in_range(
.. note::
Clarification of `lower` and `upper`:
- - If provided as a tuple, it should have the same number of elements as the channels in the input tensor.
+ - If provided as a tuple, it should have the same number of elements as the channels in the input torch.tensor.
This bound is then applied uniformly across all batches.
- - When provided as a tensor, it allows for different bounds to be applied to each batch.
- The tensor shape should be (B, C, 1, 1), where B is the batch size and C is the number of channels.
+ - When provided as a torch.tensor, it allows for different bounds to be applied to each batch.
+ The torch.tensor shape should be (B, C, 1, 1), torch.where B is the batch size and C is
+ the number of channels.
- - If the tensor has a 1-D shape, same bound will be applied across all batches.
+ - If the torch.tensor has a 1-D shape, same bound will be applied across all batches.
Examples:
>>> rng = torch.manual_seed(1)
@@ -109,14 +108,11 @@ def in_range(
"""
input_shape = input.shape
- KORNIA_CHECK(
- isinstance(lower, (tuple, Tensor)) and isinstance(upper, (tuple, Tensor)),
- "Invalid `lower` and `upper` format. Should be tuple or Tensor.",
- )
- KORNIA_CHECK(
- isinstance(return_mask, bool),
- "Invalid `return_mask` format. Should be boolean.",
- )
+ if not isinstance(lower, (tuple, torch.Tensor)) or not isinstance(upper, (tuple, torch.Tensor)):
+ raise TypeError("Invalid `lower` and `upper` format. Should be tuple or torch.Tensor.")
+
+ if not isinstance(return_mask, bool):
+ raise TypeError("Invalid `return_mask` format. Should be boolean.")
if isinstance(lower, tuple) and isinstance(upper, tuple):
if len(lower) != input_shape[1] or len(upper) != input_shape[1]:
@@ -133,7 +129,7 @@ def in_range(
.repeat(input_shape[0], 1, 1, 1)
)
- elif isinstance(lower, Tensor) and isinstance(upper, Tensor):
+ elif isinstance(lower, torch.Tensor) and isinstance(upper, torch.Tensor):
valid_tensor_shape = (input_shape[0], input_shape[1], 1, 1)
if valid_tensor_shape not in (lower.shape, upper.shape):
raise ValueError(
@@ -152,11 +148,11 @@ def in_range(
return input * mask
-class InRange(Module):
+class InRange(nn.Module):
r"""Create a module for applying lower and upper bounds to input tensors.
Args:
- input: The input tensor to be filtered.
+ input: The input torch.tensor to be filtered.
lower: The lower bounds of the filter (inclusive).
upper: The upper bounds of the filter (inclusive).
return_mask: If is true, the filtered mask is returned, otherwise the filtered input image.
@@ -183,8 +179,8 @@ class InRange(Module):
def __init__(
self,
- lower: Union[tuple[Any, ...], Tensor],
- upper: Union[tuple[Any, ...], Tensor],
+ lower: Union[tuple[Any, ...], torch.Tensor],
+ upper: Union[tuple[Any, ...], torch.Tensor],
return_mask: bool = False,
) -> None:
super().__init__()
@@ -192,5 +188,5 @@ class InRange(Module):
self.upper = upper
self.return_mask = return_mask
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return in_range(input, self.lower, self.upper, self.return_mask)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 1ab6a0ccc..61d68e016 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -22,7 +22,6 @@ from typing import Any, Optional, Union
import torch
-from kornia.core import Device, Dtype, Tensor, concatenate, cos, stack, tensor, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils import deprecated
@@ -66,7 +65,7 @@ def _unpack_3d_ks(kernel_size: tuple[int, int, int] | int) -> tuple[int, int, in
return (kz, ky, kx)
-def normalize_kernel2d(input: Tensor) -> Tensor:
+def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
r"""Normalize both derivative and smoothing kernel."""
KORNIA_CHECK_SHAPE(input, ["*", "H", "W"])
@@ -77,12 +76,12 @@ def normalize_kernel2d(input: Tensor) -> Tensor:
def gaussian(
window_size: int,
- sigma: Tensor | float,
+ sigma: torch.Tensor | float,
*,
- mean: Optional[Union[Tensor, float]] = None,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ mean: Optional[Union[torch.Tensor, float]] = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Compute the gaussian values based on the window and sigma values.
Args:
@@ -98,7 +97,7 @@ def gaussian(
"""
if isinstance(sigma, float):
- sigma = tensor([[sigma]], device=device, dtype=dtype)
+ sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
@@ -106,7 +105,7 @@ def gaussian(
mean = float(window_size // 2) if mean is None else mean
if isinstance(mean, float):
- mean = tensor([[mean]], device=sigma.device, dtype=sigma.dtype)
+ mean = torch.tensor([[mean]], device=sigma.device, dtype=sigma.dtype)
KORNIA_CHECK_IS_TENSOR(mean)
KORNIA_CHECK_SHAPE(mean, ["B", "1"])
@@ -122,8 +121,12 @@ def gaussian(
def gaussian_discrete_erf(
- window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ window_size: int,
+ sigma: torch.Tensor | float,
+ *,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Discrete Gaussian by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
@@ -139,7 +142,7 @@ def gaussian_discrete_erf(
"""
if isinstance(sigma, float):
- sigma = tensor([[sigma]], device=device, dtype=dtype)
+ sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
batch_size = sigma.shape[0]
@@ -147,7 +150,7 @@ def gaussian_discrete_erf(
x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
t = 0.70710678 / sigma.abs()
- # t = tensor(2, device=sigma.device, dtype=sigma.dtype).sqrt() / (sigma.abs() * 2)
+ # t = torch.tensor(2, device=sigma.device, dtype=sigma.dtype).sqrt() / (sigma.abs() * 2)
gauss = 0.5 * ((t * (x + 0.5)).erf() - (t * (x - 0.5)).erf())
gauss = gauss.clamp(min=0)
@@ -155,11 +158,11 @@ def gaussian_discrete_erf(
return gauss / gauss.sum(-1, keepdim=True)
-def _modified_bessel_0(x: Tensor) -> Tensor:
+def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
"""Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
ax = torch.abs(x)
- out = zeros_like(x)
+ out = torch.zeros_like(x)
idx_a = ax < 3.75
if idx_a.any():
@@ -178,11 +181,11 @@ def _modified_bessel_0(x: Tensor) -> Tensor:
return out
-def _modified_bessel_1(x: Tensor) -> Tensor:
+def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
"""Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
ax = torch.abs(x)
- out = zeros_like(x)
+ out = torch.zeros_like(x)
idx_a = ax < 3.75
if idx_a.any():
@@ -196,12 +199,12 @@ def _modified_bessel_1(x: Tensor) -> Tensor:
ans = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2))
ans = 0.39894228 + y * (-0.3988024e-1 + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * ans))))
ans = ans * ax[idx_b].exp() / ax[idx_b].sqrt()
- out[idx_b] = where(x[idx_b] < 0, -ans, ans)
+ out[idx_b] = torch.where(x[idx_b] < 0, -ans, ans)
return out
-def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
+def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
"""Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
KORNIA_CHECK(n >= 2, "n must be greater than 1.99")
@@ -243,8 +246,12 @@ def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
def gaussian_discrete(
- window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ window_size: int,
+ sigma: torch.Tensor | float,
+ *,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Discrete Gaussian kernel based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
@@ -260,7 +267,7 @@ def gaussian_discrete(
"""
if isinstance(sigma, float):
- sigma = tensor([[sigma]], device=device, dtype=dtype)
+ sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
@@ -273,12 +280,14 @@ def gaussian_discrete(
]
# NOTE: on monain is exp(-sig)
# https://github.com/Project-MONAI/MONAI/blob/dev/monai/networks/layers/convutils.py#L128
- out = concatenate(bessels[:0:-1] + bessels, -1) * sigma2.exp()
+ out = torch.cat(bessels[:0:-1] + bessels, -1) * sigma2.exp()
return out / out.sum(-1, keepdim=True)
-def laplacian_1d(window_size: int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32) -> Tensor:
+def laplacian_1d(
+ window_size: int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
"""One could also use the Laplacian of Gaussian formula to design the filter."""
# TODO: add default dtype as None when kornia relies on torch > 1.12
filter_1d = torch.ones(window_size, device=device, dtype=dtype)
@@ -287,7 +296,9 @@ def laplacian_1d(window_size: int, *, device: Optional[Device] = None, dtype: Dt
return filter_1d
-def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_box_kernel1d(
+ kernel_size: int, *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
r"""Return a 1-D box filter.
Args:
@@ -300,13 +311,13 @@ def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype
:math:`\frac{1}{\text{kernel\_size}}`.
"""
- scale = tensor(1.0 / kernel_size, device=device, dtype=dtype)
+ scale = torch.tensor(1.0 / kernel_size, device=device, dtype=dtype)
return scale.expand(1, kernel_size)
def get_box_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ kernel_size: tuple[int, int] | int, *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
r"""Return a 2-D box filter.
Args:
@@ -320,13 +331,13 @@ def get_box_kernel2d(
"""
ky, kx = _unpack_2d_ks(kernel_size)
- scale = tensor(1.0 / (kx * ky), device=device, dtype=dtype)
+ scale = torch.tensor(1.0 / (kx * ky), device=device, dtype=dtype)
return scale.expand(1, ky, kx)
def get_binary_kernel2d(
- window_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
-) -> Tensor:
+ window_size: tuple[int, int] | int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
"""Create a binary kernel to extract the patches.
If the window size is HxW will create a (H*W)x1xHxW kernel.
@@ -337,20 +348,22 @@ def get_binary_kernel2d(
window_range = kx * ky
- kernel = zeros((window_range, window_range), device=device, dtype=dtype)
+ kernel = torch.zeros((window_range, window_range), device=device, dtype=dtype)
idx = torch.arange(window_range, device=device)
kernel[idx, idx] += 1.0
return kernel.view(window_range, 1, ky, kx)
-def get_sobel_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_sobel_kernel_3x3(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return a sobel kernel of 3x3."""
- return tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ return torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
-def get_sobel_kernel_5x5_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_sobel_kernel_5x5_2nd_order(
+ *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Return a 2nd order sobel kernel of 5x5."""
- return tensor(
+ return torch.tensor(
[
[-1.0, 0.0, 2.0, 0.0, -1.0],
[-4.0, 0.0, 8.0, 0.0, -4.0],
@@ -363,9 +376,11 @@ def get_sobel_kernel_5x5_2nd_order(*, device: Optional[Device] = None, dtype: Op
)
-def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def _get_sobel_kernel_5x5_2nd_order_xy(
+ *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Return a 2nd order sobel kernel of 5x5."""
- return tensor(
+ return torch.tensor(
[
[-1.0, -2.0, 0.0, 2.0, 1.0],
[-2.0, -4.0, 0.0, 4.0, 2.0],
@@ -378,14 +393,14 @@ def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Optional[Device] = None, dtype
)
-def get_diff_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_diff_kernel_3x3(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return a first order derivative kernel of 3x3."""
- return tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ return torch.tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]], device=device, dtype=dtype)
-def get_diff_kernel3d(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_diff_kernel3d(device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return a first order derivative kernel of 3x3x3."""
- kernel = tensor(
+ kernel = torch.tensor(
[
[
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
@@ -409,9 +424,11 @@ def get_diff_kernel3d(device: Optional[Device] = None, dtype: Optional[Dtype] =
return kernel[:, None, ...]
-def get_diff_kernel3d_2nd_order(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_diff_kernel3d_2nd_order(
+ device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Return a first order derivative kernel of 3x3x3."""
- kernel = tensor(
+ kernel = torch.tensor(
[
[
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
@@ -450,39 +467,47 @@ def get_diff_kernel3d_2nd_order(device: Optional[Device] = None, dtype: Optional
return kernel[:, None, ...]
-def get_sobel_kernel2d(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_sobel_kernel2d(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return 1st order gradient for sobel operator."""
kernel_x = get_sobel_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
- return stack([kernel_x, kernel_y])
+ return torch.stack([kernel_x, kernel_y])
-def get_diff_kernel2d(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_diff_kernel2d(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return 1st order gradient for diff operator."""
kernel_x = get_diff_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
- return stack([kernel_x, kernel_y])
+ return torch.stack([kernel_x, kernel_y])
-def get_sobel_kernel2d_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_sobel_kernel2d_2nd_order(
+ *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Return 2nd order gradient for sobel operator."""
gxx = get_sobel_kernel_5x5_2nd_order(device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
gxy = _get_sobel_kernel_5x5_2nd_order_xy(device=device, dtype=dtype)
- return stack([gxx, gxy, gyy])
+ return torch.stack([gxx, gxy, gyy])
-def get_diff_kernel2d_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_diff_kernel2d_2nd_order(
+ *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Return 2nd order gradient for diff operator."""
- gxx = tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ gxx = torch.tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
- gxy = tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]], device=device, dtype=dtype)
- return stack([gxx, gxy, gyy])
+ gxy = torch.tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]], device=device, dtype=dtype)
+ return torch.stack([gxx, gxy, gyy])
def get_spatial_gradient_kernel2d(
- mode: str, order: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ mode: str,
+ order: int,
+ *,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return kernel for 1st or 2nd order image gradients.
Uses one of the following operators: sobel, diff.
@@ -491,7 +516,7 @@ def get_spatial_gradient_kernel2d(
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
if mode == "sobel" and order == 1:
- kernel: Tensor = get_sobel_kernel2d(device=device, dtype=dtype)
+ kernel: torch.Tensor = get_sobel_kernel2d(device=device, dtype=dtype)
elif mode == "sobel" and order == 2:
kernel = get_sobel_kernel2d_2nd_order(device=device, dtype=dtype)
elif mode == "diff" and order == 1:
@@ -505,8 +530,8 @@ def get_spatial_gradient_kernel2d(
def get_spatial_gradient_kernel3d(
- mode: str, order: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ mode: str, order: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
r"""Return kernel for 1st or 2nd order scale pyramid gradients.
Uses one of the following operators: sobel, diff.
@@ -526,12 +551,12 @@ def get_spatial_gradient_kernel3d(
def get_gaussian_kernel1d(
kernel_size: int,
- sigma: float | Tensor,
+ sigma: float | torch.Tensor,
force_even: bool = False,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return Gaussian filter coefficients.
Args:
@@ -561,12 +586,12 @@ def get_gaussian_kernel1d(
def get_gaussian_discrete_kernel1d(
kernel_size: int,
- sigma: float | Tensor,
+ sigma: float | torch.Tensor,
force_even: bool = False,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return Gaussian filter coefficients based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -598,12 +623,12 @@ def get_gaussian_discrete_kernel1d(
def get_gaussian_erf_kernel1d(
kernel_size: int,
- sigma: float | Tensor,
+ sigma: float | torch.Tensor,
force_even: bool = False,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return Gaussian filter coefficients by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -635,12 +660,12 @@ def get_gaussian_erf_kernel1d(
def get_gaussian_kernel2d(
kernel_size: tuple[int, int] | int,
- sigma: tuple[float, float] | Tensor,
+ sigma: tuple[float, float] | torch.Tensor,
force_even: bool = False,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return Gaussian filter matrix coefficients.
Args:
@@ -676,7 +701,7 @@ def get_gaussian_kernel2d(
"""
if isinstance(sigma, tuple):
- sigma = tensor([sigma], device=device, dtype=dtype)
+ sigma = torch.tensor([sigma], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
@@ -692,12 +717,12 @@ def get_gaussian_kernel2d(
def get_gaussian_kernel3d(
kernel_size: tuple[int, int, int] | int,
- sigma: tuple[float, float, float] | Tensor,
+ sigma: tuple[float, float, float] | torch.Tensor,
force_even: bool = False,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return Gaussian filter matrix coefficients.
Args:
@@ -735,7 +760,7 @@ def get_gaussian_kernel3d(
"""
if isinstance(sigma, tuple):
- sigma = tensor([sigma], device=device, dtype=dtype)
+ sigma = torch.tensor([sigma], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "3"])
@@ -751,8 +776,8 @@ def get_gaussian_kernel3d(
def get_laplacian_kernel1d(
- kernel_size: int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
-) -> Tensor:
+ kernel_size: int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
r"""Return the coefficients of a 1D Laplacian filter.
Args:
@@ -781,8 +806,8 @@ def get_laplacian_kernel1d(
def get_laplacian_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
-) -> Tensor:
+ kernel_size: tuple[int, int] | int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
r"""Return Gaussian filter matrix coefficients.
Args:
@@ -826,9 +851,9 @@ def get_pascal_kernel_2d(
kernel_size: tuple[int, int] | int,
norm: bool = True,
*,
- device: Optional[Device] = None,
- dtype: Optional[Dtype] = None,
-) -> Tensor:
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
"""Generate pascal filter kernel by kernel size.
Args:
@@ -867,8 +892,8 @@ def get_pascal_kernel_2d(
def get_pascal_kernel_1d(
- kernel_size: int, norm: bool = False, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ kernel_size: int, norm: bool = False, *, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
Args:
@@ -907,7 +932,7 @@ def get_pascal_kernel_1d(
cur[-j - 1] = value
pre = cur
- out = tensor(cur, device=device, dtype=dtype)
+ out = torch.tensor(cur, device=device, dtype=dtype)
if norm:
out = out / out.sum()
@@ -915,9 +940,9 @@ def get_pascal_kernel_1d(
return out
-def get_canny_nms_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_canny_nms_kernel(device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return 3x3 kernels for the Canny Non-maximal suppression."""
- return tensor(
+ return torch.tensor(
[
[[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]],
[[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]],
@@ -933,9 +958,9 @@ def get_canny_nms_kernel(device: Optional[Device] = None, dtype: Optional[Dtype]
)
-def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_hysteresis_kernel(device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return the 3x3 kernels for the Canny hysteresis."""
- return tensor(
+ return torch.tensor(
[
[[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]],
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]],
@@ -951,7 +976,9 @@ def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype
)
-def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
+def get_hanning_kernel1d(
+ kernel_size: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
r"""Return Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
@@ -976,13 +1003,15 @@ def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtyp
_check_kernel_size(kernel_size, 2, allow_even=True)
x = torch.arange(kernel_size, device=device, dtype=dtype)
- x = 0.5 - 0.5 * cos(2.0 * math.pi * x / float(kernel_size - 1))
+ x = 0.5 - 0.5 * torch.cos(2.0 * math.pi * x / float(kernel_size - 1))
return x
def get_hanning_kernel2d(
- kernel_size: tuple[int, int] | int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
-) -> Tensor:
+ kernel_size: tuple[int, int] | int,
+ device: Optional[Union[str, torch.device]] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
r"""Return 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
@@ -1006,15 +1035,15 @@ def get_hanning_kernel2d(
@deprecated(replace_with="get_gaussian_kernel1d", version="6.9.10")
-def get_gaussian_kernel1d_t(*args: Any, **kwargs: Any) -> Tensor: # noqa: D103
+def get_gaussian_kernel1d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103
return get_gaussian_kernel1d(*args, **kwargs)
@deprecated(replace_with="get_gaussian_kernel2d", version="6.9.10")
-def get_gaussian_kernel2d_t(*args: Any, **kwargs: Any) -> Tensor: # noqa: D103
+def get_gaussian_kernel2d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103
return get_gaussian_kernel2d(*args, **kwargs)
@deprecated(replace_with="get_gaussian_kernel3d", version="6.9.10")
-def get_gaussian_kernel3d_t(*args: Any, **kwargs: Any) -> Tensor: # noqa: D103
+def get_gaussian_kernel3d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103
return get_gaussian_kernel3d(*args, **kwargs)
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 24aabfa80..e72663e18 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -18,8 +18,8 @@
from __future__ import annotations
import torch
+import torch.nn.functional as F
-from kornia.core import Tensor, pad, stack, tensor, zeros
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.transform import rotate, rotate3d
from kornia.utils import _extract_device_dtype
@@ -28,8 +28,8 @@ from .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks
def get_motion_kernel2d(
- kernel_size: int, angle: Tensor | float, direction: Tensor | float = 0.0, mode: str = "nearest"
-) -> Tensor:
+ kernel_size: int, angle: torch.Tensor | float, direction: torch.Tensor | float = 0.0, mode: str = "nearest"
+) -> torch.Tensor:
r"""Return 2D motion blur filter.
Args:
@@ -59,23 +59,23 @@ def get_motion_kernel2d(
"""
device, dtype = _extract_device_dtype(
- [angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
+ [angle if isinstance(angle, torch.Tensor) else None, direction if isinstance(direction, torch.Tensor) else None]
)
# TODO: add support to kernel_size as tuple or integer
kernel_tuple = _unpack_2d_ks(kernel_size)
_check_kernel_size(kernel_size, 2)
- if not isinstance(angle, Tensor):
- angle = tensor([angle], device=device, dtype=dtype)
+ if not isinstance(angle, torch.Tensor):
+ angle = torch.tensor([angle], device=device, dtype=dtype)
if angle.dim() == 0:
angle = angle[None]
KORNIA_CHECK_SHAPE(angle, ["B"])
- if not isinstance(direction, Tensor):
- direction = tensor([direction], device=device, dtype=dtype)
+ if not isinstance(direction, torch.Tensor):
+ direction = torch.tensor([direction], device=device, dtype=dtype)
if direction.dim() == 0:
direction = direction[None]
@@ -96,8 +96,8 @@ def get_motion_kernel2d(
# Alternatively
# m = ((1 - 2 * direction)[:, None].repeat(1, kernel_size) / (kernel_size - 1))
# kernel[:, kernel_size // 2, :] = direction[:, None].repeat(1, kernel_size) + m * torch.arange(0, kernel_size)
- k = stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
- kernel = pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
+ kernel = F.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Gotcha {kernel.shape}")
@@ -111,8 +111,11 @@ def get_motion_kernel2d(
def get_motion_kernel3d(
- kernel_size: int, angle: Tensor | tuple[float, float, float], direction: Tensor | float = 0.0, mode: str = "nearest"
-) -> Tensor:
+ kernel_size: int,
+ angle: torch.Tensor | tuple[float, float, float],
+ direction: torch.Tensor | float = 0.0,
+ mode: str = "nearest",
+) -> torch.Tensor:
r"""Return 3D motion blur filter.
Args:
@@ -158,23 +161,23 @@ def get_motion_kernel3d(
"""
device, dtype = _extract_device_dtype(
- [angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
+ [angle if isinstance(angle, torch.Tensor) else None, direction if isinstance(direction, torch.Tensor) else None]
)
# TODO: add support to kernel_size as tuple or integer
kernel_tuple = _unpack_3d_ks(kernel_size)
_check_kernel_size(kernel_size, 2)
- if not isinstance(angle, Tensor):
- angle = tensor([angle], device=device, dtype=dtype)
+ if not isinstance(angle, torch.Tensor):
+ angle = torch.tensor([angle], device=device, dtype=dtype)
if angle.dim() == 1:
angle = angle[None]
KORNIA_CHECK_SHAPE(angle, ["B", "3"])
- if not isinstance(direction, Tensor):
- direction = tensor([direction], device=device, dtype=dtype)
+ if not isinstance(direction, torch.Tensor):
+ direction = torch.tensor([direction], device=device, dtype=dtype)
if direction.dim() == 0:
direction = direction[None]
@@ -187,13 +190,15 @@ def get_motion_kernel3d(
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
- kernel = zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)
+ kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)
# Element-wise linspace
# kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(
# [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
- k = stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
- kernel = pad(k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])
+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
+ kernel = F.pad(
+ k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0]
+ )
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Gotcha {kernel.shape}")
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index a96ebe8c3..cf97ff992 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -17,15 +17,16 @@
from __future__ import annotations
-from kornia.core import Module, Tensor
+import torch
+from torch import nn
from .filter import filter2d
from .kernels import get_laplacian_kernel2d, normalize_kernel2d
def laplacian(
- input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", normalized: bool = True
-) -> Tensor:
+ input: torch.Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", normalized: bool = True
+) -> torch.Tensor:
r"""Create an operator that returns a tensor using a Laplacian filter.
.. image:: _static/img/laplacian.png
@@ -62,7 +63,7 @@ def laplacian(
return filter2d(input, kernel, border_type)
-class Laplacian(Module):
+class Laplacian(nn.Module):
r"""Create an operator that returns a tensor using a Laplacian filter.
The operator smooths the given tensor with a laplacian kernel by convolving
@@ -104,5 +105,5 @@ class Laplacian(Module):
f"border_type={self.border_type})"
)
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return laplacian(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 29dc6111f..2d2e68592 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -17,10 +17,10 @@
from __future__ import annotations
+import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import _unpack_2d_ks, get_binary_kernel2d
@@ -32,7 +32,7 @@ def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]
return (ky - 1) // 2, (kx - 1) // 2
-def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
+def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torch.Tensor:
r"""Blur an image using the median filter.
.. image:: _static/img/median_blur.png
@@ -42,7 +42,7 @@ def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
kernel_size: the blurring kernel size.
Returns:
- the blurred input tensor with shape :math:`(B,C,H,W)`.
+ the blurred input torch.tensor with shape :math:`(B,C,H,W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/filtering_operators.html>`__.
@@ -60,25 +60,25 @@ def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
padding = _compute_zero_padding(kernel_size)
# prepare kernel
- kernel: Tensor = get_binary_kernel2d(kernel_size, device=input.device, dtype=input.dtype)
+ kernel: torch.Tensor = get_binary_kernel2d(kernel_size, device=input.device, dtype=input.dtype)
b, c, h, w = input.shape
# map the local window to single vector
- features: Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
+ features: torch.Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
features = features.view(b, c, -1, h, w) # BxCx(K_h * K_w)xHxW
# compute the median along the feature axis
return features.median(dim=2)[0]
-class MedianBlur(Module):
+class MedianBlur(nn.Module):
r"""Blur an image using the median filter.
Args:
kernel_size: the blurring kernel size.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -97,5 +97,5 @@ class MedianBlur(Module):
super().__init__()
self.kernel_size = kernel_size
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return median_blur(input, self.kernel_size)
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 33179de9a..83a275f8d 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -19,8 +19,9 @@ from __future__ import annotations
from typing import ClassVar
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK
from .filter import filter2d, filter3d
@@ -29,8 +30,8 @@ from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3d
_VALID_BORDER = {"constant", "reflect", "replicate", "circular"}
-class MotionBlur(Module):
- r"""Blur 2D images (4D tensor) using the motion filter.
+class MotionBlur(nn.Module):
+ r"""Blur 2D images (4D torch.tensor) using the motion filter.
Args:
kernel_size: motion kernel width and height. It should be odd and positive.
@@ -44,7 +45,7 @@ class MotionBlur(Module):
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -73,12 +74,12 @@ class MotionBlur(Module):
f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"
)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)
-class MotionBlur3D(Module):
- r"""Blur 3D volumes (5D tensor) using the motion filter.
+class MotionBlur3D(nn.Module):
+ r"""Blur 3D volumes (5D torch.tensor) using the motion filter.
Args:
kernel_size: motion kernel width and height. It should be odd and positive.
@@ -92,7 +93,7 @@ class MotionBlur3D(Module):
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
- the blurred input tensor.
+ the blurred input torch.tensor.
Shape:
- Input: :math:`(B, C, D, H, W)`
@@ -112,16 +113,16 @@ class MotionBlur3D(Module):
def __init__(
self,
kernel_size: int,
- angle: float | tuple[float, float, float] | Tensor,
- direction: float | Tensor,
+ angle: float | tuple[float, float, float] | torch.Tensor,
+ direction: float | torch.Tensor,
border_type: str = "constant",
mode: str = "nearest",
) -> None:
super().__init__()
self.kernel_size = kernel_size
KORNIA_CHECK(
- isinstance(angle, (Tensor, float, list, tuple)),
- f"Angle should be a Tensor, float or a sequence of floats. Got {angle}",
+ isinstance(angle, (torch.Tensor, float, list, tuple)),
+ f"Angle should be a torch.Tensor, float or a sequence of floats. Got {angle}",
)
if isinstance(angle, float):
self.angle = (angle, angle, angle)
@@ -138,32 +139,32 @@ class MotionBlur3D(Module):
f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"
)
- def forward(self, x: Tensor) -> Tensor:
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)
def motion_blur(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: int,
- angle: float | Tensor,
- direction: float | Tensor,
+ angle: float | torch.Tensor,
+ direction: float | torch.Tensor,
border_type: str = "constant",
mode: str = "nearest",
-) -> Tensor:
- r"""Perform motion blur on tensor images.
+) -> torch.Tensor:
+ r"""Perform motion blur on torch.tensor images.
.. image:: _static/img/motion_blur.png
Args:
- input: the input tensor with shape :math:`(B, C, H, W)`.
+ input: the input torch.tensor with shape :math:`(B, C, H, W)`.
kernel_size: motion kernel width and height. It should be odd and positive.
angle (Union[torch.Tensor, float]): angle of the motion blur in degrees (anti-clockwise rotation).
- If tensor, it must be :math:`(B,)`.
+ If torch.tensor, it must be :math:`(B,)`.
direction : forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
uniformly (but still angled) motion blur.
- If tensor, it must be :math:`(B,)`.
+ If torch.tensor, it must be :math:`(B,)`.
border_type: the padding mode to be applied before convolving. The expected modes are:
``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
@@ -188,25 +189,25 @@ def motion_blur(
def motion_blur3d(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: int,
- angle: tuple[float, float, float] | Tensor,
- direction: float | Tensor,
+ angle: tuple[float, float, float] | torch.Tensor,
+ direction: float | torch.Tensor,
border_type: str = "constant",
mode: str = "nearest",
-) -> Tensor:
- r"""Perform motion blur on 3D volumes (5D tensor).
+) -> torch.Tensor:
+ r"""Perform motion blur on 3D volumes (5D torch.tensor).
Args:
- input: the input tensor with shape :math:`(B, C, D, H, W)`.
+ input: the input torch.tensor with shape :math:`(B, C, D, H, W)`.
kernel_size: motion kernel width, height and depth. It should be odd and positive.
angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
- If tensor, it must be :math:`(B, 3)`.
+ If torch.tensor, it must be :math:`(B, 3)`.
direction: forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
uniformly (but still angled) motion blur.
- If tensor, it must be :math:`(B,)`.
+ If torch.tensor, it must be :math:`(B,)`.
border_type: the padding mode to be applied before convolving. The expected modes are:
``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 6df969941..a24eebad2 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -21,21 +21,20 @@ from typing import ClassVar
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, pad
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
-def spatial_gradient(input: Tensor, mode: str = "sobel", order: int = 1, normalized: bool = True) -> Tensor:
+def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, normalized: bool = True) -> torch.Tensor:
r"""Compute the first order image derivative in both x and y using a Sobel operator.
.. image:: _static/img/spatial_gradient.png
Args:
- input: input image tensor with shape :math:`(B, C, H, W)`.
+ input: input image torch.tensor with shape :math:`(B, C, H, W)`.
mode: derivatives modality, can be: `sobel` or `diff`.
order: the order of the derivatives.
normalized: whether the output is normalized.
@@ -65,19 +64,19 @@ def spatial_gradient(input: Tensor, mode: str = "sobel", order: int = 1, normali
b, c, h, w = input.shape
tmp_kernel = kernel[:, None, ...]
- # Pad with "replicate for spatial dims, but with zeros for channel
+ # Pad with "replicate for spatial dims, but with torch.zeros for channel
spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
out_channels: int = 3 if order == 2 else 2
- padded_inp: Tensor = pad(input.reshape(b * c, 1, h, w), spatial_pad, "replicate")
+ padded_inp: torch.Tensor = F.pad(input.reshape(b * c, 1, h, w), spatial_pad, "replicate")
out = F.conv2d(padded_inp, tmp_kernel, groups=1, padding=0, stride=1)
return out.reshape(b, c, out_channels, h, w)
-def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Tensor:
+def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1) -> torch.Tensor:
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
- input: input features tensor with shape :math:`(B, C, D, H, W)`.
+ input: input features torch.tensor with shape :math:`(B, C, D, H, W)`.
mode: derivatives modality, can be: `sobel` or `diff`.
order: the order of the derivatives.
@@ -100,7 +99,7 @@ def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Ten
dtype = input.dtype
if (mode == "diff") and (order == 1):
# we go for the special case implementation due to conv3d bad speed
- x: Tensor = pad(input, 6 * [1], "replicate")
+ x: torch.Tensor = F.pad(input, 6 * [1], "replicate")
center = slice(1, -1)
left = slice(0, -2)
right = slice(2, None)
@@ -116,10 +115,10 @@ def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Ten
tmp_kernel = kernel.repeat(c, 1, 1, 1, 1)
- # convolve input tensor with grad kernel
+ # convolve input torch.tensor with grad kernel
kernel_flip = tmp_kernel.flip(-3)
- # Pad with "replicate for spatial dims, but with zeros for channel
+ # Pad with "replicate for spatial dims, but with torch.zeros for channel
spatial_pad = [
kernel.size(2) // 2,
kernel.size(2) // 2,
@@ -129,13 +128,13 @@ def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Ten
kernel.size(4) // 2,
]
out_ch: int = 6 if order == 2 else 3
- out = F.conv3d(pad(input, spatial_pad, "replicate"), kernel_flip, padding=0, groups=c).view(
+ out = F.conv3d(F.pad(input, spatial_pad, "replicate"), kernel_flip, padding=0, groups=c).view(
b, c, out_ch, d, h, w
)
return out
-def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
+def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:
r"""Compute the Sobel operator and returns the magnitude per channel.
.. image:: _static/img/sobel.png
@@ -162,19 +161,19 @@ def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
# comput the x/y gradients
- edges: Tensor = spatial_gradient(input, normalized=normalized)
+ edges: torch.Tensor = spatial_gradient(input, normalized=normalized)
# unpack the edges
- gx: Tensor = edges[:, :, 0]
- gy: Tensor = edges[:, :, 1]
+ gx: torch.Tensor = edges[:, :, 0]
+ gy: torch.Tensor = edges[:, :, 1]
# compute gradient maginitude
- magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps)
+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)
return magnitude
-class SpatialGradient(Module):
+class SpatialGradient(nn.Module):
r"""Compute the first order image derivative in both x and y using a Sobel operator.
Args:
@@ -207,11 +206,11 @@ class SpatialGradient(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(order={self.order}, normalized={self.normalized}, mode={self.mode})"
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return spatial_gradient(input, self.mode, self.order, self.normalized)
-class SpatialGradient3d(Module):
+class SpatialGradient3d(nn.Module):
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
@@ -245,11 +244,11 @@ class SpatialGradient3d(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(order={self.order}, mode={self.mode})"
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return spatial_gradient3d(input, self.mode, self.order)
-class Sobel(Module):
+class Sobel(nn.Module):
r"""Compute the Sobel operator and returns the magnitude per channel.
Args:
@@ -277,5 +276,5 @@ class Sobel(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(normalized={self.normalized})"
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return sobel(input, self.normalized, self.eps)
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index a5268ad2c..07119c815 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -18,22 +18,23 @@
from __future__ import annotations
import torch
-
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+from torch import nn
from .gaussian import gaussian_blur2d
def unsharp_mask(
- input: Tensor, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = "reflect"
-) -> Tensor:
- r"""Create an operator that sharpens a tensor by applying operation out = 2 * image - gaussian_blur2d(image).
+ input: torch.Tensor,
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | torch.Tensor,
+ border_type: str = "reflect",
+) -> torch.Tensor:
+ r"""Create an operator that sharpens a torch.tensor by applying operation out = 2 * image - gaussian_blur2d(image).
.. image:: _static/img/unsharp_mask.png
Args:
- input: the input tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma: the standard deviation of the kernel.
border_type: the padding mode to be applied before convolving.
@@ -41,7 +42,7 @@ def unsharp_mask(
``'replicate'`` or ``'circular'``.
Returns:
- the blurred tensor with shape :math:`(B,C,H,W)`.
+ the blurred torch.tensor with shape :math:`(B,C,H,W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -50,11 +51,11 @@ def unsharp_mask(
torch.Size([2, 4, 5, 5])
"""
- data_blur: Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
+ data_blur: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
return torch.lerp(data_blur, input, weight=2.0)
-class UnsharpMask(Module):
+class UnsharpMask(nn.Module):
r"""Create an operator that sharpens image with: out = 2 * image - gaussian_blur2d(image).
Args:
@@ -65,7 +66,7 @@ class UnsharpMask(Module):
``'replicate'`` or ``'circular'``.
Returns:
- the sharpened tensor with shape :math:`(B,C,H,W)`.
+ the sharpened torch.tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -84,12 +85,15 @@ class UnsharpMask(Module):
"""
def __init__(
- self, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = "reflect"
+ self,
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | torch.Tensor,
+ border_type: str = "reflect",
) -> None:
super().__init__()
self.kernel_size = kernel_size
self.sigma = sigma
self.border_type = border_type
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return unsharp_mask(input, self.kernel_size, self.sigma, self.border_type)
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 3ccf620ee..f0f0e1510 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -22,8 +22,6 @@ from typing import Optional
import torch
-from kornia.core import arange, stack, where
-
from .linalg import transform_points
__all__ = [
@@ -298,9 +296,9 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
x_min = boxes[:, 0, 0].long()
x_max = boxes[:, 1, 0].long()
- z = arange(D0, device=boxes.device, dtype=torch.long)
- y = arange(D1, device=boxes.device, dtype=torch.long)
- x = arange(D2, device=boxes.device, dtype=torch.long)
+ z = torch.arange(D0, device=boxes.device, dtype=torch.long)
+ y = torch.arange(D1, device=boxes.device, dtype=torch.long)
+ x = torch.arange(D2, device=boxes.device, dtype=torch.long)
# Compute mask as union of planes in one step
m = (
@@ -582,10 +580,10 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
- inds = where(ovr <= iou_threshold)[0]
+ inds = torch.where(ovr <= iou_threshold)[0]
order = order[inds + 1]
if len(keep) > 0:
- return stack(keep)
+ return torch.stack(keep)
return torch.tensor(keep)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 9741dddd4..08fc40ce7 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -22,7 +22,6 @@ from typing import Optional, Tuple, cast
import torch
from torch import Size
-from kornia.core import Tensor, stack, zeros
from kornia.geometry.bbox import validate_bbox
from kornia.geometry.linalg import transform_points
from kornia.utils import eye_like
@@ -86,7 +85,7 @@ def _boxes_to_polygons(
raise ValueError("We expect to create a batch of 2D boxes (quadrilaterals) in vertices format (B, N, 4, 2)")
# Create (B,N,4,2) with all points in top left position of boxes
- polygons = zeros((xmin.shape[0], xmin.shape[1], 4, 2), device=xmin.device, dtype=xmin.dtype)
+ polygons = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 2), device=xmin.device, dtype=xmin.dtype)
polygons[..., 0] = xmin.unsqueeze(-1)
polygons[..., 1] = ymin.unsqueeze(-1)
# Shift top-right, bottom-right, bottom-left points to the right coordinates
@@ -168,7 +167,7 @@ def _boxes3d_to_polygons3d(
# Front
# Create (B,N,4,3) with all points in front top left position of boxes
- front_vertices = zeros((xmin.shape[0], xmin.shape[1], 4, 3), device=xmin.device, dtype=xmin.dtype)
+ front_vertices = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 3), device=xmin.device, dtype=xmin.dtype)
front_vertices[..., 0] = xmin.unsqueeze(-1)
front_vertices[..., 1] = ymin.unsqueeze(-1)
front_vertices[..., 2] = zmin.unsqueeze(-1)
@@ -237,12 +236,12 @@ class Boxes:
self._data = boxes
self._mode = mode
- def __getitem__(self, key: slice | int | Tensor) -> Boxes:
+ def __getitem__(self, key: slice | int | torch.Tensor) -> Boxes:
new_box = type(self)(self._data[key], False)
new_box._mode = self._mode
return new_box
- def __setitem__(self, key: slice | int | Tensor, value: Boxes) -> Boxes:
+ def __setitem__(self, key: slice | int | torch.Tensor, value: Boxes) -> Boxes:
self._data[key] = value._data
return self
@@ -289,7 +288,10 @@ class Boxes:
return obj
def index_put(
- self, indices: tuple[Tensor, ...] | list[Tensor], values: Tensor | Boxes, inplace: bool = False
+ self,
+ indices: tuple[torch.Tensor, ...] | list[torch.Tensor],
+ values: torch.Tensor | Boxes,
+ inplace: bool = False,
) -> Boxes:
if inplace:
_data = self._data
@@ -308,7 +310,7 @@ class Boxes:
obj._data = _data
return obj
- def pad(self, padding_size: Tensor) -> Boxes:
+ def pad(self, padding_size: torch.Tensor) -> Boxes:
"""Pad a bounding box.
Args:
@@ -321,7 +323,7 @@ class Boxes:
self._data[..., 1] += padding_size[..., None, 2:3].to(device=self._data.device) # top padding
return self
- def unpad(self, padding_size: Tensor) -> Boxes:
+ def unpad(self, padding_size: torch.Tensor) -> Boxes:
"""Pad a bounding box.
Args:
@@ -336,11 +338,11 @@ class Boxes:
def clamp(
self,
- topleft: Optional[Tensor | tuple[int, int]] = None,
- botright: Optional[Tensor | tuple[int, int]] = None,
+ topleft: Optional[torch.Tensor | tuple[int, int]] = None,
+ botright: Optional[torch.Tensor | tuple[int, int]] = None,
inplace: bool = False,
) -> Boxes:
- if not (isinstance(topleft, Tensor) and isinstance(botright, Tensor)):
+ if not (isinstance(topleft, torch.Tensor) and isinstance(botright, torch.Tensor)):
raise NotImplementedError
if inplace:
_data = self._data
@@ -628,7 +630,7 @@ class Boxes:
else:
out_shape = (self.shape[0], height, width)
- clipped_boxes_xyxy = cast(Tensor, self.to_tensor("xyxy", as_padded_sequence=True))
+ clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))
clipped_boxes_xyxy[..., ::2].clamp_(0, width)
clipped_boxes_xyxy[..., 1::2].clamp_(0, height)
@@ -676,7 +678,7 @@ class Boxes:
"""Inplace version of :func:`Boxes.transform_boxes`."""
return self.transform_boxes(M, inplace=True)
- def translate(self, size: Tensor, method: str = "warp", inplace: bool = False) -> Boxes:
+ def translate(self, size: torch.Tensor, method: str = "warp", inplace: bool = False) -> Boxes:
"""Translate boxes by the provided size.
Args:
@@ -695,7 +697,7 @@ class Boxes:
else:
raise NotImplementedError
- M: Tensor = eye_like(3, size)
+ M: torch.Tensor = eye_like(3, size)
M[:, :2, 2] = size
return self.transform_boxes(M, inplace=inplace)
@@ -760,7 +762,7 @@ class VideoBoxes(Boxes):
def to_tensor(self, mode: Optional[str] = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]
out = super().to_tensor(mode, as_padded_sequence=False)
- if isinstance(out, Tensor):
+ if isinstance(out, torch.Tensor):
return out.view(-1, self.temporal_channel_size, *out.shape[1:])
# If returns a list of boxes.
return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]
@@ -814,12 +816,12 @@ class Boxes3D:
self._data = boxes
self._mode = mode
- def __getitem__(self, key: slice | int | Tensor) -> Boxes3D:
+ def __getitem__(self, key: slice | int | torch.Tensor) -> Boxes3D:
new_box = Boxes3D(self._data[key], False, mode="xyzxyz_plus")
new_box._mode = self._mode
return new_box
- def __setitem__(self, key: slice | int | Tensor, value: Boxes3D) -> Boxes3D:
+ def __setitem__(self, key: slice | int | torch.Tensor, value: Boxes3D) -> Boxes3D:
self._data[key] = value._data
return self
@@ -973,7 +975,7 @@ class Boxes3D:
batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
# Create boxes in xyzxyz_plus format.
- boxes = stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
+ boxes = torch.stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
batched_boxes.shape[0], batched_boxes.shape[1], 6
)
@@ -1061,13 +1063,15 @@ class Boxes3D:
)
if self._is_batched: # (B, N, 8, 3)
- mask = zeros(
+ mask = torch.zeros(
(self._data.shape[0], self._data.shape[1], depth, height, width),
dtype=self._data.dtype,
device=self._data.device,
)
else: # (N, 8, 3)
- mask = zeros((self._data.shape[0], depth, height, width), dtype=self._data.dtype, device=self._data.device)
+ mask = torch.zeros(
+ (self._data.shape[0], depth, height, width), dtype=self._data.dtype, device=self._data.device
+ )
# Boxes coordinates can be outside the image size after transforms. Clamp values to the image size
clipped_boxes_xyzxyz = self.to_tensor("xyzxyz")
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index 804c93ce9..57757cd9f 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -18,8 +18,7 @@
from typing import Optional
import torch
-
-from kornia.core import cos, ones_like, sin, stack, zeros_like
+import torch.nn.functional as F
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75
@@ -42,20 +41,20 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
taux = taux.reshape(-1)
tauy = tauy.reshape(-1)
- cTx = cos(taux)
- sTx = sin(taux)
- cTy = cos(tauy)
- sTy = sin(tauy)
- zero = zeros_like(cTx)
- one = ones_like(cTx)
+ cTx = torch.cos(taux)
+ sTx = torch.sin(taux)
+ cTy = torch.cos(tauy)
+ sTy = torch.sin(tauy)
+ zero = torch.zeros_like(cTx)
+ one = torch.ones_like(cTx)
- Rx = stack([one, zero, zero, zero, cTx, sTx, zero, -sTx, cTx], -1).reshape(-1, 3, 3)
- Ry = stack([cTy, zero, -sTy, zero, one, zero, sTy, zero, cTy], -1).reshape(-1, 3, 3)
+ Rx = torch.stack([one, zero, zero, zero, cTx, sTx, zero, -sTx, cTx], -1).reshape(-1, 3, 3)
+ Ry = torch.stack([cTy, zero, -sTy, zero, one, zero, sTy, zero, cTy], -1).reshape(-1, 3, 3)
R = Ry @ Rx
if return_inverse:
invR22 = 1 / R[..., 2, 2]
- invPz = stack(
+ invPz = torch.stack(
[invR22, zero, R[..., 0, 2] * invR22, zero, invR22, R[..., 1, 2] * invR22, zero, zero, one], -1
).reshape(-1, 3, 3)
@@ -65,9 +64,9 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
return inv_tilt
- Pz = stack([R[..., 2, 2], zero, -R[..., 0, 2], zero, R[..., 2, 2], -R[..., 1, 2], zero, zero, one], -1).reshape(
- -1, 3, 3
- )
+ Pz = torch.stack(
+ [R[..., 2, 2], zero, -R[..., 0, 2], zero, R[..., 2, 2], -R[..., 1, 2], zero, zero, one], -1
+ ).reshape(-1, 3, 3)
tilt = Pz @ R.transpose(-1, -2)
if ndim == 0:
@@ -118,9 +117,9 @@ def distort_points(
if dist.shape[-1] not in [4, 5, 8, 12, 14]:
raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")
- # Adding zeros to obtain vector with 14 coeffs.
+ # Adding torch.zeros to obtain vector with 14 coeffs.
if dist.shape[-1] < 14:
- dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]])
+ dist = F.pad(dist, [0, 14 - dist.shape[-1]])
# Convert 2D points from pixels to normalized camera coordinates
new_cx: torch.Tensor = new_K[..., 0:1, 2] # princial point in x (Bx1)
@@ -158,7 +157,7 @@ def distort_points(
tilt = tilt_projection(dist[..., 12], dist[..., 13])
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
- points_untilt = stack([xd, yd, ones_like(xd)], -1) @ tilt.transpose(-2, -1)
+ points_untilt = torch.stack([xd, yd, torch.ones_like(xd)], -1) @ tilt.transpose(-2, -1)
xd = points_untilt[..., 0] / points_untilt[..., 2]
yd = points_untilt[..., 1] / points_untilt[..., 2]
@@ -171,4 +170,4 @@ def distort_points(
x = fx * xd + cx
y = fy * yd + cy
- return stack([x, y], -1)
+ return torch.stack([x, y], -1)
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 027f33177..c4bdc0bd2 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -20,7 +20,6 @@ from typing import Optional, Tuple
import torch
from torch.linalg import qr as linalg_qr
-from kornia.core import arange, ones_like, where, zeros
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_to_homogeneous, normalize_points_with_intrinsics
from kornia.geometry.linalg import transform_points
@@ -32,7 +31,7 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->
r"""Normalize points.
Args:
- points : Tensor containing the points to be normalized with shape :math:`(B, N, D)`.
+ points : torch.Tensor containing the points to be normalized with shape :math:`(B, N, D)`.
eps : Small value to avoid division by zero error.
Returns:
@@ -49,7 +48,7 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->
scale = torch.sqrt(D_float) / (scale + eps) # B
transform = eye_like(D_int + 1, points) # (B, D+1, D+1)
- idxs = arange(D_int, dtype=torch.int64, device=points.device)
+ idxs = torch.arange(D_int, dtype=torch.int64, device=points.device)
transform[:, idxs, idxs] = transform[:, idxs, idxs] * scale[:, None]
transform[:, idxs, D_int] = transform[:, idxs, D_int] + (-scale[:, None] * x_mean[:, 0, idxs])
@@ -67,8 +66,8 @@ def solve_pnp_dlt(
) -> torch.Tensor:
r"""Attempt to solve the Perspective-n-Point (PnP) problem using Direct Linear Transform (DLT).
- Given a batch (where batch size is :math:`B`) of :math:`N` 3D points
- (where :math:`N \geq 6`) in the world space, a batch of :math:`N`
+ Given a batch (torch.where batch size is :math:`B`) of :math:`N` 3D points
+ (torch.where :math:`N \geq 6`) in the world space, a batch of :math:`N`
corresponding 2D points in the image space and a batch of
intrinsic matrices, this function tries to estimate a batch of
world to camera transformation matrices.
@@ -86,18 +85,18 @@ def solve_pnp_dlt(
twisted cubic. However, this function does not check for this condition.
Args:
- world_points : A tensor with shape :math:`(B, N, 3)` representing
+ world_points : A torch.tensor with shape :math:`(B, N, 3)` representing
the points in the world space.
- img_points : A tensor with shape :math:`(B, N, 2)` representing
+ img_points : A torch.tensor with shape :math:`(B, N, 2)` representing
the points in the image space.
- intrinsics : A tensor with shape :math:`(B, 3, 3)` representing
+ intrinsics : A torch.tensor with shape :math:`(B, 3, 3)` representing
the intrinsic matrices.
- weights : A tensor with shape :math:`(B, N)` representing the
+ weights : A torch.tensor with shape :math:`(B, N)` representing the
weights for each point. If None, all points are considered to be equally important.
svd_eps : A small float value to avoid numerical precision issues.
Returns:
- A tensor with shape :math:`(B, 3, 4)` representing the estimated world to
+ A torch.tensor with shape :math:`(B, 3, 4)` representing the estimated world to
camera transformation matrices (also known as the extrinsic matrices).
Example:
@@ -182,7 +181,7 @@ def solve_pnp_dlt(
inv_img_transform_norm = torch.inverse(img_transform_norm)
# Setting up the system (the matrix A in Ax=0)
- system = zeros((B, 2 * N, 12), dtype=world_points.dtype, device=world_points.device)
+ system = torch.zeros((B, 2 * N, 12), dtype=world_points.dtype, device=world_points.device)
system[:, 0::2, 0:4] = world_points_norm_h
system[:, 1::2, 4:8] = world_points_norm_h
system[:, 0::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 0:1]
@@ -221,8 +220,8 @@ def solve_pnp_dlt(
# the all the rotation matrices are non-negative (since determinant
# of a rotation matrix should be 1).
det = torch.det(solution[:, :3, :3])
- ones = ones_like(det)
- sign_fix = where(det < 0, ones * -1, ones)
+ ones_tensor = torch.ones_like(det)
+ sign_fix = torch.where(det < 0, ones_tensor * -1, ones_tensor)
solution = solution * sign_fix[:, None, None]
# Then, we make sure that norm of the 0th columns of the rotation
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 8dc179488..65bd3cd32 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -20,8 +20,8 @@ from __future__ import annotations
from typing import Optional
import torch
+import torch.nn.functional as F
-from kornia.core import stack
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
@@ -79,9 +79,9 @@ def undistort_points(
if dist.shape[-1] not in [4, 5, 8, 12, 14]:
raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")
- # Adding zeros to obtain vector with 14 coeffs.
+ # Adding torch.zeros to obtain vector with 14 coeffs.
if dist.shape[-1] < 14:
- dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]])
+ dist = F.pad(dist, [0, 14 - dist.shape[-1]])
# Convert 2D points from pixels to normalized camera coordinates
cx: torch.Tensor = K[..., 0:1, 2] # princial point in x (Bx1)
@@ -98,7 +98,7 @@ def undistort_points(
inv_tilt = tilt_projection(dist[..., 12], dist[..., 13], True)
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
- x, y = transform_points(inv_tilt, stack([x, y], dim=-1)).unbind(-1)
+ x, y = transform_points(inv_tilt, torch.stack([x, y], dim=-1)).unbind(-1)
# Iteratively undistort points
x0, y0 = x, y
@@ -131,7 +131,7 @@ def undistort_points(
new_fy: torch.Tensor = new_K[..., 1:2, 1] # focal in y (Bx1)
x = new_fx * x + new_cx
y = new_fy * y + new_cy
- return stack([x, y], -1)
+ return torch.stack([x, y], -1)
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L287
diff --git a/kornia/geometry/camera/distortion_affine.py b/kornia/geometry/camera/distortion_affine.py
index d640719e9..7487680e7 100644
--- a/kornia/geometry/camera/distortion_affine.py
+++ b/kornia/geometry/camera/distortion_affine.py
@@ -15,15 +15,15 @@
# limitations under the License.
#
-"""Module containing the affine distortion model."""
+"""nn.Module containing the affine distortion model."""
# inspired by: https://github.com/farm-ng/sophus-rs/blob/main/src/sensor/affine.rs
-import kornia.core as ops
-from kornia.core import Tensor
+import torch
+
from kornia.core.check import KORNIA_CHECK_SHAPE
-def distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params: Tensor) -> Tensor:
+def distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor) -> torch.Tensor:
r"""Distort one or more points from the canonical z=1 plane into the camera frame.
.. math::
@@ -33,11 +33,11 @@ def distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params: T
\begin{bmatrix} c_x \\ c_y \end{bmatrix}
Args:
- projected_points_in_camera_z1_plane: Tensor representing the points to distort with shape (..., 2).
- params: Tensor representing the parameters of the affine distortion model with shape (..., 4).
+ projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the affine distortion model with shape (..., 4).
Returns:
- Tensor representing the distorted points with shape (..., 2).
+ torch.Tensor representing the distorted points with shape (..., 2).
Example:
>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 image
@@ -58,10 +58,10 @@ def distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params: T
u = fx * x + cx
v = fy * y + cy
- return ops.stack([u, v], dim=-1)
+ return torch.stack([u, v], dim=-1)
-def undistort_points_affine(distorted_points_in_camera: Tensor, params: Tensor) -> Tensor:
+def undistort_points_affine(distorted_points_in_camera: torch.Tensor, params: torch.Tensor) -> torch.Tensor:
r"""Undistort one or more points from the camera frame into the canonical z=1 plane.
.. math::
@@ -71,11 +71,11 @@ def undistort_points_affine(distorted_points_in_camera: Tensor, params: Tensor)
\begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}^{-1}
Args:
- distorted_points_in_camera: Tensor representing the points to undistort with shape (..., 2).
- params: Tensor representing the parameters of the affine distortion model with shape (..., 4).
+ distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the affine distortion model with shape (..., 4).
Returns:
- Tensor representing the undistorted points with shape (..., 2).
+ torch.Tensor representing the undistorted points with shape (..., 2).
Example:
>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 image
@@ -96,10 +96,10 @@ def undistort_points_affine(distorted_points_in_camera: Tensor, params: Tensor)
x = (u - cx) / fx
y = (v - cy) / fy
- return ops.stack([x, y], dim=-1)
+ return torch.stack([x, y], dim=-1)
-def dx_distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params: Tensor) -> Tensor:
+def dx_distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor) -> torch.Tensor:
r"""Compute the derivative of the x distortion with respect to the x coordinate.
.. math::
@@ -107,11 +107,12 @@ def dx_distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params
\begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}
Args:
- projected_points_in_camera_z1_plane: Tensor representing the points to distort with shape (..., 2).
- params: Tensor representing the parameters of the affine distortion model with shape (..., 4).
+ projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the affine distortion model with shape (..., 4).
Returns:
- Tensor representing the derivative of the x distortion with respect to the x coordinate with shape (..., 2).
+ torch.Tensor representing the derivative of the x distortion with respect to the x coordinate
+ with shape (..., 2).
Example:
>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 image
@@ -126,6 +127,6 @@ def dx_distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params
fx, fy = params[..., 0], params[..., 1]
- zeros = ops.zeros_like(fx)
+ zeros = torch.zeros_like(fx)
- return ops.stack([ops.stack([fx, zeros], dim=-1), ops.stack([zeros, fy], dim=-1)], dim=-2)
+ return torch.stack([torch.stack([fx, zeros], dim=-1), torch.stack([zeros, fy], dim=-1)], dim=-2)
diff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.py
index 4dbaaee79..e155cbe9b 100644
--- a/kornia/geometry/camera/distortion_kannala_brandt.py
+++ b/kornia/geometry/camera/distortion_kannala_brandt.py
@@ -19,18 +19,17 @@
import torch
-import kornia.core as ops
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.camera.distortion_affine import distort_points_affine
def _distort_points_kannala_brandt_impl(
- projected_points_in_camera_z1_plane: Tensor,
- params: Tensor,
- radius_sq: Tensor,
-) -> Tensor:
- # https://github.com/farm-ng/sophus-rs/blob/20f6cac68f17fe1ac41d0aa8a27489e2b886806f/src/sensor/kannala_brandt.rs#L51-L67
+ projected_points_in_camera_z1_plane: torch.Tensor,
+ params: torch.Tensor,
+ radius_sq: torch.Tensor,
+) -> torch.Tensor:
+ # https://github.com/farm-ng/sophus-rs/blob/20f6cac68f17fe1ac41d0aa8a27489e2b886806f/
+ # src/sensor/kannala_brandt.rs#L51-L67
x = projected_points_in_camera_z1_plane[..., 0]
y = projected_points_in_camera_z1_plane[..., 1]
@@ -44,7 +43,7 @@ def _distort_points_kannala_brandt_impl(
radius = radius_sq.sqrt()
radius_inverse = 1.0 / radius
- theta = radius.atan2(ops.ones_like(radius))
+ theta = radius.atan2(torch.ones_like(radius))
theta2 = theta**2
theta4 = theta2**2
theta6 = theta2 * theta4
@@ -57,18 +56,20 @@ def _distort_points_kannala_brandt_impl(
u = fx * scaling * x + cx
v = fy * scaling * y + cy
- return ops.stack([u, v], dim=-1)
+ return torch.stack([u, v], dim=-1)
-def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, params: Tensor) -> Tensor:
+def distort_points_kannala_brandt(
+ projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor
+) -> torch.Tensor:
r"""Distort points from the canonical z=1 plane into the camera frame using the Kannala-Brandt model.
Args:
- projected_points_in_camera_z1_plane: Tensor representing the points to distort with shape (..., 2).
- params: Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
+ projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
Returns:
- Tensor representing the distorted points with shape (..., 2).
+ torch.Tensor representing the distorted points with shape (..., 2).
Example:
>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 image
@@ -85,7 +86,7 @@ def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, p
radius_sq = x**2 + y**2
- distorted_points = ops.where(
+ distorted_points = torch.where(
radius_sq[..., None] > 1e-8,
_distort_points_kannala_brandt_impl(
projected_points_in_camera_z1_plane,
@@ -98,15 +99,15 @@ def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, p
return distorted_points
-def undistort_points_kannala_brandt(distorted_points_in_camera: Tensor, params: Tensor) -> Tensor:
+def undistort_points_kannala_brandt(distorted_points_in_camera: torch.Tensor, params: torch.Tensor) -> torch.Tensor:
r"""Undistort points from the camera frame into the canonical z=1 plane using the Kannala-Brandt model.
Args:
- distorted_points_in_camera: Tensor representing the points to undistort with shape (..., 2).
- params: Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
+ distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
Returns:
- Tensor representing the undistorted points with shape (..., 2).
+ torch.Tensor representing the undistorted points with shape (..., 2).
Example:
>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 image
@@ -163,7 +164,9 @@ def undistort_points_kannala_brandt(distorted_points_in_camera: Tensor, params:
return undistorted.to(device=device, dtype=out_dtype)
-def dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, params: Tensor) -> Tensor:
+def dx_distort_points_kannala_brandt(
+ projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor
+) -> torch.Tensor:
r"""Compute the derivative of the x distortion with respect to the x coordinate.
.. math::
@@ -171,11 +174,12 @@ def dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor
\begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}
Args:
- projected_points_in_camera_z1_plane: Tensor representing the points to distort with shape (..., 2).
- params: Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
+ projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).
+ params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).
Returns:
- Tensor representing the derivative of the x distortion with respect to the x coordinate with shape (..., 2).
+ torch.Tensor representing the derivative of the x distortion with respect to the x coordinate
+ with shape (..., 2).
Example:
>>> points = torch.tensor([1., 2.])
@@ -224,10 +228,10 @@ def dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor
c20 = c19 / c2.pow(3.0)
c21 = a * b * c19 * (-c13 * c2 + c15 * c17) / c3
- return ops.stack(
+ return torch.stack(
[
- ops.stack([c20 * fx * (-c0 * c16 + c0 * c18 + c14), c21 * fx], dim=-1),
- ops.stack([c21 * fy, c20 * fy * (-c1 * c16 + c1 * c18 + c14)], dim=-1),
+ torch.stack([c20 * fx * (-c0 * c16 + c0 * c18 + c14), c21 * fx], dim=-1),
+ torch.stack([c21 * fy, c20 * fy * (-c1 * c16 + c1 * c18 + c14)], dim=-1),
],
dim=-2,
)
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 4d8436f3b..2e5298993 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -19,7 +19,6 @@ from typing import Iterable, List, Union
import torch
-from kornia.core import Device, Tensor, eye, stack, zeros
from kornia.core.check import KORNIA_CHECK_SAME_DEVICE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import inverse_transformation, transform_points
@@ -30,12 +29,12 @@ class PinholeCamera:
r"""Class that represents a Pinhole Camera model.
Args:
- intrinsics: tensor with shape :math:`(B, 4, 4)`
+ intrinsics: torch.tensor with shape :math:`(B, 4, 4)`
containing the full 4x4 camera calibration matrix.
- extrinsics: tensor with shape :math:`(B, 4, 4)`
+ extrinsics: torch.tensor with shape :math:`(B, 4, 4)`
containing the full 4x4 rotation-translation matrix.
- height: tensor with shape :math:`(B)` containing the image height.
- width: tensor with shape :math:`(B)` containing the image width.
+ height: torch.tensor with shape :math:`(B)` containing the image height.
+ width: torch.tensor with shape :math:`(B)` containing the image width.
.. note::
We assume that the class attributes are in batch form in order to take
@@ -43,7 +42,9 @@ class PinholeCamera:
"""
- def __init__(self, intrinsics: Tensor, extrinsics: Tensor, height: Tensor, width: Tensor) -> None:
+ def __init__(
+ self, intrinsics: torch.Tensor, extrinsics: torch.Tensor, height: torch.Tensor, width: torch.Tensor
+ ) -> None:
# verify batch size and shapes
self._check_valid([intrinsics, extrinsics, height, width])
self._check_valid_params(intrinsics, "intrinsics")
@@ -52,19 +53,19 @@ class PinholeCamera:
self._check_valid_shape(width, "width")
self._check_consistent_device([intrinsics, extrinsics, height, width])
# set class attributes
- self.height: Tensor = height
- self.width: Tensor = width
- self._intrinsics: Tensor = intrinsics
- self._extrinsics: Tensor = extrinsics
+ self.height: torch.Tensor = height
+ self.width: torch.Tensor = width
+ self._intrinsics: torch.Tensor = intrinsics
+ self._extrinsics: torch.Tensor = extrinsics
@staticmethod
- def _check_valid(data_iter: Iterable[Tensor]) -> bool:
+ def _check_valid(data_iter: Iterable[torch.Tensor]) -> bool:
if not all(data.shape[0] for data in data_iter):
raise ValueError("Arguments shapes must match")
return True
@staticmethod
- def _check_valid_params(data: Tensor, data_name: str) -> bool:
+ def _check_valid_params(data: torch.Tensor, data_name: str) -> bool:
if len(data.shape) not in (3, 4) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?
raise ValueError(
f"Argument {data_name} shape must be in the following shape Bx4x4 or BxNx4x4. Got {data.shape}"
@@ -72,13 +73,13 @@ class PinholeCamera:
return True
@staticmethod
- def _check_valid_shape(data: Tensor, data_name: str) -> bool:
+ def _check_valid_shape(data: torch.Tensor, data_name: str) -> bool:
if not len(data.shape) == 1:
raise ValueError(f"Argument {data_name} shape must be in the following shape B. Got {data.shape}")
return True
@staticmethod
- def _check_consistent_device(data_iter: List[Tensor]) -> None:
+ def _check_consistent_device(data_iter: List[torch.Tensor]) -> None:
first = data_iter[0]
for data in data_iter:
KORNIA_CHECK_SAME_DEVICE(data, first)
@@ -87,17 +88,17 @@ class PinholeCamera:
r"""Return the device for camera buffers.
Returns:
- Device type
+ Union[str, torch.device, None] type
"""
return self._intrinsics.device
@property
- def intrinsics(self) -> Tensor:
+ def intrinsics(self) -> torch.Tensor:
r"""The full 4x4 intrinsics matrix.
Returns:
- tensor of shape :math:`(B, 4, 4)`.
+ torch.tensor of shape :math:`(B, 4, 4)`.
"""
if not self._check_valid_params(self._intrinsics, "intrinsics"):
@@ -105,11 +106,11 @@ class PinholeCamera:
return self._intrinsics
@property
- def extrinsics(self) -> Tensor:
+ def extrinsics(self) -> torch.Tensor:
r"""The full 4x4 extrinsics matrix.
Returns:
- tensor of shape :math:`(B, 4, 4)`.
+ torch.tensor of shape :math:`(B, 4, 4)`.
"""
if not self._check_valid_params(self._extrinsics, "extrinsics"):
@@ -127,155 +128,155 @@ class PinholeCamera:
return self.intrinsics.shape[0]
@property
- def fx(self) -> Tensor:
+ def fx(self) -> torch.Tensor:
r"""Return the focal length in the x-direction.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 0, 0]
@property
- def fy(self) -> Tensor:
+ def fy(self) -> torch.Tensor:
r"""Return the focal length in the y-direction.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 1, 1]
@property
- def cx(self) -> Tensor:
+ def cx(self) -> torch.Tensor:
r"""Return the x-coordinate of the principal point.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 0, 2]
@property
- def cy(self) -> Tensor:
+ def cy(self) -> torch.Tensor:
r"""Return the y-coordinate of the principal point.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 1, 2]
@property
- def tx(self) -> Tensor:
+ def tx(self) -> torch.Tensor:
r"""Return the x-coordinate of the translation vector.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 0, -1]
@tx.setter
- def tx(self, value: Union[Tensor, float]) -> "PinholeCamera":
+ def tx(self, value: Union[torch.Tensor, float]) -> "PinholeCamera":
r"""Set the x-coordinate of the translation vector with the given value."""
self.extrinsics[..., 0, -1] = value
return self
@property
- def ty(self) -> Tensor:
+ def ty(self) -> torch.Tensor:
r"""Return the y-coordinate of the translation vector.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 1, -1]
@ty.setter
- def ty(self, value: Union[Tensor, float]) -> "PinholeCamera":
+ def ty(self, value: Union[torch.Tensor, float]) -> "PinholeCamera":
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 1, -1] = value
return self
@property
- def tz(self) -> Tensor:
+ def tz(self) -> torch.Tensor:
r"""Returns the z-coordinate of the translation vector.
Returns:
- tensor of shape :math:`(B)`.
+ torch.tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 2, -1]
@tz.setter
- def tz(self, value: Union[Tensor, float]) -> "PinholeCamera":
+ def tz(self, value: Union[torch.Tensor, float]) -> "PinholeCamera":
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 2, -1] = value
return self
@property
- def rt_matrix(self) -> Tensor:
+ def rt_matrix(self) -> torch.Tensor:
r"""Return the 3x4 rotation-translation matrix.
Returns:
- tensor of shape :math:`(B, 3, 4)`.
+ torch.tensor of shape :math:`(B, 3, 4)`.
"""
return self.extrinsics[..., :3, :4]
@property
- def camera_matrix(self) -> Tensor:
+ def camera_matrix(self) -> torch.Tensor:
r"""Return the 3x3 camera matrix containing the intrinsics.
Returns:
- tensor of shape :math:`(B, 3, 3)`.
+ torch.tensor of shape :math:`(B, 3, 3)`.
"""
return self.intrinsics[..., :3, :3]
@property
- def rotation_matrix(self) -> Tensor:
+ def rotation_matrix(self) -> torch.Tensor:
r"""Return the 3x3 rotation matrix from the extrinsics.
Returns:
- tensor of shape :math:`(B, 3, 3)`.
+ torch.tensor of shape :math:`(B, 3, 3)`.
"""
return self.extrinsics[..., :3, :3]
@property
- def translation_vector(self) -> Tensor:
+ def translation_vector(self) -> torch.Tensor:
r"""Return the translation vector from the extrinsics.
Returns:
- tensor of shape :math:`(B, 3, 1)`.
+ torch.tensor of shape :math:`(B, 3, 1)`.
"""
return self.extrinsics[..., :3, -1:]
def clone(self) -> "PinholeCamera":
r"""Return a deep copy of the current object instance."""
- height: Tensor = self.height.clone()
- width: Tensor = self.width.clone()
- intrinsics: Tensor = self.intrinsics.clone()
- extrinsics: Tensor = self.extrinsics.clone()
+ height: torch.Tensor = self.height.clone()
+ width: torch.Tensor = self.width.clone()
+ intrinsics: torch.Tensor = self.intrinsics.clone()
+ extrinsics: torch.Tensor = self.extrinsics.clone()
return PinholeCamera(intrinsics, extrinsics, height, width)
- def intrinsics_inverse(self) -> Tensor:
+ def intrinsics_inverse(self) -> torch.Tensor:
r"""Return the inverse of the 4x4 instrisics matrix.
Returns:
- tensor of shape :math:`(B, 4, 4)`.
+ torch.tensor of shape :math:`(B, 4, 4)`.
"""
return self.intrinsics.inverse()
- def scale(self, scale_factor: Tensor) -> "PinholeCamera":
+ def scale(self, scale_factor: torch.Tensor) -> "PinholeCamera":
r"""Scale the pinhole model.
Args:
- scale_factor: a tensor with the scale factor. It has
+ scale_factor: a torch.tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
:math:`(B)` or :math:`(1)`.
@@ -284,21 +285,21 @@ class PinholeCamera:
"""
# scale the intrinsic parameters
- intrinsics: Tensor = self.intrinsics.clone()
+ intrinsics: torch.Tensor = self.intrinsics.clone()
intrinsics[..., 0, 0] *= scale_factor
intrinsics[..., 1, 1] *= scale_factor
intrinsics[..., 0, 2] *= scale_factor
intrinsics[..., 1, 2] *= scale_factor
# scale the image height/width
- height: Tensor = scale_factor * self.height.clone()
- width: Tensor = scale_factor * self.width.clone()
+ height: torch.Tensor = scale_factor * self.height.clone()
+ width: torch.Tensor = scale_factor * self.width.clone()
return PinholeCamera(intrinsics, self.extrinsics, height, width)
- def scale_(self, scale_factor: Union[float, Tensor]) -> "PinholeCamera":
+ def scale_(self, scale_factor: Union[float, torch.Tensor]) -> "PinholeCamera":
r"""Scale the pinhole model in-place.
Args:
- scale_factor: a tensor with the scale factor. It has
+ scale_factor: a torch.tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
:math:`(B)` or :math:`(1)`.
@@ -316,15 +317,15 @@ class PinholeCamera:
self.width *= scale_factor
return self
- def project(self, point_3d: Tensor) -> Tensor:
+ def project(self, point_3d: torch.Tensor) -> torch.Tensor:
r"""Project a 3d point in world coordinates onto the 2d camera plane.
Args:
- point_3d: tensor containing the 3d points to be projected
- to the camera plane. The shape of the tensor can be :math:`(*, 3)`.
+ point_3d: torch.tensor containing the 3d points to be projected
+ to the camera plane. The shape of the torch.tensor can be :math:`(*, 3)`.
Returns:
- tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.
+ torch.tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.
Example:
>>> _ = torch.manual_seed(0)
@@ -341,22 +342,22 @@ class PinholeCamera:
P = self.intrinsics @ self.extrinsics
return convert_points_from_homogeneous(transform_points(P, point_3d))
- def unproject(self, point_2d: Tensor, depth: Tensor) -> Tensor:
+ def unproject(self, point_2d: torch.Tensor, depth: torch.Tensor) -> torch.Tensor:
r"""Unproject a 2d point in 3d.
Transform coordinates in the pixel frame to the world frame.
Args:
- point_2d: tensor containing the 2d to be projected to
- world coordinates. The shape of the tensor can be :math:`(*, 2)`.
- depth: tensor containing the depth value of each 2d
- points. The tensor shape must be equal to point2d :math:`(*, 1)`.
- normalize: whether to normalize the pointcloud. This
+ point_2d: torch.tensor containing the 2d to be projected to
+ world coordinates. The shape of the torch.tensor can be :math:`(*, 2)`.
+ depth: torch.tensor containing the depth value of each 2d
+ points. The torch.tensor shape must be equal to point2d :math:`(*, 1)`.
+ normalize: whether to F.normalize the pointcloud. This
must be set to `True` when the depth is represented as the Euclidean
ray length from the camera position.
Returns:
- tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.
+ torch.tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.
Example:
>>> _ = torch.manual_seed(0)
@@ -379,21 +380,21 @@ class PinholeCamera:
@classmethod
def from_parameters(
self,
- fx: Tensor,
- fy: Tensor,
- cx: Tensor,
- cy: Tensor,
+ fx: torch.Tensor,
+ fy: torch.Tensor,
+ cx: torch.Tensor,
+ cy: torch.Tensor,
height: int,
width: int,
- tx: Tensor,
- ty: Tensor,
- tz: Tensor,
+ tx: torch.Tensor,
+ ty: torch.Tensor,
+ tz: torch.Tensor,
batch_size: int,
- device: Device,
+ device: Union[str, torch.device, None],
dtype: torch.dtype,
) -> "PinholeCamera":
# create the camera matrix
- intrinsics = zeros(batch_size, 4, 4, device=device, dtype=dtype)
+ intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
intrinsics[..., 1, 1] += fy
intrinsics[..., 0, 2] += cx
@@ -401,14 +402,14 @@ class PinholeCamera:
intrinsics[..., 2, 2] += 1.0
intrinsics[..., 3, 3] += 1.0
# create the pose matrix
- extrinsics = eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1)
+ extrinsics = torch.eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1)
extrinsics[..., 0, -1] += tx
extrinsics[..., 1, -1] += ty
extrinsics[..., 2, -1] += tz
# create image hegith and width
- height_tmp = zeros(batch_size, device=device, dtype=dtype)
+ height_tmp = torch.zeros(batch_size, device=device, dtype=dtype)
height_tmp[..., 0] += height
- width_tmp = zeros(batch_size, device=device, dtype=dtype)
+ width_tmp = torch.zeros(batch_size, device=device, dtype=dtype)
width_tmp[..., 0] += width
return self(intrinsics, extrinsics, height_tmp, width_tmp)
@@ -420,9 +421,9 @@ class PinholeCamerasList(PinholeCamera):
it will keep the same class properties but with an extra dimension.
.. note::
- The underlying data tensor will be stacked in the first dimension.
- That's it, given a list of two camera instances, the intrinsics tensor
- will have a shape :math:`(B, N, 4, 4)` where :math:`B` is the batch
+ The underlying data torch.tensor will be stacked in the first dimension.
+ That's it, given a list of two camera instances, the intrinsics torch.tensor
+ will have a shape :math:`(B, N, 4, 4)` torch.where :math:`B` is the batch
size and :math:`N` is the numbers of cameras (in this case two).
Args:
@@ -446,11 +447,11 @@ class PinholeCamerasList(PinholeCamera):
width.append(pinhole.width)
intrinsics.append(pinhole.intrinsics)
extrinsics.append(pinhole.extrinsics)
- # concatenate and set members. We will assume BxNx4x4
- self.height: Tensor = stack(height, dim=1)
- self.width: Tensor = stack(width, dim=1)
- self._intrinsics: Tensor = stack(intrinsics, dim=1)
- self._extrinsics: Tensor = stack(extrinsics, dim=1)
+ # torch.cat and set members. We will assume BxNx4x4
+ self.height: torch.Tensor = torch.stack(height, dim=1)
+ self.width: torch.Tensor = torch.stack(width, dim=1)
+ self._intrinsics: torch.Tensor = torch.stack(intrinsics, dim=1)
+ self._extrinsics: torch.Tensor = torch.stack(extrinsics, dim=1)
return self
@property
@@ -463,14 +464,14 @@ class PinholeCamerasList(PinholeCamera):
def get_pinhole(self, idx: int) -> PinholeCamera:
r"""Return a PinholeCamera object with parameters such as Bx4x4."""
- height: Tensor = self.height[..., idx]
- width: Tensor = self.width[..., idx]
- intrinsics: Tensor = self.intrinsics[:, idx]
- extrinsics: Tensor = self.extrinsics[:, idx]
+ height: torch.Tensor = self.height[..., idx]
+ width: torch.Tensor = self.width[..., idx]
+ intrinsics: torch.Tensor = self.intrinsics[:, idx]
+ extrinsics: torch.Tensor = self.extrinsics[:, idx]
return PinholeCamera(intrinsics, extrinsics, height, width)
-def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
+def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
r"""Return the pinhole matrix from a pinhole model.
.. note::
@@ -478,11 +479,11 @@ def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
:attr:`kornia.PinholeCamera.camera_matrix`.
Args:
- pinholes: tensor of pinhole models.
+ pinholes: torch.tensor of pinhole models.
eps: epsilon for numerical stability.
Returns:
- tensor of pinhole matrices.
+ torch.tensor of pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
@@ -506,7 +507,7 @@ def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
# unpack pinhole values
fx, fy, cx, cy = torch.chunk(pinholes[..., :4], 4, dim=1) # Nx1
# create output container
- k = eye(4, device=pinholes.device, dtype=pinholes.dtype) + eps
+ k = torch.eye(4, device=pinholes.device, dtype=pinholes.dtype) + eps
k = k.view(1, 4, 4).repeat(pinholes.shape[0], 1, 1) # Nx4x4
# fill output with pinhole values
k[..., 0, 0:1] = fx
@@ -516,7 +517,7 @@ def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
return k
-def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
+def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
r"""Return the inverted pinhole matrix from a pinhole model.
.. note::
@@ -524,11 +525,11 @@ def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
:attr:`kornia.PinholeCamera.intrinsics_inverse()`.
Args:
- pinhole: tensor with pinhole models.
+ pinhole: torch.tensor with pinhole models.
eps: epsilon for numerical stability.
Returns:
- tensor of inverted pinhole matrices.
+ torch.tensor of inverted pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
@@ -552,7 +553,7 @@ def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
# unpack pinhole values
fx, fy, cx, cy = torch.chunk(pinhole[..., :4], 4, dim=1) # Nx1
# create output container
- k = eye(4, device=pinhole.device, dtype=pinhole.dtype)
+ k = torch.eye(4, device=pinhole.device, dtype=pinhole.dtype)
k = k.view(1, 4, 4).repeat(pinhole.shape[0], 1, 1) # Nx4x4
# fill output with inverse values
k[..., 0, 0:1] = 1.0 / (fx + eps)
@@ -562,7 +563,7 @@ def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
return k
-def scale_pinhole(pinholes: Tensor, scale: Tensor) -> Tensor:
+def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
r"""Scale the pinhole matrix for each pinhole model.
.. note::
@@ -570,11 +571,11 @@ def scale_pinhole(pinholes: Tensor, scale: Tensor) -> Tensor:
:attr:`kornia.PinholeCamera.scale()`.
Args:
- pinholes: tensor with the pinhole model.
- scale: tensor of scales.
+ pinholes: torch.tensor with the pinhole model.
+ scale: torch.tensor of scales.
Returns:
- tensor of scaled pinholes.
+ torch.tensor of scaled pinholes.
Shape:
- Input: :math:`(N, 12)` and :math:`(N, 1)`
@@ -601,20 +602,20 @@ def scale_pinhole(pinholes: Tensor, scale: Tensor) -> Tensor:
return pinholes_scaled
-def get_optical_pose_base(pinholes: Tensor) -> Tensor:
+def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
"""Compute extrinsic transformation matrices for pinholes.
Args:
- pinholes: tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
+ pinholes: torch.tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
of size (N, 12).
Returns:
- tensor of extrinsic transformation matrices of size (N, 4, 4).
+ torch.tensor of extrinsic transformation matrices of size (N, 4, 4).
"""
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
- # TODO: where is rtvec_to_pose?
+ # TODO: torch.where is rtvec_to_pose?
raise NotImplementedError
# TODO: We have rtvec_to_pose in torchgeometry
# https://github.com/whh14/torchgeometry/blob/master/torchgeometry/conversions.py#L240
@@ -623,7 +624,7 @@ def get_optical_pose_base(pinholes: Tensor) -> Tensor:
# return rtvec_to_pose(optical_pose_parent) type: ignore
-def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
+def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> torch.Tensor:
r"""Homography from reference to ith pinhole.
.. note::
@@ -633,7 +634,7 @@ def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
pinhole = (f_x, f_y, c_x, c_y, height, width,
r_x, r_y, r_z, t_x, t_y, t_z)
- where:
+ torch.where:
:math:`(r_x, r_y, r_z)` is the rotation vector in angle-axis
convention.
@@ -644,8 +645,8 @@ def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}
Args:
- pinhole_i: tensor with pinhole model for ith frame.
- pinhole_ref: tensor with pinhole model for reference frame.
+ pinhole_i: torch.tensor with pinhole model for ith frame.
+ pinhole_ref: torch.tensor with pinhole model for reference frame.
Returns:
tensors that convert depth points (u, v, d) from pinhole_ref to pinhole_i.
@@ -675,7 +676,7 @@ def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26
-def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Tensor:
+def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: torch.Tensor) -> torch.Tensor:
r"""Transform coordinates in the pixel frame to the camera frame.
Args:
@@ -684,7 +685,7 @@ def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Te
pixel_coords: the grid with (u, v, 1) pixel coordinates. Shape must be BxHxWx3.
Returns:
- tensor of shape BxHxWx3 with (x, y, z) cam coordinates.
+ torch.tensor of shape BxHxWx3 with (x, y, z) cam coordinates.
"""
if not len(depth.shape) == 4 and depth.shape[1] == 1:
@@ -693,7 +694,7 @@ def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Te
raise ValueError(f"Input intrinsics_inv has to be in the shape of Bx4x4. Got {intrinsics_inv.shape}")
if not len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3:
raise ValueError(f"Input pixel_coords has to be in the shape of BxHxWx3. Got {intrinsics_inv.shape}")
- cam_coords: Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
+ cam_coords: torch.Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
@@ -701,7 +702,7 @@ def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Te
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43
-def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12) -> Tensor:
+def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Transform coordinates in the camera frame to the pixel frame.
Args:
@@ -711,7 +712,7 @@ def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12)
eps: small value to avoid division by zero error.
Returns:
- tensor of shape BxHxWx2 with (u, v) pixel coordinates.
+ torch.tensor of shape BxHxWx2 with (u, v) pixel coordinates.
"""
if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
@@ -719,17 +720,17 @@ def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12)
if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):
raise ValueError(f"Input dst_proj_src has to be in the shape of Bx4x4. Got {dst_proj_src.shape}")
# apply projection matrix to points
- point_coords: Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
- x_coord: Tensor = point_coords[..., 0]
- y_coord: Tensor = point_coords[..., 1]
- z_coord: Tensor = point_coords[..., 2]
+ point_coords: torch.Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
+ x_coord: torch.Tensor = point_coords[..., 0]
+ y_coord: torch.Tensor = point_coords[..., 1]
+ z_coord: torch.Tensor = point_coords[..., 2]
# compute pixel coordinates
- u_coord: Tensor = x_coord / (z_coord + eps)
- v_coord: Tensor = y_coord / (z_coord + eps)
+ u_coord: torch.Tensor = x_coord / (z_coord + eps)
+ v_coord: torch.Tensor = y_coord / (z_coord + eps)
- # stack and return the coordinates, that's the actual flow
- pixel_coords_dst: Tensor = stack([u_coord, v_coord], dim=-1)
+ # torch.stack and return the coordinates, that's the actual flow
+ pixel_coords_dst: torch.Tensor = torch.stack([u_coord, v_coord], dim=-1)
return pixel_coords_dst # BxHxWx2
@@ -738,10 +739,10 @@ def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12)
r"""Create an object that returns the pinhole matrix from a pinhole model
Args:
- pinholes (Tensor): tensor of pinhole models.
+ pinholes (torch.Tensor): torch.tensor of pinhole models.
Returns:
- Tensor: tensor of pinhole matrices.
+ torch.Tensor: torch.tensor of pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
@@ -764,10 +765,10 @@ class InversePinholeMatrix(nn.Module):
r"""Return and object that inverts a pinhole matrix from a pinhole model
Args:
- pinholes (Tensor): tensor with pinhole models.
+ pinholes (torch.Tensor): torch.tensor with pinhole models.
Returns:
- Tensor: tensor of inverted pinhole matrices.
+ torch.Tensor: torch.tensor of inverted pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
diff --git a/kornia/geometry/camera/projection_orthographic.py b/kornia/geometry/camera/projection_orthographic.py
index 370ac58c9..1551d3533 100644
--- a/kornia/geometry/camera/projection_orthographic.py
+++ b/kornia/geometry/camera/projection_orthographic.py
@@ -15,15 +15,15 @@
# limitations under the License.
#
-"""Module containing functions for orthographic projection."""
+"""nn.Module containing functions for orthographic projection."""
# inspired by: https://github.com/farm-ng/sophus-rs/blob/main/src/sensor/ortho_camera.rs
-import kornia.core as ops
-from kornia.core import Tensor
+import torch
+
from kornia.core.check import KORNIA_CHECK_SHAPE
-def project_points_orthographic(points_in_camera: Tensor) -> Tensor:
+def project_points_orthographic(points_in_camera: torch.Tensor) -> torch.Tensor:
r"""Project points from the camera frame into the canonical z=1 plane through orthographic projection.
.. math::
@@ -32,10 +32,10 @@ def project_points_orthographic(points_in_camera: Tensor) -> Tensor:
Args:
- points_in_camera: Tensor representing the points to project.
+ points_in_camera: torch.Tensor representing the points to project.
Returns:
- Tensor representing the projected points.
+ torch.Tensor representing the projected points.
Example:
>>> points = torch.tensor([1., 2., 3.])
@@ -47,7 +47,7 @@ def project_points_orthographic(points_in_camera: Tensor) -> Tensor:
return points_in_camera[..., :2]
-def unproject_points_orthographic(points_in_camera: Tensor, extension: Tensor) -> Tensor:
+def unproject_points_orthographic(points_in_camera: torch.Tensor, extension: torch.Tensor) -> torch.Tensor:
r"""Unproject one or more points from the canonical z=1 plane into the camera frame.
.. math::
@@ -55,11 +55,11 @@ def unproject_points_orthographic(points_in_camera: Tensor, extension: Tensor) -
\begin{bmatrix} u \\ v \\ w \end{bmatrix}
Args:
- points_in_camera: Tensor representing the points to unproject with shape (..., 2).
- extension: Tensor representing the extension of the points to unproject with shape (..., 1).
+ points_in_camera: torch.Tensor representing the points to unproject with shape (..., 2).
+ extension: torch.Tensor representing the extension of the points to unproject with shape (..., 1).
Returns:
- Tensor representing the unprojected points with shape (..., 3).
+ torch.Tensor representing the unprojected points with shape (..., 3).
Example:
>>> points = torch.tensor([1., 2.])
@@ -73,20 +73,20 @@ def unproject_points_orthographic(points_in_camera: Tensor, extension: Tensor) -
if len(points_in_camera.shape) != len(extension.shape):
extension = extension[..., None]
- return ops.concatenate([points_in_camera, extension], dim=-1)
+ return torch.cat([points_in_camera, extension], dim=-1)
-def dx_project_points_orthographic(points_in_camera: Tensor) -> Tensor:
+def dx_project_points_orthographic(points_in_camera: torch.Tensor) -> torch.Tensor:
r"""Compute the derivative of the x projection with respect to the x coordinate.
.. math::
\frac{\partial u}{\partial x} = 1
Args:
- points_in_camera: Tensor representing the points to project.
+ points_in_camera: torch.Tensor representing the points to project.
Returns:
- Tensor representing the derivative of the x projection with respect to the x coordinate.
+ torch.Tensor representing the derivative of the x projection with respect to the x coordinate.
Example:
>>> points = torch.tensor([1., 2., 3.])
@@ -95,4 +95,4 @@ def dx_project_points_orthographic(points_in_camera: Tensor) -> Tensor:
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "3"])
- return ops.ones_like(points_in_camera[..., 0:1])
+ return torch.ones_like(points_in_camera[..., 0:1])
diff --git a/kornia/geometry/camera/projection_z1.py b/kornia/geometry/camera/projection_z1.py
index 3f56fb239..06c0ad377 100644
--- a/kornia/geometry/camera/projection_z1.py
+++ b/kornia/geometry/camera/projection_z1.py
@@ -15,19 +15,19 @@
# limitations under the License.
#
-"""Module for the projection of points in the canonical z=1 plane."""
+"""nn.Module for the projection of points in the canonical z=1 plane."""
# inspired by: https://github.com/farm-ng/sophus-rs/blob/main/src/sensor/perspective_camera.rs
from __future__ import annotations
from typing import Optional
-import kornia.core as ops
-from kornia.core import Tensor
+import torch
+
from kornia.core.check import KORNIA_CHECK_SHAPE
-def project_points_z1(points_in_camera: Tensor) -> Tensor:
+def project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor:
r"""Project one or more points from the camera frame into the canonical z=1 plane through perspective division.
.. math::
@@ -42,10 +42,10 @@ def project_points_z1(points_in_camera: Tensor) -> Tensor:
points will be behind the camera and causing numerical issues for z == 0.
Args:
- points_in_camera: Tensor representing the points to project with shape (..., 3).
+ points_in_camera: torch.Tensor representing the points to project with shape (..., 3).
Returns:
- Tensor representing the projected points with shape (..., 2).
+ torch.Tensor representing the projected points with shape (..., 2).
Example:
>>> points = torch.tensor([1., 2., 3.])
@@ -57,7 +57,9 @@ def project_points_z1(points_in_camera: Tensor) -> Tensor:
return points_in_camera[..., :2] / points_in_camera[..., 2:3]
-def unproject_points_z1(points_in_cam_canonical: Tensor, extension: Optional[Tensor] = None) -> Tensor:
+def unproject_points_z1(
+ points_in_cam_canonical: torch.Tensor, extension: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Unproject one or more points from the canonical z=1 plane into the camera frame.
.. math::
@@ -65,11 +67,11 @@ def unproject_points_z1(points_in_cam_canonical: Tensor, extension: Optional[Ten
\begin{bmatrix} u \\ v \end{bmatrix} \cdot w
Args:
- points_in_cam_canonical: Tensor representing the points to unproject with shape (..., 2).
- extension: Tensor representing the extension (depth) of the points to unproject with shape (..., 1).
+ points_in_cam_canonical: torch.Tensor representing the points to unproject with shape (..., 2).
+ extension: torch.Tensor representing the extension (depth) of the points to unproject with shape (..., 1).
Returns:
- Tensor representing the unprojected points with shape (..., 3).
+ torch.Tensor representing the unprojected points with shape (..., 3).
Example:
>>> points = torch.tensor([1., 2.])
@@ -81,7 +83,7 @@ def unproject_points_z1(points_in_cam_canonical: Tensor, extension: Optional[Ten
KORNIA_CHECK_SHAPE(points_in_cam_canonical, ["*", "2"])
if extension is None:
- extension = ops.ones(
+ extension = torch.ones(
points_in_cam_canonical.shape[:-1] + (1,),
device=points_in_cam_canonical.device,
dtype=points_in_cam_canonical.dtype,
@@ -89,10 +91,10 @@ def unproject_points_z1(points_in_cam_canonical: Tensor, extension: Optional[Ten
elif extension.shape[0] > 1:
extension = extension[..., None] # (..., 1)
- return ops.concatenate([points_in_cam_canonical * extension, extension], dim=-1)
+ return torch.cat([points_in_cam_canonical * extension, extension], dim=-1)
-def dx_project_points_z1(points_in_camera: Tensor) -> Tensor:
+def dx_project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor:
r"""Compute the derivative of the x projection with respect to the x coordinate.
Returns point derivative of inverse depth point projection with respect to the x coordinate.
@@ -110,10 +112,11 @@ def dx_project_points_z1(points_in_camera: Tensor) -> Tensor:
points will be behind the camera and causing numerical issues for z == 0.
Args:
- points_in_camera: Tensor representing the points to project with shape (..., 3).
+ points_in_camera: torch.Tensor representing the points to project with shape (..., 3).
Returns:
- Tensor representing the derivative of the x projection with respect to the x coordinate with shape (..., 2, 3).
+ torch.Tensor representing the derivative of the x projection with respect to the x coordinate
+ with shape (..., 2, 3).
Example:
>>> points = torch.tensor([1., 2., 3.])
@@ -130,11 +133,11 @@ def dx_project_points_z1(points_in_camera: Tensor) -> Tensor:
z_inv = 1.0 / z
z_sq = z_inv * z_inv
- zeros = ops.zeros_like(z_inv)
- return ops.stack(
+ zeros = torch.zeros_like(z_inv)
+ return torch.stack(
[
- ops.stack([z_inv, zeros, -x * z_sq], dim=-1),
- ops.stack([zeros, z_inv, -y * z_sq], dim=-1),
+ torch.stack([z_inv, zeros, -x * z_sq], dim=-1),
+ torch.stack([zeros, z_inv, -y * z_sq], dim=-1),
],
dim=-2,
)
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index e2a859a66..5c9cbcf47 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -19,7 +19,6 @@ from typing import Any
import torch
-from kornia.core import Tensor, stack, zeros
from kornia.geometry.linalg import transform_points
from kornia.utils.grid import create_meshgrid
@@ -47,7 +46,7 @@ class StereoException(Exception):
class StereoCamera:
- def __init__(self, rectified_left_camera: Tensor, rectified_right_camera: Tensor) -> None:
+ def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor) -> None:
r"""Class representing a horizontal stereo camera setup.
Args:
@@ -58,8 +57,8 @@ class StereoCamera:
"""
self._check_stereo_camera(rectified_left_camera, rectified_right_camera)
- self.rectified_left_camera: Tensor = rectified_left_camera
- self.rectified_right_camera: Tensor = rectified_right_camera
+ self.rectified_left_camera: torch.Tensor = rectified_left_camera
+ self.rectified_right_camera: torch.Tensor = rectified_right_camera
self.device = self.rectified_left_camera.device
self.dtype = self.rectified_left_camera.dtype
@@ -67,7 +66,7 @@ class StereoCamera:
self._Q_matrix = self._init_Q_matrix()
@staticmethod
- def _check_stereo_camera(rectified_left_camera: Tensor, rectified_right_camera: Tensor) -> None:
+ def _check_stereo_camera(rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor) -> None:
r"""Ensure user specified correct camera matrices.
Args:
@@ -138,79 +137,79 @@ class StereoCamera:
return self.rectified_left_camera.shape[0]
@property
- def fx(self) -> Tensor:
+ def fx(self) -> torch.Tensor:
r"""Return the focal length in the x-direction.
Note that the focal lengths of the rectified left and right
camera are assumed to be equal.
Returns:
- tensor of shape :math:`(B)`
+ torch.tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 0, 0]
@property
- def fy(self) -> Tensor:
+ def fy(self) -> torch.Tensor:
r"""Returns the focal length in the y-direction.
Note that the focal lengths of the rectified left and right
camera are assumed to be equal.
Returns:
- tensor of shape :math:`(B)`
+ torch.tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 1, 1]
@property
- def cx_left(self) -> Tensor:
+ def cx_left(self) -> torch.Tensor:
r"""Return the x-coordinate of the principal point for the left camera.
Returns:
- tensor of shape :math:`(B)`
+ torch.tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 0, 2]
@property
- def cx_right(self) -> Tensor:
+ def cx_right(self) -> torch.Tensor:
r"""Return the x-coordinate of the principal point for the right camera.
Returns:
- tensor of shape :math:`(B)`
+ torch.tensor of shape :math:`(B)`
"""
return self.rectified_right_camera[..., 0, 2]
@property
- def cy(self) -> Tensor:
+ def cy(self) -> torch.Tensor:
r"""Return the y-coordinate of the principal point.
Note that the y-coordinate of the principal points
is assumed to be equal for the left and right camera.
Returns:
- tensor of shape :math:`(B)`
+ torch.tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 1, 2]
@property
- def tx(self) -> Tensor:
+ def tx(self) -> torch.Tensor:
r"""The horizontal baseline between the two cameras.
Returns:
- Tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return -self.rectified_right_camera[..., 0, 3] / self.fx
@property
- def Q(self) -> Tensor:
+ def Q(self) -> torch.Tensor:
r"""The Q matrix of the horizontal stereo setup.
- This matrix is used for reprojecting a disparity tensor to
+ This matrix is used for reprojecting a disparity torch.tensor to
the corresponding point cloud. Note that this is in a general form that allows different focal
lengths in the x and y direction.
@@ -220,15 +219,15 @@ class StereoCamera:
"""
return self._Q_matrix
- def _init_Q_matrix(self) -> Tensor:
+ def _init_Q_matrix(self) -> torch.Tensor:
r"""Initialize the Q matrix of the horizontal stereo setup. See the Q property.
Returns:
The Q matrix of shape :math:`(B, 4, 4)`.
"""
- Q = zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
- baseline: Tensor = -self.tx
+ Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
+ baseline: torch.Tensor = -self.tx
Q[:, 0, 0] = self.fy * baseline
Q[:, 0, 3] = -self.fy * self.cx_left * baseline
Q[:, 1, 1] = self.fx * baseline
@@ -238,11 +237,11 @@ class StereoCamera:
Q[:, 3, 3] = self.fy * (self.cx_left - self.cx_right) # NOTE: This is usually zero.
return Q
- def reproject_disparity_to_3D(self, disparity_tensor: Tensor) -> Tensor:
- r"""Reproject the disparity tensor to a 3D point cloud.
+ def reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:
+ r"""Reproject the disparity torch.tensor to a 3D point cloud.
Args:
- disparity_tensor: Disparity tensor of shape :math:`(B, 1, H, W)`.
+ disparity_tensor: Disparity torch.tensor of shape :math:`(B, 1, H, W)`.
Returns:
The 3D point cloud of shape :math:`(B, H, W, 3)`
@@ -251,16 +250,16 @@ class StereoCamera:
return reproject_disparity_to_3D(disparity_tensor, self.Q)
-def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
- r"""Ensure correct user provided correct disparity tensor.
+def _check_disparity_tensor(disparity_tensor: torch.Tensor) -> None:
+ r"""Ensure correct user provided correct disparity torch.tensor.
Args:
- disparity_tensor: The disparity tensor of shape :math:`(B, 1, H, W)`.
+ disparity_tensor: The disparity torch.tensor of shape :math:`(B, 1, H, W)`.
"""
- if not isinstance(disparity_tensor, Tensor):
+ if not isinstance(disparity_tensor, torch.Tensor):
raise StereoException(
- f"Expected 'disparity_tensor' to be an instance of Tensor but got {type(disparity_tensor)}."
+ f"Expected 'disparity_tensor' to be an instance of torch.Tensor but got {type(disparity_tensor)}."
)
if len(disparity_tensor.shape) != 4:
@@ -279,15 +278,15 @@ def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
)
-def _check_Q_matrix(Q_matrix: Tensor) -> None:
+def _check_Q_matrix(Q_matrix: torch.Tensor) -> None:
r"""Ensure Q matrix is of correct form.
Args:
Q_matrix: The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`
"""
- if not isinstance(Q_matrix, Tensor):
- raise StereoException(f"Expected 'Q_matrix' to be an instance of Tensor but got {type(Q_matrix)}.")
+ if not isinstance(Q_matrix, torch.Tensor):
+ raise StereoException(f"Expected 'Q_matrix' to be an instance of torch.Tensor but got {type(Q_matrix)}.")
if not len(Q_matrix.shape) == 3:
raise StereoException(f"Expected 'Q_matrix' to have 3 dimensions. Got {Q_matrix.shape}")
@@ -301,12 +300,12 @@ def _check_Q_matrix(Q_matrix: Tensor) -> None:
)
-def reproject_disparity_to_3D(disparity_tensor: Tensor, Q_matrix: Tensor) -> Tensor:
- r"""Reproject the disparity tensor to a 3D point cloud.
+def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:
+ r"""Reproject the disparity torch.tensor to a 3D point cloud.
Args:
- disparity_tensor: Disparity tensor of shape :math:`(B, H, W, 1)`.
- Q_matrix: Tensor of Q matrices of shapes :math:`(B, 4, 4)`.
+ disparity_tensor: Disparity torch.tensor of shape :math:`(B, H, W, 1)`.
+ Q_matrix: torch.Tensor of Q matrices of shapes :math:`(B, 4, 4)`.
Returns:
The 3D point cloud of shape :math:`(B, H, W, 3)`
@@ -323,7 +322,7 @@ def reproject_disparity_to_3D(disparity_tensor: Tensor, Q_matrix: Tensor) -> Ten
uv = uv.expand(batch_size, -1, -1, -1)
v, u = torch.unbind(uv, dim=-1)
v, u = torch.unsqueeze(v, -1), torch.unsqueeze(u, -1)
- uvd = stack((u, v, disparity_tensor), 1).reshape(batch_size, 3, -1).permute(0, 2, 1)
+ uvd = torch.stack((u, v, disparity_tensor), 1).reshape(batch_size, 3, -1).permute(0, 2, 1)
points = transform_points(Q_matrix, uvd).reshape(batch_size, rows, cols, 3)
# Final check that everything went well.
diff --git a/kornia/geometry/camera/utils.py b/kornia/geometry/camera/utils.py
index 81006595d..87ce493f5 100644
--- a/kornia/geometry/camera/utils.py
+++ b/kornia/geometry/camera/utils.py
@@ -18,21 +18,21 @@
from __future__ import annotations
import math
+from typing import Union
import torch
-from torch import Tensor
-from kornia.core import Device
+# from torch import Tensor (use torch.Tensor instead)
from kornia.geometry.camera import PinholeCamera
def create_camera_dimensions(
- device: Device, dtype: torch.dtype, n_cams1: int = 3, n_cams2: int = 2
-) -> tuple[Tensor, Tensor, Tensor]:
+ device: Union[str, torch.device, None], dtype: torch.dtype, n_cams1: int = 3, n_cams2: int = 2
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Create camera dimensions for ray sampling.
Args:
- device: Device for tensors
+ device: Union[str, torch.device, None] for tensors
dtype: Data type for tensors
n_cams1: Number of cameras in first group (default: 3)
n_cams2: Number of cameras in second group (default: 2)
@@ -64,11 +64,11 @@ def create_camera_dimensions(
def create_intrinsics(
fxs: list[float | int],
fys: list[float | int],
- cxs: Tensor | list[float | int],
- cys: Tensor | list[float | int],
- device: Device,
+ cxs: torch.Tensor | list[float | int],
+ cys: torch.Tensor | list[float | int],
+ device: Union[str, torch.device, None],
dtype: torch.dtype,
-) -> Tensor:
+) -> torch.Tensor:
"""Create intrinsic camera matrices from focal lengths and principal points.
Args:
@@ -76,16 +76,16 @@ def create_intrinsics(
fys: Focal length in y direction
cxs: Principal point x coordinate
cys: Principal point y coordinate
- device: Device for tensors
+ device: Union[str, torch.device, None] for tensors
dtype: Data type for tensors
Returns:
Stacked intrinsic matrices of shape (N, 4, 4)
"""
- intrinsics_batch: list[Tensor] = []
+ intrinsics_batch: list[torch.Tensor] = []
# Convert cxs and cys to lists if they are tensors
- cxs_list = cxs.tolist() if isinstance(cxs, Tensor) else cxs
- cys_list = cys.tolist() if isinstance(cys, Tensor) else cys
+ cxs_list = cxs.tolist() if isinstance(cxs, torch.Tensor) else cxs
+ cys_list = cys.tolist() if isinstance(cys, torch.Tensor) else cys
for fx, fy, cx, cy in zip(fxs, fys, cxs_list, cys_list):
intrinsics = torch.eye(4, device=device, dtype=dtype)
intrinsics[0, 0] = fx
@@ -103,9 +103,9 @@ def create_extrinsics_with_rotation(
txs: list[float],
tys: list[float],
tzs: list[float],
- device: Device,
+ device: Union[str, torch.device, None],
dtype: torch.dtype,
-) -> Tensor:
+) -> torch.Tensor:
"""Create extrinsic camera matrices with rotation and translation.
Args:
@@ -115,29 +115,29 @@ def create_extrinsics_with_rotation(
txs: Translation in x direction
tys: Translation in y direction
tzs: Translation in z direction
- device: Device for tensors
+ device: Union[str, torch.device, None] for tensors
dtype: Data type for tensors
Returns:
Stacked extrinsic matrices of shape (N, 4, 4)
"""
- extrinsics_batch: list[Tensor] = []
+ extrinsics_batch: list[torch.Tensor] = []
for alpha, beta, gamma, tx, ty, tz in zip(alphas, betas, gammas, txs, tys, tzs):
Rx = torch.eye(3, device=device, dtype=dtype)
- Rx[1, 1] = math.cos(alpha)
- Rx[1, 2] = math.sin(alpha)
+ Rx[1, 1] = math.torch.cos(alpha)
+ Rx[1, 2] = math.torch.sin(alpha)
Rx[2, 1] = -Rx[1, 2]
Rx[2, 2] = Rx[1, 1]
Ry = torch.eye(3, device=device, dtype=dtype)
- Ry[0, 0] = math.cos(beta)
- Ry[0, 2] = -math.sin(beta)
+ Ry[0, 0] = math.torch.cos(beta)
+ Ry[0, 2] = -math.torch.sin(beta)
Ry[2, 0] = -Ry[0, 2]
Ry[2, 2] = Ry[0, 0]
Rz = torch.eye(3, device=device, dtype=dtype)
- Rz[0, 0] = math.cos(gamma)
- Rz[0, 1] = math.sin(gamma)
+ Rz[0, 0] = math.torch.cos(gamma)
+ Rz[0, 1] = math.torch.sin(gamma)
Rz[1, 0] = -Rz[0, 1]
Rz[1, 1] = Rz[0, 0]
@@ -154,13 +154,15 @@ def create_extrinsics_with_rotation(
return torch.stack(extrinsics_batch)
-def create_pinhole_camera(height: float, width: float, device: Device, dtype: torch.dtype) -> PinholeCamera:
+def create_pinhole_camera(
+ height: float, width: float, device: Union[str, torch.device, None], dtype: torch.dtype
+) -> PinholeCamera:
"""Create a single PinholeCamera with default parameters.
Args:
height: Camera image height
width: Camera image width
- device: Device for tensors
+ device: Union[str, torch.device, None] for tensors
dtype: Data type for tensors
Returns:
@@ -190,11 +192,11 @@ def create_pinhole_camera(height: float, width: float, device: Device, dtype: to
)
-def create_four_cameras(device: Device, dtype: torch.dtype) -> PinholeCamera:
+def create_four_cameras(device: Union[str, torch.device, None], dtype: torch.dtype) -> PinholeCamera:
"""Create four PinholeCameras with predefined parameters.
Args:
- device: Device for tensors
+ device: Union[str, torch.device, None] for tensors
dtype: Data type for tensors
Returns:
@@ -225,19 +227,19 @@ def create_four_cameras(device: Device, dtype: torch.dtype) -> PinholeCamera:
return cameras
-def create_random_images_for_cameras(cameras: PinholeCamera) -> list[Tensor]:
+def create_random_images_for_cameras(cameras: PinholeCamera) -> list[torch.Tensor]:
"""Create random images for a given set of cameras."""
torch.manual_seed(112)
- imgs: list[Tensor] = []
+ imgs: list[torch.Tensor] = []
for height, width in zip(cameras.height.tolist(), cameras.width.tolist()):
image_data = torch.randint(0, 255, (3, int(height), int(width)), dtype=torch.uint8) # (C, H, W)
imgs.append(image_data) # (C, H, W)
return imgs
-def create_red_images_for_cameras(cameras: PinholeCamera, device: Device) -> list[Tensor]:
+def create_red_images_for_cameras(cameras: PinholeCamera, device: Union[str, torch.device, None]) -> list[torch.Tensor]:
"""Create red images for a given set of cameras."""
- imgs: list[Tensor] = []
+ imgs: list[torch.Tensor] = []
for height, width in zip(cameras.height.tolist(), cameras.width.tolist()):
image_data = torch.zeros(3, int(height), int(width), dtype=torch.uint8) # (C, H, W)
image_data[0, ...] = 255 # Red channel
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 01a717179..3fe4c611c 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -23,7 +23,6 @@ import torch
import torch.nn.functional as F
from kornia.constants import pi
-from kornia.core import Tensor, concatenate, cos, pad, sin, stack, tensor, where, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils import deprecated
from kornia.utils.helpers import _torch_inverse_cast
@@ -77,58 +76,58 @@ __all__ = [
]
-def rad2deg(tensor: Tensor) -> Tensor:
+def rad2deg(tensor: torch.Tensor) -> torch.Tensor:
r"""Convert angles from radians to degrees.
Args:
- tensor: Tensor of arbitrary shape.
+ tensor: torch.Tensor of arbitrary shape.
Returns:
- Tensor with same shape as input.
+ torch.Tensor with same shape as input.
Example:
- >>> input = tensor(3.1415926535)
+ >>> input = torch.tensor(3.1415926535)
>>> rad2deg(input)
tensor(180.)
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
return 180.0 * tensor / pi.to(tensor.device).type(tensor.dtype)
-def deg2rad(tensor: Tensor) -> Tensor:
+def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
r"""Convert angles from degrees to radians.
Args:
- tensor: Tensor of arbitrary shape.
+ tensor: torch.Tensor of arbitrary shape.
Returns:
tensor with same shape as input.
Examples:
- >>> input = tensor(180.)
+ >>> input = torch.tensor(180.)
>>> deg2rad(input)
tensor(3.1416)
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.0
-def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
+def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert polar coordinates to cartesian coordinates.
Args:
- rho: Tensor of arbitrary shape.
- phi: Tensor of same arbitrary shape.
+ rho: torch.Tensor of arbitrary shape.
+ phi: torch.Tensor of same arbitrary shape.
Returns:
- - x: Tensor with same shape as input.
- - y: Tensor with same shape as input.
+ - x: torch.Tensor with same shape as input.
+ - y: torch.Tensor with same shape as input.
Example:
>>> rho = torch.rand(1, 3, 3)
@@ -136,25 +135,25 @@ def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
>>> x, y = pol2cart(rho, phi)
"""
- if not (isinstance(rho, Tensor) & isinstance(phi, Tensor)):
- raise TypeError(f"Input type is not a Tensor. Got {type(rho)}, {type(phi)}")
+ if not (isinstance(rho, torch.Tensor) & isinstance(phi, torch.Tensor)):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(rho)}, {type(phi)}")
- x = rho * cos(phi)
- y = rho * sin(phi)
+ x = rho * torch.cos(phi)
+ y = rho * torch.sin(phi)
return x, y
-def cart2pol(x: Tensor, y: Tensor, eps: float = 1.0e-8) -> tuple[Tensor, Tensor]:
+def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> tuple[torch.Tensor, torch.Tensor]:
"""Convert cartesian coordinates to polar coordinates.
Args:
- x: Tensor of arbitrary shape.
- y: Tensor of same arbitrary shape.
+ x: torch.Tensor of arbitrary shape.
+ y: torch.Tensor of same arbitrary shape.
eps: To avoid division by zero.
Returns:
- - rho: Tensor with same shape as input.
- - phi: Tensor with same shape as input.
+ - rho: torch.Tensor with same shape as input.
+ - phi: torch.Tensor with same shape as input.
Example:
>>> x = torch.rand(1, 3, 3)
@@ -162,15 +161,15 @@ def cart2pol(x: Tensor, y: Tensor, eps: float = 1.0e-8) -> tuple[Tensor, Tensor]
>>> rho, phi = cart2pol(x, y)
"""
- if not (isinstance(x, Tensor) & isinstance(y, Tensor)):
- raise TypeError(f"Input type is not a Tensor. Got {type(x)}, {type(y)}")
+ if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}, {type(y)}")
rho = torch.sqrt(x**2 + y**2 + eps)
phi = torch.atan2(y, x)
return rho, phi
-def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor:
+def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert points from homogeneous to Euclidean space.
Args:
@@ -181,30 +180,30 @@ def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor
the points in Euclidean space :math:`(B, N, D-1)`.
Examples:
- >>> input = tensor([[0., 0., 1.]])
+ >>> input = torch.tensor([[0., 0., 1.]])
>>> convert_points_from_homogeneous(input)
tensor([[0., 0.]])
"""
- if not isinstance(points, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(points)}")
+ if not isinstance(points, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
# we check for points at max_val
- z_vec: Tensor = points[..., -1:]
+ z_vec: torch.Tensor = points[..., -1:]
# set the results of division by zeror/near-zero to 1.0
# follow the convention of opencv:
# https://github.com/opencv/opencv/pull/14411/files
- mask: Tensor = torch.abs(z_vec) > eps
- scale = where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
+ mask: torch.Tensor = torch.abs(z_vec) > eps
+ scale = torch.where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
return scale * points[..., :-1]
-def convert_points_to_homogeneous(points: Tensor) -> Tensor:
+def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
r"""Convert points from Euclidean to homogeneous space.
Args:
@@ -214,26 +213,26 @@ def convert_points_to_homogeneous(points: Tensor) -> Tensor:
the points in homogeneous coordinates :math:`(*, N, D+1)`.
Examples:
- >>> input = tensor([[0., 0.]])
+ >>> input = torch.tensor([[0., 0.]])
>>> convert_points_to_homogeneous(input)
tensor([[0., 0., 1.]])
"""
- if not isinstance(points, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(points)}")
+ if not isinstance(points, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
- return pad(points, [0, 1], "constant", 1.0)
+ return F.pad(points, [0, 1], "constant", 1.0)
-def _convert_affinematrix_to_homography_impl(A: Tensor) -> Tensor:
- H: Tensor = pad(A, [0, 0, 0, 1], "constant", value=0.0)
+def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
+ H: torch.Tensor = F.pad(A, [0, 0, 0, 1], "constant", value=0.0)
H[..., -1, -1] += 1.0
return H
-def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
+def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
r"""Convert batch of affine matrices.
Args:
@@ -243,7 +242,7 @@ def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
the homography matrix with shape of :math:`(B,3,3)`.
Examples:
- >>> A = tensor([[[1., 0., 0.],
+ >>> A = torch.tensor([[[1., 0., 0.],
... [0., 1., 0.]]])
>>> convert_affinematrix_to_homography(A)
tensor([[[1., 0., 0.],
@@ -251,8 +250,8 @@ def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
[0., 0., 1.]]])
"""
- if not isinstance(A, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(A)}")
+ if not isinstance(A, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")
if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):
raise ValueError(f"Input matrix must be a Bx2x3 tensor. Got {A.shape}")
@@ -260,7 +259,7 @@ def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
return _convert_affinematrix_to_homography_impl(A)
-def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
+def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
r"""Convert batch of 3d affine matrices.
Args:
@@ -270,7 +269,7 @@ def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
the homography matrix with shape of :math:`(B,4,4)`.
Examples:
- >>> A = tensor([[[1., 0., 0., 0.],
+ >>> A = torch.tensor([[[1., 0., 0., 0.],
... [0., 1., 0., 0.],
... [0., 0., 1., 0.]]])
>>> convert_affinematrix_to_homography3d(A)
@@ -280,8 +279,8 @@ def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
[0., 0., 0., 1.]]])
"""
- if not isinstance(A, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(A)}")
+ if not isinstance(A, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")
if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):
raise ValueError(f"Input matrix must be a Bx3x4 tensor. Got {A.shape}")
@@ -289,7 +288,7 @@ def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
return _convert_affinematrix_to_homography_impl(A)
-def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
+def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix.
Args:
@@ -299,26 +298,26 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
tensor of rotation matrices of shape :math:`(N, 3, 3)`.
Example:
- >>> input = tensor([[0., 0., 0.]])
+ >>> input = torch.tensor([[0., 0., 0.]])
>>> axis_angle_to_rotation_matrix(input) # doctest: +ELLIPSIS
tensor([[[1., ...0., 0.],
[0., 1., ...0.],
[...0., 0., 1.]]])
- >>> input = tensor([[1.5708, 0., 0.]])
+ >>> input = torch.tensor([[1.5708, 0., 0.]])
>>> axis_angle_to_rotation_matrix(input)
tensor([[[ 1.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, -3.6200e-06, -1.0000e+00],
[ 0.0000e+00, 1.0000e+00, -3.6200e-06]]])
"""
- if not isinstance(axis_angle, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(axis_angle)}")
+ if not isinstance(axis_angle, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(axis_angle)}")
if not axis_angle.shape[-1] == 3:
raise ValueError(f"Input size must be a (*, 3) tensor. Got {axis_angle.shape}")
- def _compute_rotation_matrix(axis_angle: Tensor, theta2: Tensor, eps: float = 1e-6) -> Tensor:
+ def _compute_rotation_matrix(axis_angle: torch.Tensor, theta2: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
theta = torch.sqrt(theta2.clamp(min=1e-12)) # clamping to ensure no nan gradients
wxyz = axis_angle / (theta.unsqueeze(-1) + eps) # (B, 3)
wx, wy, wz = wxyz.unbind(dim=1) # (B,)
@@ -354,7 +353,7 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
return rot
- def _compute_rotation_matrix_taylor(axis_angle: Tensor) -> Tensor:
+ def _compute_rotation_matrix_taylor(axis_angle: torch.Tensor) -> torch.Tensor:
rx, ry, rz = axis_angle.unbind(-1)
k_one = torch.ones_like(rx)
@@ -388,11 +387,11 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
@deprecated(replace_with="axis_angle_to_rotation_matrix", version="0.7.0")
-def angle_axis_to_rotation_matrix(axis_angle: Tensor) -> Tensor: # noqa: D103
+def angle_axis_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor: # noqa: D103
return axis_angle_to_rotation_matrix(axis_angle)
-def rotation_matrix_to_axis_angle(rotation_matrix: Tensor) -> Tensor:
+def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector in radians.
Args:
@@ -402,34 +401,34 @@ def rotation_matrix_to_axis_angle(rotation_matrix: Tensor) -> Tensor:
Rodrigues vector transformation of shape :math:`(N, 3)`.
Example:
- >>> input = tensor([[1., 0., 0.],
+ >>> input = torch.tensor([[1., 0., 0.],
... [0., 1., 0.],
... [0., 0., 1.]])
>>> rotation_matrix_to_axis_angle(input)
tensor([0., 0., 0.])
- >>> input = tensor([[1., 0., 0.],
+ >>> input = torch.tensor([[1., 0., 0.],
... [0., 0., -1.],
... [0., 1., 0.]])
>>> rotation_matrix_to_axis_angle(input)
tensor([1.5708, 0.0000, 0.0000])
"""
- if not isinstance(rotation_matrix, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(rotation_matrix)}")
+ if not isinstance(rotation_matrix, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
- quaternion: Tensor = rotation_matrix_to_quaternion(rotation_matrix)
+ quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix)
return quaternion_to_axis_angle(quaternion)
@deprecated(replace_with="rotation_matrix_to_axis_angle", version="0.7.0")
-def rotation_matrix_to_angle_axis(rotation_matrix: Tensor) -> Tensor: # noqa: D103
+def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensor: # noqa: D103
return rotation_matrix_to_axis_angle(rotation_matrix)
-def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8) -> Tensor:
+def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.0e-8) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to 4d quaternion vector.
The quaternion vector has components in (w, x, y, z) format.
@@ -442,69 +441,69 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
the rotation in quaternion with shape :math:`(*, 4)`.
Example:
- >>> input = tensor([[1., 0., 0.],
+ >>> input = torch.tensor([[1., 0., 0.],
... [0., 1., 0.],
... [0., 0., 1.]])
>>> rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps)
tensor([1., 0., 0., 0.])
"""
- if not isinstance(rotation_matrix, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(rotation_matrix)}")
+ if not isinstance(rotation_matrix, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
- def safe_zero_division(numerator: Tensor, denominator: Tensor) -> Tensor:
+ def safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor) -> torch.Tensor:
eps: float = torch.finfo(numerator.dtype).tiny
return numerator / torch.clamp(denominator, min=eps)
- rotation_matrix_vec: Tensor = rotation_matrix.reshape(*rotation_matrix.shape[:-2], 9)
+ rotation_matrix_vec: torch.Tensor = rotation_matrix.reshape(*rotation_matrix.shape[:-2], 9)
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(rotation_matrix_vec, chunks=9, dim=-1)
- trace: Tensor = m00 + m11 + m22
+ trace: torch.Tensor = m00 + m11 + m22
- def trace_positive_cond() -> Tensor:
+ def trace_positive_cond() -> torch.Tensor:
sq = torch.sqrt(trace + 1.0 + eps) * 2.0 # sq = 4 * qw.
qw = 0.25 * sq
qx = safe_zero_division(m21 - m12, sq)
qy = safe_zero_division(m02 - m20, sq)
qz = safe_zero_division(m10 - m01, sq)
- return concatenate((qw, qx, qy, qz), dim=-1)
+ return torch.cat((qw, qx, qy, qz), dim=-1)
- def cond_1() -> Tensor:
+ def cond_1() -> torch.Tensor:
sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2.0 # sq = 4 * qx.
qw = safe_zero_division(m21 - m12, sq)
qx = 0.25 * sq
qy = safe_zero_division(m01 + m10, sq)
qz = safe_zero_division(m02 + m20, sq)
- return concatenate((qw, qx, qy, qz), dim=-1)
+ return torch.cat((qw, qx, qy, qz), dim=-1)
- def cond_2() -> Tensor:
+ def cond_2() -> torch.Tensor:
sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2.0 # sq = 4 * qy.
qw = safe_zero_division(m02 - m20, sq)
qx = safe_zero_division(m01 + m10, sq)
qy = 0.25 * sq
qz = safe_zero_division(m12 + m21, sq)
- return concatenate((qw, qx, qy, qz), dim=-1)
+ return torch.cat((qw, qx, qy, qz), dim=-1)
- def cond_3() -> Tensor:
+ def cond_3() -> torch.Tensor:
sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2.0 # sq = 4 * qz.
qw = safe_zero_division(m10 - m01, sq)
qx = safe_zero_division(m02 + m20, sq)
qy = safe_zero_division(m12 + m21, sq)
qz = 0.25 * sq
- return concatenate((qw, qx, qy, qz), dim=-1)
+ return torch.cat((qw, qx, qy, qz), dim=-1)
- where_2 = where(m11 > m22, cond_2(), cond_3())
- where_1 = where((m00 > m11) & (m00 > m22), cond_1(), where_2)
+ where_2 = torch.where(m11 > m22, cond_2(), cond_3())
+ where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
- quaternion: Tensor = where(trace > 0.0, trace_positive_cond(), where_1)
+ quaternion: torch.Tensor = torch.where(trace > 0.0, trace_positive_cond(), where_1)
return quaternion
-def normalize_quaternion(quaternion: Tensor, eps: float = 1.0e-12) -> Tensor:
+def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torch.Tensor:
r"""Normalize a quaternion.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
@@ -518,13 +517,13 @@ def normalize_quaternion(quaternion: Tensor, eps: float = 1.0e-12) -> Tensor:
the normalized quaternion of shape :math:`(*, 4)`.
Example:
- >>> quaternion = tensor((1., 0., 1., 0.))
+ >>> quaternion = torch.tensor((1., 0., 1., 0.))
>>> normalize_quaternion(quaternion)
tensor([0.7071, 0.0000, 0.7071, 0.0000])
"""
- if not isinstance(quaternion, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
+ if not isinstance(quaternion, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
@@ -536,7 +535,7 @@ def normalize_quaternion(quaternion: Tensor, eps: float = 1.0e-12) -> Tensor:
# https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py#L247
-def quaternion_to_rotation_matrix(quaternion: Tensor) -> Tensor:
+def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
r"""Convert a quaternion to a rotation matrix.
The quaternion should be in (w, x, y, z) format.
@@ -549,21 +548,21 @@ def quaternion_to_rotation_matrix(quaternion: Tensor) -> Tensor:
the rotation matrix of shape :math:`(*, 3, 3)`.
Example:
- >>> quaternion = tensor((0., 0., 0., 1.))
+ >>> quaternion = torch.tensor((0., 0., 0., 1.))
>>> quaternion_to_rotation_matrix(quaternion)
tensor([[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., 1.]])
"""
- if not isinstance(quaternion, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
+ if not isinstance(quaternion, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
# normalize the input quaternion
- quaternion_norm: Tensor = normalize_quaternion(quaternion)
+ quaternion_norm: torch.Tensor = normalize_quaternion(quaternion)
# unpack the normalized quaternion components
w = quaternion_norm[..., 0]
@@ -572,21 +571,21 @@ def quaternion_to_rotation_matrix(quaternion: Tensor) -> Tensor:
z = quaternion_norm[..., 3]
# compute the actual conversion
- tx: Tensor = 2.0 * x
- ty: Tensor = 2.0 * y
- tz: Tensor = 2.0 * z
- twx: Tensor = tx * w
- twy: Tensor = ty * w
- twz: Tensor = tz * w
- txx: Tensor = tx * x
- txy: Tensor = ty * x
- txz: Tensor = tz * x
- tyy: Tensor = ty * y
- tyz: Tensor = tz * y
- tzz: Tensor = tz * z
- one: Tensor = tensor(1.0)
-
- matrix_flat: Tensor = stack(
+ tx: torch.Tensor = 2.0 * x
+ ty: torch.Tensor = 2.0 * y
+ tz: torch.Tensor = 2.0 * z
+ twx: torch.Tensor = tx * w
+ twy: torch.Tensor = ty * w
+ twz: torch.Tensor = tz * w
+ txx: torch.Tensor = tx * x
+ txy: torch.Tensor = ty * x
+ txz: torch.Tensor = tz * x
+ tyy: torch.Tensor = ty * y
+ tyz: torch.Tensor = tz * y
+ tzz: torch.Tensor = tz * z
+ one: torch.Tensor = torch.tensor(1.0)
+
+ matrix_flat: torch.Tensor = torch.stack(
(
one - (tyy + tzz),
txy - twz,
@@ -608,7 +607,7 @@ def quaternion_to_rotation_matrix(quaternion: Tensor) -> Tensor:
return matrix
-def quaternion_to_axis_angle(quaternion: Tensor) -> Tensor:
+def quaternion_to_axis_angle(quaternion: torch.Tensor) -> torch.Tensor:
"""Convert quaternion vector to axis angle of rotation in radians.
The quaternion should be in (w, x, y, z) format.
@@ -626,40 +625,40 @@ def quaternion_to_axis_angle(quaternion: Tensor) -> Tensor:
- Output: :math:`(*, 3)`
Example:
- >>> quaternion = tensor((1., 0., 0., 0.))
+ >>> quaternion = torch.tensor((1., 0., 0., 0.))
>>> quaternion_to_axis_angle(quaternion)
tensor([0., 0., 0.])
"""
- if not torch.is_tensor(quaternion):
- raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
+ if not isinstance(quaternion, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape Nx4 or 4. Got {quaternion.shape}")
# unpack input and compute conversion
- q1: Tensor = tensor([])
- q2: Tensor = tensor([])
- q3: Tensor = tensor([])
- cos_theta: Tensor = tensor([])
+ q1: torch.Tensor = torch.tensor([])
+ q2: torch.Tensor = torch.tensor([])
+ q3: torch.Tensor = torch.tensor([])
+ cos_theta: torch.Tensor = torch.tensor([])
cos_theta = quaternion[..., 0]
q1 = quaternion[..., 1]
q2 = quaternion[..., 2]
q3 = quaternion[..., 3]
- sin_squared_theta: Tensor = q1 * q1 + q2 * q2 + q3 * q3
+ sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
- sin_theta: Tensor = torch.sqrt(sin_squared_theta)
- two_theta: Tensor = 2.0 * where(
+ sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
+ two_theta: torch.Tensor = 2.0 * torch.where(
cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
)
- k_pos: Tensor = two_theta / sin_theta
- k_neg: Tensor = 2.0 * torch.ones_like(sin_theta)
- k: Tensor = where(sin_squared_theta > 0.0, k_pos, k_neg)
+ k_pos: torch.Tensor = two_theta / sin_theta
+ k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
+ k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
- axis_angle: Tensor = torch.zeros_like(quaternion)[..., :3]
+ axis_angle: torch.Tensor = torch.zeros_like(quaternion)[..., :3]
axis_angle[..., 0] += q1 * k
axis_angle[..., 1] += q2 * k
axis_angle[..., 2] += q3 * k
@@ -667,11 +666,11 @@ def quaternion_to_axis_angle(quaternion: Tensor) -> Tensor:
@deprecated(replace_with="quaternion_to_axis_angle", version="0.7.0")
-def quaternion_to_angle_axis(quaternion: Tensor) -> Tensor: # noqa: D103
+def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor: # noqa: D103
return quaternion_to_axis_angle(quaternion)
-def quaternion_log_to_exp(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
+def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torch.Tensor:
r"""Apply exponential map to log quaternion.
The quaternion should be in (w, x, y, z) format.
@@ -685,32 +684,32 @@ def quaternion_log_to_exp(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
the quaternion exponential map of shape :math:`(*, 4)`.
Example:
- >>> quaternion = tensor((0., 0., 0.))
+ >>> quaternion = torch.tensor((0., 0., 0.))
>>> quaternion_log_to_exp(quaternion, eps=torch.finfo(quaternion.dtype).eps)
tensor([1., 0., 0., 0.])
"""
- if not isinstance(quaternion, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
+ if not isinstance(quaternion, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 3:
raise ValueError(f"Input must be a tensor of shape (*, 3). Got {quaternion.shape}")
# compute quaternion norm
- norm_q: Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
+ norm_q: torch.Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
# compute scalar and vector
- quaternion_vector: Tensor = quaternion * sin(norm_q) / norm_q
- quaternion_scalar: Tensor = cos(norm_q)
+ quaternion_vector: torch.Tensor = quaternion * torch.sin(norm_q) / norm_q
+ quaternion_scalar: torch.Tensor = torch.cos(norm_q)
# compose quaternion and return
- quaternion_exp: Tensor = tensor([])
- quaternion_exp = concatenate((quaternion_scalar, quaternion_vector), dim=-1)
+ quaternion_exp: torch.Tensor = torch.tensor([])
+ quaternion_exp = torch.cat((quaternion_scalar, quaternion_vector), dim=-1)
return quaternion_exp
-def quaternion_exp_to_log(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
+def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torch.Tensor:
r"""Apply the log map to a quaternion.
The quaternion should be in (w, x, y, z) format.
@@ -724,29 +723,31 @@ def quaternion_exp_to_log(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
the quaternion log map of shape :math:`(*, 3)`.
Example:
- >>> quaternion = tensor((1., 0., 0., 0.))
+ >>> quaternion = torch.tensor((1., 0., 0., 0.))
>>> quaternion_exp_to_log(quaternion, eps=torch.finfo(quaternion.dtype).eps)
tensor([0., 0., 0.])
"""
- if not isinstance(quaternion, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
+ if not isinstance(quaternion, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
# unpack quaternion vector and scalar
- quaternion_vector: Tensor = tensor([])
- quaternion_scalar: Tensor = tensor([])
+ quaternion_vector: torch.Tensor = torch.tensor([])
+ quaternion_scalar: torch.Tensor = torch.tensor([])
quaternion_scalar = quaternion[..., 0:1]
quaternion_vector = quaternion[..., 1:4]
# compute quaternion norm
- norm_q: Tensor = torch.norm(quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)
+ norm_q: torch.Tensor = torch.norm(quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)
# apply log map
- quaternion_log: Tensor = quaternion_vector * torch.acos(torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
+ quaternion_log: torch.Tensor = (
+ quaternion_vector * torch.acos(torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
+ )
return quaternion_log
@@ -755,7 +756,7 @@ def quaternion_exp_to_log(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
# https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138
-def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
+def axis_angle_to_quaternion(axis_angle: torch.Tensor) -> torch.Tensor:
r"""Convert an axis angle to a quaternion.
The quaternion vector has components in (w, x, y, z) format.
@@ -773,35 +774,37 @@ def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
- Output: :math:`(*, 4)`
Example:
- >>> axis_angle = tensor((0., 1., 0.))
+ >>> axis_angle = torch.tensor((0., 1., 0.))
>>> axis_angle_to_quaternion(axis_angle)
tensor([0.8776, 0.0000, 0.4794, 0.0000])
"""
- if not torch.is_tensor(axis_angle):
- raise TypeError(f"Input type is not a Tensor. Got {type(axis_angle)}")
+ if not isinstance(axis_angle, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(axis_angle)}")
if not axis_angle.shape[-1] == 3:
raise ValueError(f"Input must be a tensor of shape Nx3 or 3. Got {axis_angle.shape}")
# unpack input and compute conversion
- a0: Tensor = axis_angle[..., 0:1]
- a1: Tensor = axis_angle[..., 1:2]
- a2: Tensor = axis_angle[..., 2:3]
- theta_squared: Tensor = a0 * a0 + a1 * a1 + a2 * a2
+ a0: torch.Tensor = axis_angle[..., 0:1]
+ a1: torch.Tensor = axis_angle[..., 1:2]
+ a2: torch.Tensor = axis_angle[..., 2:3]
+ theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2
- theta: Tensor = torch.sqrt(theta_squared)
- half_theta: Tensor = theta * 0.5
+ theta: torch.Tensor = torch.sqrt(theta_squared)
+ half_theta: torch.Tensor = theta * 0.5
- mask: Tensor = theta_squared > 0.0
- ones: Tensor = torch.ones_like(half_theta)
+ mask: torch.Tensor = theta_squared > 0.0
+ ones: torch.Tensor = torch.ones_like(half_theta)
- k_neg: Tensor = 0.5 * ones
- k_pos: Tensor = sin(half_theta) / theta
- k: Tensor = where(mask, k_pos, k_neg)
- w: Tensor = where(mask, cos(half_theta), ones)
+ k_neg: torch.Tensor = 0.5 * ones
+ k_pos: torch.Tensor = torch.sin(half_theta) / theta
+ k: torch.Tensor = torch.where(mask, k_pos, k_neg)
+ w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
- quaternion: Tensor = torch.zeros(size=(*axis_angle.shape[:-1], 4), dtype=axis_angle.dtype, device=axis_angle.device)
+ quaternion: torch.Tensor = torch.zeros(
+ size=(*axis_angle.shape[:-1], 4), dtype=axis_angle.dtype, device=axis_angle.device
+ )
quaternion[..., 1:2] = a0 * k
quaternion[..., 2:3] = a1 * k
quaternion[..., 3:4] = a2 * k
@@ -810,14 +813,16 @@ def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
@deprecated(replace_with="axis_angle_to_quaternion", version="0.7.0")
-def angle_axis_to_quaternion(axis_angle: Tensor) -> Tensor: # noqa: D103
+def angle_axis_to_quaternion(axis_angle: torch.Tensor) -> torch.Tensor: # noqa: D103
return axis_angle_to_quaternion(axis_angle)
# inspired by: https://stackoverflow.com/questions/56207448/efficient-quaternions-to-euler-transformation
-def euler_from_quaternion(w: Tensor, x: Tensor, y: Tensor, z: Tensor) -> tuple[Tensor, Tensor, Tensor]:
+def euler_from_quaternion(
+ w: torch.Tensor, x: torch.Tensor, y: torch.Tensor, z: torch.Tensor
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert a quaternion coefficients to Euler angles.
Returned angles are in radians in XYZ convention.
@@ -853,7 +858,9 @@ def euler_from_quaternion(w: Tensor, x: Tensor, y: Tensor, z: Tensor) -> tuple[T
return roll, pitch, yaw
-def quaternion_from_euler(roll: Tensor, pitch: Tensor, yaw: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+def quaternion_from_euler(
+ roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert Euler angles to quaternion coefficients.
Euler angles are assumed to be in radians in XYZ convention.
@@ -893,7 +900,9 @@ def quaternion_from_euler(roll: Tensor, pitch: Tensor, yaw: Tensor) -> tuple[Ten
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71
-def normalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width: int, eps: float = 1e-8) -> Tensor:
+def normalize_pixel_coordinates(
+ pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -908,7 +917,7 @@ def normalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width: i
the normalized pixel coordinates with shape :math:`(*, 2)`.
Examples:
- >>> coords = tensor([[50., 100.]])
+ >>> coords = torch.tensor([[50., 100.]])
>>> normalize_pixel_coordinates(coords, 100, 50)
tensor([[1.0408, 1.0202]])
@@ -917,19 +926,23 @@ def normalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width: i
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
# compute normalization factor
- hw: Tensor = stack(
+ hw: torch.Tensor = torch.stack(
[
- tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
- tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
+ torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
+ torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
]
)
- factor: Tensor = tensor(2.0, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (hw - 1).clamp(eps)
+ factor: torch.Tensor = torch.tensor(2.0, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (
+ hw - 1
+ ).clamp(eps)
return factor * pixel_coordinates - 1
-def denormalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width: int, eps: float = 1e-8) -> Tensor:
+def denormalize_pixel_coordinates(
+ pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -944,7 +957,7 @@ def denormalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width:
the denormalized pixel coordinates with shape :math:`(*, 2)`.
Examples:
- >>> coords = tensor([[-1., -1.]])
+ >>> coords = torch.tensor([[-1., -1.]])
>>> denormalize_pixel_coordinates(coords, 100, 50)
tensor([[0., 0.]])
@@ -952,16 +965,20 @@ def denormalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width:
if pixel_coordinates.shape[-1] != 2:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
# compute normalization factor
- hw: Tensor = stack([tensor(width), tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ hw: torch.Tensor = (
+ torch.stack([torch.tensor(width), torch.tensor(height)])
+ .to(pixel_coordinates.device)
+ .to(pixel_coordinates.dtype)
+ )
- factor: Tensor = tensor(2.0) / (hw - 1).clamp(eps)
+ factor: torch.Tensor = torch.tensor(2.0) / (hw - 1).clamp(eps)
- return tensor(1.0) / factor * (pixel_coordinates + 1)
+ return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
def normalize_pixel_coordinates3d(
- pixel_coordinates: Tensor, depth: int, height: int, width: int, eps: float = 1e-8
-) -> Tensor:
+ pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -980,18 +997,20 @@ def normalize_pixel_coordinates3d(
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
# compute normalization factor
- dhw: Tensor = (
- stack([tensor(depth), tensor(width), tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ dhw: torch.Tensor = (
+ torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
+ .to(pixel_coordinates.device)
+ .to(pixel_coordinates.dtype)
)
- factor: Tensor = tensor(2.0) / (dhw - 1).clamp(eps)
+ factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
return factor * pixel_coordinates - 1
def denormalize_pixel_coordinates3d(
- pixel_coordinates: Tensor, depth: int, height: int, width: int, eps: float = 1e-8
-) -> Tensor:
+ pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -1010,16 +1029,18 @@ def denormalize_pixel_coordinates3d(
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
# compute normalization factor
- dhw: Tensor = (
- stack([tensor(depth), tensor(width), tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ dhw: torch.Tensor = (
+ torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
+ .to(pixel_coordinates.device)
+ .to(pixel_coordinates.dtype)
)
- factor: Tensor = tensor(2.0) / (dhw - 1).clamp(eps)
+ factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
- return tensor(1.0) / factor * (pixel_coordinates + 1)
+ return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
-def angle_to_rotation_matrix(angle: Tensor) -> Tensor:
+def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
r"""Create a rotation matrix out of angles in degrees.
Args:
@@ -1034,14 +1055,14 @@ def angle_to_rotation_matrix(angle: Tensor) -> Tensor:
"""
ang_rad = deg2rad(angle)
- cos_a: Tensor = cos(ang_rad)
- sin_a: Tensor = sin(ang_rad)
- return stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)
+ cos_a: torch.Tensor = torch.cos(ang_rad)
+ sin_a: torch.Tensor = torch.sin(ang_rad)
+ return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)
def normalize_homography(
- dst_pix_trans_src_pix: Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
-) -> Tensor:
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
+) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
Args:
@@ -1054,8 +1075,8 @@ def normalize_homography(
the normalized homography of shape :math:`(B, 3, 3)`.
"""
- if not isinstance(dst_pix_trans_src_pix, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
+ if not isinstance(dst_pix_trans_src_pix, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst_pix_trans_src_pix)}")
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (3, 3)):
raise ValueError(f"Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {dst_pix_trans_src_pix.shape}")
@@ -1065,13 +1086,13 @@ def normalize_homography(
dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
src_pix_trans_src_norm = _torch_inverse_cast(src_norm_trans_src_pix)
- dst_norm_trans_dst_pix: Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
# compute chain transformations
- dst_norm_trans_src_norm: Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
+ dst_norm_trans_src_norm: torch.Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
return dst_norm_trans_src_norm
@@ -1081,7 +1102,7 @@ def normal_transform_pixel(
eps: float = 1e-14,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
Args:
@@ -1095,7 +1116,7 @@ def normal_transform_pixel(
normalized transform with shape :math:`(1, 3, 3)`.
"""
- tr_mat = tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
+ tr_mat = torch.tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
# prevent divide by zero bugs
width_denom: float = eps if width == 1 else width - 1.0
@@ -1114,7 +1135,7 @@ def normal_transform_pixel3d(
eps: float = 1e-14,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
Args:
@@ -1129,7 +1150,7 @@ def normal_transform_pixel3d(
normalized transform with shape :math:`(1, 4, 4)`.
"""
- tr_mat = tensor(
+ tr_mat = torch.tensor(
[[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]],
device=device,
dtype=dtype,
@@ -1148,8 +1169,8 @@ def normal_transform_pixel3d(
def denormalize_homography(
- dst_pix_trans_src_pix: Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
-) -> Tensor:
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int], dsize_dst: tuple[int, int]
+) -> torch.Tensor:
r"""De-normalize a given homography in pixels from [-1, 1] to actual height and width.
Args:
@@ -1162,8 +1183,8 @@ def denormalize_homography(
the denormalized homography of shape :math:`(B, 3, 3)`.
"""
- if not isinstance(dst_pix_trans_src_pix, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
+ if not isinstance(dst_pix_trans_src_pix, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst_pix_trans_src_pix)}")
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (3, 3)):
raise ValueError(f"Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {dst_pix_trans_src_pix.shape}")
@@ -1173,18 +1194,18 @@ def denormalize_homography(
dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
- dst_norm_trans_dst_pix: Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
dst_denorm_trans_dst_pix = _torch_inverse_cast(dst_norm_trans_dst_pix)
# compute chain transformations
- dst_norm_trans_src_norm: Tensor = dst_denorm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)
+ dst_norm_trans_src_norm: torch.Tensor = dst_denorm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)
return dst_norm_trans_src_norm
def normalize_homography3d(
- dst_pix_trans_src_pix: Tensor, dsize_src: tuple[int, int, int], dsize_dst: tuple[int, int, int]
-) -> Tensor:
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int, int], dsize_dst: tuple[int, int, int]
+) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
Args:
@@ -1200,8 +1221,8 @@ def normalize_homography3d(
Output: :math:`(B, 4, 4)`
"""
- if not isinstance(dst_pix_trans_src_pix, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
+ if not isinstance(dst_pix_trans_src_pix, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst_pix_trans_src_pix)}")
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (4, 4)):
raise ValueError(f"Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {dst_pix_trans_src_pix.shape}")
@@ -1210,16 +1231,16 @@ def normalize_homography3d(
src_d, src_h, src_w = dsize_src
dst_d, dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: Tensor = normal_transform_pixel3d(src_d, src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(src_d, src_h, src_w).to(dst_pix_trans_src_pix)
src_pix_trans_src_norm = _torch_inverse_cast(src_norm_trans_src_pix)
- dst_norm_trans_dst_pix: Tensor = normal_transform_pixel3d(dst_d, dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(dst_d, dst_h, dst_w).to(dst_pix_trans_src_pix)
# compute chain transformations
- dst_norm_trans_src_norm: Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
+ dst_norm_trans_src_norm: torch.Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
return dst_norm_trans_src_norm
-def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) -> Tensor:
+def normalize_points_with_intrinsics(point_2d: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:
"""Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
@@ -1253,7 +1274,7 @@ def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) ->
return xy
-def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Tensor) -> Tensor:
+def denormalize_points_with_intrinsics(point_2d_norm: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:
"""Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
@@ -1279,26 +1300,26 @@ def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Ten
# v = fy * Y + cy
# unpack coordinates
- x_coord: Tensor = point_2d_norm[..., 0]
- y_coord: Tensor = point_2d_norm[..., 1]
+ x_coord: torch.Tensor = point_2d_norm[..., 0]
+ y_coord: torch.Tensor = point_2d_norm[..., 1]
# unpack intrinsics
- fx: Tensor = camera_matrix[..., 0, 0]
- fy: Tensor = camera_matrix[..., 1, 1]
- cx: Tensor = camera_matrix[..., 0, 2]
- cy: Tensor = camera_matrix[..., 1, 2]
+ fx: torch.Tensor = camera_matrix[..., 0, 0]
+ fy: torch.Tensor = camera_matrix[..., 1, 1]
+ cx: torch.Tensor = camera_matrix[..., 0, 2]
+ cy: torch.Tensor = camera_matrix[..., 1, 2]
if len(cx.shape) < len(x_coord.shape): # broadcast intrinsics
cx, cy, fx, fy = cx.unsqueeze(-1), cy.unsqueeze(-1), fx.unsqueeze(-1), fy.unsqueeze(-1)
# apply intrinsics ans return
- u_coord: Tensor = x_coord * fx + cx
- v_coord: Tensor = y_coord * fy + cy
+ u_coord: torch.Tensor = x_coord * fx + cx
+ v_coord: torch.Tensor = y_coord * fy + cy
- return stack([u_coord, v_coord], dim=-1)
+ return torch.stack([u_coord, v_coord], dim=-1)
-def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:
+def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
r"""Combine 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.
Args:
@@ -1319,11 +1340,11 @@ def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
- Rt = concatenate([R, t], dim=2)
+ Rt = torch.cat([R, t], dim=2)
return convert_affinematrix_to_homography3d(Rt)
-def matrix4x4_to_Rt(extrinsics: Tensor) -> tuple[Tensor, Tensor]:
+def matrix4x4_to_Rt(extrinsics: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert 4x4 extrinsics into 3x3 rotation matrix R and 1x3 translation vector ts.
Args:
@@ -1348,7 +1369,7 @@ def matrix4x4_to_Rt(extrinsics: Tensor) -> tuple[Tensor, Tensor]:
return R, t
-def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
+def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torch.Tensor:
r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
@@ -1370,7 +1391,7 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
"""
KORNIA_CHECK_SHAPE(extrinsics_graphics, ["B", "4", "4"])
- invert_yz = tensor(
+ invert_yz = torch.tensor(
[[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1.0]]],
dtype=extrinsics_graphics.dtype,
device=extrinsics_graphics.device,
@@ -1378,7 +1399,7 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
return extrinsics_graphics @ invert_yz
-def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
+def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
@@ -1408,7 +1429,7 @@ def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
return matrix4x4_to_Rt(mat4x4)
-def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
+def camtoworld_vision_to_graphics_4x4(extrinsics_vision: torch.Tensor) -> torch.Tensor:
r"""Convert vision coordinate frame (e.g. OpenCV) to graphics coordinate frame (e.g. OpenGK.).
I.e. flips y and z axis Graphics convention: [+x, +y, +z] == [right, up, backwards].
@@ -1430,7 +1451,7 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
"""
KORNIA_CHECK_SHAPE(extrinsics_vision, ["B", "4", "4"])
- invert_yz = tensor(
+ invert_yz = torch.tensor(
[[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1.0]]],
dtype=extrinsics_vision.dtype,
device=extrinsics_vision.device,
@@ -1438,7 +1459,7 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
return extrinsics_vision @ invert_yz
-def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
+def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
@@ -1468,7 +1489,7 @@ def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
return matrix4x4_to_Rt(mat4x4)
-def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
+def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert camtoworld to worldtocam frame used in Colmap.
See
@@ -1496,12 +1517,12 @@ def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
R_inv = R.transpose(1, 2)
- new_t: Tensor = -R_inv @ t
+ new_t: torch.Tensor = -R_inv @ t
return (R_inv, new_t)
-def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
+def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert worldtocam frame used in Colmap to camtoworld.
Args:
@@ -1526,12 +1547,12 @@ def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
R_inv = R.transpose(1, 2)
- new_t: Tensor = -R_inv @ t
+ new_t: torch.Tensor = -R_inv @ t
return (R_inv, new_t)
-def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Tensor]:
+def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert output of Apple ARKit screen pose to the camera-to-world transformation, expected by Colmap.
Both poses in quaternion representation.
@@ -1545,7 +1566,7 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Ten
tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]
Example:
- >>> q, t = tensor([0, 1, 0, 1.])[None], torch.ones(3).reshape(1, 3, 1)
+ >>> q, t = torch.tensor([0, 1, 0, 1.])[None], torch.ones(3).reshape(1, 3, 1)
>>> ARKitQTVecs_to_ColmapQTVecs(q, t)
(tensor([[0.7071, 0.0000, 0.7071, 0.0000]]), tensor([[[-1.0000],
[-1.0000],
@@ -1562,7 +1583,7 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Ten
return q_colmap, t_colmap
-def vector_to_skew_symmetric_matrix(vec: Tensor) -> Tensor:
+def vector_to_skew_symmetric_matrix(vec: torch.Tensor) -> torch.Tensor:
r"""Convert a vector to a skew symmetric matrix.
A vector :math:`(v1, v2, v3)` has a corresponding skew-symmetric matrix, which is of the form:
@@ -1590,8 +1611,13 @@ def vector_to_skew_symmetric_matrix(vec: Tensor) -> Tensor:
if vec.shape[-1] != 3 or len(vec.shape) > 2:
raise ValueError(f"Input vector must be of shape (B, 3) or (3,). Got {vec.shape}")
v1, v2, v3 = vec[..., 0], vec[..., 1], vec[..., 2]
- zeros = zeros_like(v1)
- skew_symmetric_matrix = stack(
- [stack([zeros, -v3, v2], dim=-1), stack([v3, zeros, -v1], dim=-1), stack([-v2, v1, zeros], dim=-1)], dim=-2
+ zeros = torch.zeros_like(v1)
+ skew_symmetric_matrix = torch.stack(
+ [
+ torch.stack([zeros, -v3, v2], dim=-1),
+ torch.stack([v3, zeros, -v1], dim=-1),
+ torch.stack([-v2, v1, zeros], dim=-1),
+ ],
+ dim=-2,
)
return skew_symmetric_matrix
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 9650b91d6..1d9bcd92b 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -15,16 +15,17 @@
# limitations under the License.
#
-"""Module containing operators to work on RGB-Depth images."""
+"""nn.Module containing operators to work on RGB-Depth images."""
from __future__ import annotations
from typing import Optional
import torch
+import torch.nn.functional as F
+from torch import nn
import kornia.core as kornia_ops
-from kornia.core import Module, Tensor, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters.sobel import spatial_gradient
from kornia.utils import create_meshgrid
@@ -33,7 +34,7 @@ from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproje
from .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsics
from .linalg import convert_points_to_homogeneous, transform_points
-"""Module containing operators to work on RGB-Depth images."""
+"""nn.Module containing operators to work on RGB-Depth images."""
__all__ = [
"DepthWarper",
@@ -51,11 +52,11 @@ __all__ = [
def unproject_meshgrid(
height: int,
width: int,
- camera_matrix: Tensor,
+ camera_matrix: torch.Tensor,
normalize_points: bool = False,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
.. tip::
@@ -79,12 +80,12 @@ def unproject_meshgrid(
KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])
# create base coordinates grid
- points_uv: Tensor = create_meshgrid(
+ points_uv: torch.Tensor = create_meshgrid(
height, width, normalized_coordinates=False, device=device, dtype=dtype
).squeeze() # HxWx2
# project pixels to camera frame
- camera_matrix_tmp: Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
+ camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
points_xy = normalize_points_with_intrinsics(points_uv, camera_matrix_tmp) # HxWx2
@@ -98,8 +99,11 @@ def unproject_meshgrid(
def depth_to_3d_v2(
- depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False, xyz_grid: Optional[Tensor] = None
-) -> Tensor:
+ depth: torch.Tensor,
+ camera_matrix: torch.Tensor,
+ normalize_points: bool = False,
+ xyz_grid: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
# NOTE: when this replaces the `depth_to_3d` behaviour, a deprecated function should be added here, instead
# of just replace the other function.
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
@@ -131,7 +135,7 @@ def depth_to_3d_v2(
# create base grid if not provided
height, width = depth.shape[-2:]
- points_xyz: Tensor = xyz_grid or unproject_meshgrid(
+ points_xyz: torch.Tensor = xyz_grid or unproject_meshgrid(
height, width, camera_matrix, normalize_points, depth.device, depth.dtype
)
@@ -140,7 +144,7 @@ def depth_to_3d_v2(
return points_xyz * depth[..., None] # HxWx3
-def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
+def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
.. note::
@@ -171,23 +175,23 @@ def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = F
# create base coordinates grid
_, _, height, width = depth.shape
- points_2d: Tensor = create_meshgrid(
+ points_2d: torch.Tensor = create_meshgrid(
height, width, normalized_coordinates=False, device=depth.device, dtype=depth.dtype
) # 1xHxWx2
# depth should come in Bx1xHxW
- points_depth: Tensor = depth.permute(0, 2, 3, 1) # 1xHxWx1
+ points_depth: torch.Tensor = depth.permute(0, 2, 3, 1) # 1xHxWx1
# project pixels to camera frame
- camera_matrix_tmp: Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
- points_3d: Tensor = unproject_points(
+ camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
+ points_3d: torch.Tensor = unproject_points(
points_2d, points_depth, camera_matrix_tmp, normalize=normalize_points
) # BxHxWx3
return points_3d.permute(0, 3, 1, 2) # Bx3xHxW
-def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
+def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
"""Compute the normal surface per pixel.
Args:
@@ -212,32 +216,36 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: boo
KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])
# compute the 3d points from depth
- xyz: Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW
+ xyz: torch.Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW
# compute the pointcloud spatial gradients
- gradients: Tensor = spatial_gradient(xyz) # Bx3x2xHxW
+ gradients: torch.Tensor = spatial_gradient(xyz) # Bx3x2xHxW
# compute normals
a, b = gradients[:, :, 0], gradients[:, :, 1] # Bx3xHxW
- normals: Tensor = torch.linalg.cross(a, b, dim=1)
- return kornia_ops.normalize(normals, dim=1, p=2)
+ normals: torch.Tensor = torch.linalg.cross(a, b, dim=1)
+ return F.normalize(normals, dim=1, p=2)
def depth_from_plane_equation(
- plane_normals: Tensor, plane_offsets: Tensor, points_uv: Tensor, camera_matrix: Tensor, eps: float = 1e-8
-) -> Tensor:
+ plane_normals: torch.Tensor,
+ plane_offsets: torch.Tensor,
+ points_uv: torch.Tensor,
+ camera_matrix: torch.Tensor,
+ eps: float = 1e-8,
+) -> torch.Tensor:
"""Compute depth values from plane equations and pixel coordinates.
Args:
- plane_normals (Tensor): Plane normal vectors of shape (B, 3).
- plane_offsets (Tensor): Plane offsets of shape (B, 1).
- points_uv (Tensor): Pixel coordinates of shape (B, N, 2).
- camera_matrix (Tensor): Camera intrinsic matrix of shape (B, 3, 3).
+ plane_normals (torch.Tensor): Plane normal vectors of shape (B, 3).
+ plane_offsets (torch.Tensor): Plane offsets of shape (B, 1).
+ points_uv (torch.Tensor): Pixel coordinates of shape (B, N, 2).
+ camera_matrix (torch.Tensor): Camera intrinsic matrix of shape (B, 3, 3).
eps: epsilon for numerical stability.
Returns:
- Tensor: Computed depth values at the given pixels, shape (B, N).
+ torch.Tensor: Computed depth values at the given pixels, shape (B, N).
"""
KORNIA_CHECK_SHAPE(plane_normals, ["B", "3"])
@@ -265,8 +273,12 @@ def depth_from_plane_equation(
def warp_frame_depth(
- image_src: Tensor, depth_dst: Tensor, src_trans_dst: Tensor, camera_matrix: Tensor, normalize_points: bool = False
-) -> Tensor:
+ image_src: torch.Tensor,
+ depth_dst: torch.Tensor,
+ src_trans_dst: torch.Tensor,
+ camera_matrix: torch.Tensor,
+ normalize_points: bool = False,
+) -> torch.Tensor:
"""Warp a tensor from a source to destination frame by the depth in the destination.
Compute 3d points from the depth, transform them using given transformation, then project the point cloud to an
@@ -290,7 +302,7 @@ def warp_frame_depth(
KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])
# unproject source points to camera frame
- points_3d_dst: Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
+ points_3d_dst: torch.Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
# transform points from source to destination
points_3d_dst = points_3d_dst.permute(0, 2, 3, 1) # BxHxWx3
@@ -299,17 +311,17 @@ def warp_frame_depth(
points_3d_src = transform_points(src_trans_dst[:, None], points_3d_dst) # BxHxWx3
# project back to pixels
- camera_matrix_tmp: Tensor = camera_matrix[:, None, None] # Bx1x1xHxW
- points_2d_src: Tensor = project_points(points_3d_src, camera_matrix_tmp) # BxHxWx2
+ camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1xHxW
+ points_2d_src: torch.Tensor = project_points(points_3d_src, camera_matrix_tmp) # BxHxWx2
# normalize points between [-1 / 1]
height, width = depth_dst.shape[-2:]
- points_2d_src_norm: Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
+ points_2d_src_norm: torch.Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
- return kornia_ops.map_coordinates(image_src, points_2d_src_norm, align_corners=True)
+ return F.grid_sample(image_src, points_2d_src_norm, align_corners=True)
-class DepthWarper(Module):
+class DepthWarper(nn.Module):
r"""Warp a patch by depth.
.. math::
@@ -351,14 +363,14 @@ class DepthWarper(Module):
raise TypeError(f"Expected pinhole_dst as PinholeCamera, got {type(pinhole_dst)}")
self._pinhole_dst: PinholeCamera = pinhole_dst
self._pinhole_src: None | PinholeCamera = None
- self._dst_proj_src: None | Tensor = None
+ self._dst_proj_src: None | torch.Tensor = None
# Meshgrid only depends on (height, width), can be staticmethod cached
- self.grid: Tensor = self._create_meshgrid(height, width)
+ self.grid: torch.Tensor = self._create_meshgrid(height, width)
@staticmethod
- def _create_meshgrid(height: int, width: int) -> Tensor:
- grid: Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
+ def _create_meshgrid(height: int, width: int) -> torch.Tensor:
+ grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
return convert_points_to_homogeneous(grid) # append ones to last dim
def compute_projection_matrix(self, pinhole_src: PinholeCamera) -> DepthWarper:
@@ -405,25 +417,27 @@ class DepthWarper(Module):
self._dst_proj_src = dst_proj_src
return self
- def _compute_projection(self, x: float, y: float, invd: float) -> Tensor:
+ def _compute_projection(self, x: float, y: float, invd: float) -> torch.Tensor:
if self._dst_proj_src is None or self._pinhole_src is None:
raise ValueError("Please, call compute_projection_matrix.")
- point = tensor([[[x], [y], [invd], [1.0]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
+ point = torch.tensor(
+ [[[x], [y], [invd], [1.0]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype
+ )
flow = torch.matmul(self._dst_proj_src, point)
z = 1.0 / flow[:, 2]
_x = flow[:, 0] * z
_y = flow[:, 1] * z
- return kornia_ops.concatenate([_x, _y], 1)
+ return torch.cat([_x, _y], 1)
- def compute_subpixel_step(self) -> Tensor:
+ def compute_subpixel_step(self) -> torch.Tensor:
"""Compute the inverse depth step for sub pixel accurate sampling of the depth cost volume, per camera.
Szeliski, Richard, and Daniel Scharstein. "Symmetric sub-pixel stereo matching." European Conference on Computer
Vision. Springer Berlin Heidelberg, 2002.
"""
if self._dst_proj_src is None:
- raise RuntimeError("Expected Tensor, but got None Type from the projection matrix")
+ raise RuntimeError("Expected torch.Tensor, but got None Type from the projection matrix")
delta_d = 0.01
center_x = self.width / 2
@@ -453,7 +467,7 @@ class DepthWarper(Module):
# half pixel sampling, min for all cameras
return torch.min(0.5 / dxdd)
- def warp_grid(self, depth_src: Tensor) -> Tensor:
+ def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:
"""Compute a grid for warping a given the depth from the reference pinhole camera.
The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relative
@@ -473,23 +487,23 @@ class DepthWarper(Module):
dtype: torch.dtype = depth_src.dtype
# expand the base coordinate grid according to the input batch size
- pixel_coords: Tensor = self.grid.to(device=device, dtype=dtype).expand(batch_size, -1, -1, -1) # BxHxWx3
+ pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(batch_size, -1, -1, -1) # BxHxWx3
# reproject the pixel coordinates to the camera frame
- cam_coords_src: Tensor = pixel2cam(
+ cam_coords_src: torch.Tensor = pixel2cam(
depth_src, self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype), pixel_coords
) # BxHxWx3
# reproject the camera coordinates to the pixel
- pixel_coords_src: Tensor = cam2pixel(
+ pixel_coords_src: torch.Tensor = cam2pixel(
cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)
) # (B*N)xHxWx2
# normalize between -1 and 1 the coordinates
- pixel_coords_src_norm: Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)
+ pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)
return pixel_coords_src_norm
- def forward(self, depth_src: Tensor, patch_dst: Tensor) -> Tensor:
+ def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor:
"""Warp a tensor from destination frame to reference given the depth in the reference frame.
Args:
@@ -517,7 +531,7 @@ class DepthWarper(Module):
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- return kornia_ops.map_coordinates(
+ return F.grid_sample(
patch_dst,
self.warp_grid(depth_src),
mode=self.mode,
@@ -529,12 +543,12 @@ class DepthWarper(Module):
def depth_warp(
pinhole_dst: PinholeCamera,
pinhole_src: PinholeCamera,
- depth_src: Tensor,
- patch_dst: Tensor,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor,
height: int,
width: int,
align_corners: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
"""Warp a tensor from destination frame to reference given the depth in the reference frame.
See :class:`~kornia.geometry.warp.DepthWarper` for details.
@@ -557,11 +571,13 @@ def depth_warp(
warper = DepthWarper(pinhole_dst, height, width, align_corners=align_corners)
# projection matrix is required for each call, avoid double checking in class
warper.compute_projection_matrix(pinhole_src)
- # __call__ implemented by Module (likely calls forward, not shown).
+ # __call__ implemented by nn.Module (likely calls forward, not shown).
return warper(depth_src, patch_dst)
-def depth_from_disparity(disparity: Tensor, baseline: float | Tensor, focal: float | Tensor) -> Tensor:
+def depth_from_disparity(
+ disparity: torch.Tensor, baseline: float | torch.Tensor, focal: float | torch.Tensor
+) -> torch.Tensor:
"""Compute depth from disparity.
Args:
@@ -580,20 +596,21 @@ def depth_from_disparity(disparity: Tensor, baseline: float | Tensor, focal: flo
torch.Size([4, 1, 4, 4])
"""
- KORNIA_CHECK_IS_TENSOR(disparity, f"Input disparity type is not a Tensor. Got {type(disparity)}.")
+ KORNIA_CHECK_IS_TENSOR(disparity, f"Input disparity type is not a torch.Tensor. Got {type(disparity)}.")
KORNIA_CHECK_SHAPE(disparity, ["*", "H", "W"])
KORNIA_CHECK(
- isinstance(baseline, (float, Tensor)),
- f"Input baseline should be either a float or Tensor. Got {type(baseline)}",
+ isinstance(baseline, (float, torch.Tensor)),
+ f"Input baseline should be either a float or torch.Tensor. Got {type(baseline)}",
)
KORNIA_CHECK(
- isinstance(focal, (float, Tensor)), f"Input focal should be either a float or Tensor. Got {type(focal)}"
+ isinstance(focal, (float, torch.Tensor)),
+ f"Input focal should be either a float or torch.Tensor. Got {type(focal)}",
)
- if isinstance(baseline, Tensor):
+ if isinstance(baseline, torch.Tensor):
KORNIA_CHECK_SHAPE(baseline, ["1"])
- if isinstance(focal, Tensor):
+ if isinstance(focal, torch.Tensor):
KORNIA_CHECK_SHAPE(focal, ["1"])
return baseline * focal / (disparity + 1e-8)
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 562ee48f3..c0986cb30 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -15,13 +15,12 @@
# limitations under the License.
#
-"""Module containing functionalities for the Essential matrix."""
+"""nn.Module containing functionalities for the Essential matrix."""
from typing import Optional, Tuple
import torch
-from kornia.core import eye, ones_like, stack, where, zeros
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.geometry import solvers
from kornia.utils import eye_like, vec_like
@@ -50,9 +49,9 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
and the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].
Args:
- points1: A set of carlibrated points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+ points1: A set of carlibrated points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
Returns:
the computed essential matrix with shape :math:`(B, 3, 3)`.
@@ -67,13 +66,13 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
batch_size, _, _ = points1.shape
x1, y1 = torch.chunk(points1, dim=-1, chunks=2) # Bx1xN
x2, y2 = torch.chunk(points2, dim=-1, chunks=2) # Bx1xN
- ones = ones_like(x1)
+ ones_tensor = torch.ones_like(x1)
# build the equation system and find the null space.
# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
# [x * x', x * y', x, y * x', y * y', y, x', y', 1]
# BxNx9
- X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones], dim=-1)
+ X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones_tensor], dim=-1)
# apply the weights to the linear system
if weights is None:
@@ -115,8 +114,8 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
null_ = V[:, :, -4:] # the last four rows
nullSpace = V.transpose(-1, -2)[:, -4:, :]
- coeffs = zeros(batch_size, 10, 20, device=null_.device, dtype=null_.dtype)
- d = zeros(batch_size, 60, device=null_.device, dtype=null_.dtype)
+ coeffs = torch.zeros(batch_size, 10, 20, device=null_.device, dtype=null_.dtype)
+ d = torch.zeros(batch_size, 60, device=null_.device, dtype=null_.dtype)
# Determinant constraint
coeffs[:, 9] = (
@@ -167,7 +166,7 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
b = coeffs[:, :, 10:]
singular_filter = torch.linalg.matrix_rank(coeffs[:, :, :10]) >= torch.max(
- torch.linalg.matrix_rank(coeffs), ones_like(torch.linalg.matrix_rank(coeffs[:, :, :10])) * 10
+ torch.linalg.matrix_rank(coeffs), torch.ones_like(torch.linalg.matrix_rank(coeffs[:, :, :10])) * 10
)
# check if there is no solution
@@ -181,7 +180,7 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
# check the batch size after singular filter, for batch operation afterwards
batch_size_filtered = coeffs_.shape[0]
- A = zeros(coeffs_.shape[0], 3, 13, device=coeffs_.device, dtype=coeffs_.dtype)
+ A = torch.zeros(coeffs_.shape[0], 3, 13, device=coeffs_.device, dtype=coeffs_.dtype)
for i in range(3):
A[:, i, 0] = 0.0
@@ -200,8 +199,8 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
# A: Bx3x13
# nullSpace: Bx4x9
# companion matrices to solve the polynomial, in batch
- C = zeros((batch_size_filtered, 10, 10), device=cs.device, dtype=cs.dtype)
- eye_mat = eye(C[0, 0:-1, 0:-1].shape[0], device=cs.device, dtype=cs.dtype)
+ C = torch.zeros((batch_size_filtered, 10, 10), device=cs.device, dtype=cs.dtype)
+ eye_mat = torch.eye(C[0, 0:-1, 0:-1].shape[0], device=cs.device, dtype=cs.dtype)
C[:, 0:-1, 1:] = eye_mat
cs_de = cs[:, -1].unsqueeze(-1)
@@ -212,7 +211,7 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
roots_unsqu = roots.unsqueeze(1)
- Bs = stack(
+ Bs = torch.stack(
(
A[:, :3, :1] * (roots_unsqu**3)
+ A[:, :3, 1:2] * roots_unsqu.square()
@@ -318,14 +317,14 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch
U, _, V = _torch_svd_cast(E_mat)
Vt = V.transpose(-2, -1)
- mask = ones_like(E_mat)
+ mask = torch.ones_like(E_mat)
mask[..., -1:] *= -1.0 # fill last column with negative values
maskt = mask.transpose(-2, -1)
# avoid singularities
- U = where((torch.det(U) < 0.0)[..., None, None], U * mask, U)
- Vt = where((torch.det(Vt) < 0.0)[..., None, None], Vt * maskt, Vt)
+ U = torch.where((torch.det(U) < 0.0)[..., None, None], U * mask, U)
+ Vt = torch.where((torch.det(Vt) < 0.0)[..., None, None], Vt * maskt, Vt)
W = cross_product_matrix(torch.tensor([[0.0, 0.0, 1.0]]).type_as(E_mat))
W[..., 2, 2] += 1.0
@@ -459,8 +458,8 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tens
R1, R2, t = decompose_essential_matrix(E_mat)
# compbine and returns the four possible solutions
- Rs = stack([R1, R1, R2, R2], dim=-3)
- Ts = stack([t, -t, t, -t], dim=-3)
+ Rs = torch.stack([R1, R1, R2, R2], dim=-3)
+ Ts = torch.stack([t, -t, t, -t], dim=-3)
return Rs, Ts
@@ -610,9 +609,9 @@ def find_essential(
r"""Find essential matrices.
Args:
- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.
- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.
- weights: Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.
+ points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=5`.
+ points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=5`.
+ weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.
Returns:
the computed essential matrices with shape :math:`(B, 10, 3, 3)`.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 169d072ab..e758f0abe 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -15,13 +15,12 @@
# limitations under the License.
#
-"""Module containing the functionalities for computing the Fundamental Matrix."""
+"""nn.Module containing the functionalities for computing the Fundamental Matrix."""
from typing import Literal, Optional, Tuple
import torch
-from kornia.core import Tensor, concatenate, ones_like, stack, where, zeros
from kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
@@ -29,7 +28,7 @@ from kornia.geometry.solvers import solve_cubic
from kornia.utils.helpers import _torch_svd_cast, safe_inverse_with_mask
-def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]:
+def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Normalize points (isotropic).
Computes the transformation matrix such that the two principal moments of the set of points
@@ -40,7 +39,7 @@ def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]
the result as optimal.
Args:
- points: Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.
+ points: torch.Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.
eps: epsilon value to avoid numerical instabilities.
Returns:
@@ -58,10 +57,21 @@ def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]
scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B
scale = torch.sqrt(torch.tensor(2.0)) / (scale + eps) # B
- ones, zeros = ones_like(scale), torch.zeros_like(scale)
+ ones_tensor, zeros_tensor = torch.ones_like(scale), torch.zeros_like(scale)
- transform = stack(
- [scale, zeros, -scale * x_mean[..., 0, 0], zeros, scale, -scale * x_mean[..., 0, 1], zeros, zeros, ones], dim=-1
+ transform = torch.stack(
+ [
+ scale,
+ zeros_tensor,
+ -scale * x_mean[..., 0, 0],
+ zeros_tensor,
+ scale,
+ -scale * x_mean[..., 0, 1],
+ zeros_tensor,
+ zeros_tensor,
+ ones_tensor,
+ ],
+ dim=-1,
) # Bx9
transform = transform.view(-1, 3, 3) # Bx3x3
@@ -70,10 +80,10 @@ def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]
return points_norm, transform
-def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
+def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Normalize a given transformation matrix.
- The function trakes the transformation matrix and normalize so that the value in
+ The function trakes the transformation matrix and F.normalize so that the value in
the last row and column is one.
Args:
@@ -86,18 +96,18 @@ def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
"""
if len(M.shape) < 2:
raise AssertionError(M.shape)
- norm_val: Tensor = M[..., -1:, -1:]
- return where(norm_val.abs() > eps, M / (norm_val + eps), M)
+ norm_val: torch.Tensor = M[..., -1:, -1:]
+ return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
# Reference: Adapted from the 'run_7point' function in opencv
# https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp
-def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
+def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
r"""Compute the fundamental matrix using the 7-point algorithm.
Args:
- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
+ points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2)`.
+ points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2)`.
Returns:
the computed fundamental matrix with shape :math:`(B, 3*m, 3), Valid values of m are 1, 2 or 3`
@@ -114,10 +124,10 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # Bx1xN
x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # Bx1xN
- ones = ones_like(x1)
+ ones_tensor = torch.ones_like(x1)
# form a linear system: which represents
# the equation (x2[i], 1)*F*(x1[i], 1) = 0
- X = concatenate([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], -1) # BxNx9
+ X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones_tensor], -1) # BxNx9
# X * Fmat = 0 is singular (7 equations for 9 variables)
# solving for nullspace of X to get two F
@@ -135,7 +145,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
# form a cubic equation
# finding the coefficients of cubic polynomial (coeffs)
- coeffs = zeros((batch_size, 4), device=v.device, dtype=v.dtype)
+ coeffs = torch.zeros((batch_size, 4), device=v.device, dtype=v.dtype)
f1_det = torch.linalg.det(f1)
f2_det = torch.linalg.det(f2)
@@ -148,7 +158,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
# roots = torch.tensor(np.roots(coeffs.numpy()))
roots = solve_cubic(coeffs)
- fmatrix = zeros((batch_size, 3, 3, 3), device=v.device, dtype=v.dtype)
+ fmatrix = torch.zeros((batch_size, 3, 3, 3), device=v.device, dtype=v.dtype)
valid_root_mask = (torch.count_nonzero(roots, dim=1) < 3) | (torch.count_nonzero(roots, dim=1) > 1)
_lambda = roots
@@ -171,7 +181,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
+ f2_expanded[valid_root_mask] * _mu[valid_root_mask, :, None, None]
)
- mat_ind = zeros(3, 3, dtype=torch.bool)
+ mat_ind = torch.zeros(3, 3, dtype=torch.bool)
mat_ind[2, 2] = True
fmatrix[_s_non_zero_mask, mat_ind] = 1.0
fmatrix[~_s_non_zero_mask, mat_ind] = 0.0
@@ -186,15 +196,15 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
return normalize_transformation(fmatrix)
-def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None) -> Tensor:
+def run_8point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Compute the fundamental matrix using the DLT formulation.
The linear system is solved by using the Weighted Least Squares Solution for the 8 Points algorithm.
Args:
- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+ points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
Returns:
the computed fundamental matrix with shape :math:`(B, 3, 3)`.
@@ -216,13 +226,13 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # Bx1xN
x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # Bx1xN
- ones = ones_like(x1)
+ ones_tensor = torch.ones_like(x1)
# build equations system and solve DLT
# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
# [x * x', x * y', x, y * x', y * y', y, x', y', 1]
- X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1) # BxNx9
+ X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones_tensor], dim=-1) # BxNx9
# apply the weights to the linear system
if weights is None:
@@ -246,18 +256,21 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
def find_fundamental(
- points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None, method: Literal["8POINT", "7POINT"] = "8POINT"
-) -> Tensor:
+ points1: torch.Tensor,
+ points2: torch.Tensor,
+ weights: Optional[torch.Tensor] = None,
+ method: Literal["8POINT", "7POINT"] = "8POINT",
+) -> torch.Tensor:
r"""Find the fundamental matrix.
Args:
- points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
- points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
- weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
+ points1: A set of points in the first image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ points2: A set of points in the second image with a torch.tensor shape :math:`(B, N, 2), N>=8`.
+ weights: torch.Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
method: The method to use for computing the fundamental matrix. Supported methods are "7POINT" and "8POINT".
Returns:
- the computed fundamental matrix with shape :math:`(B, 3*m, 3)`, where `m` number of fundamental matrix.
+ the computed fundamental matrix with shape :math:`(B, 3*m, 3)`, torch.where `m` number of fundamental matrix.
Raises:
ValueError: If an invalid method is provided.
@@ -272,22 +285,23 @@ def find_fundamental(
return result
-def compute_correspond_epilines(points: Tensor, F_mat: Tensor) -> Tensor:
+def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> torch.Tensor:
r"""Compute the corresponding epipolar line for a given set of points.
Args:
- points: tensor containing the set of points to project in the shape of :math:`(*, N, 2)` or :math:`(*, N, 3)`.
+ points: torch.tensor containing the set of points to project in the shape of :math:`(*, N, 2)`
+ or :math:`(*, N, 3)`.
F_mat: the fundamental to use for projection the points in the shape of :math:`(*, 3, 3)`.
Returns:
- a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
+ a torch.tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
lines corresponding to the points to the other image. Each line is described as
:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
"""
KORNIA_CHECK_SHAPE(points, ["*", "N", "DIM"])
if points.shape[-1] == 2:
- points_h: Tensor = convert_points_to_homogeneous(points)
+ points_h: torch.Tensor = convert_points_to_homogeneous(points)
elif points.shape[-1] == 3:
points_h = points
else:
@@ -298,22 +312,22 @@ def compute_correspond_epilines(points: Tensor, F_mat: Tensor) -> Tensor:
a, b, c = torch.chunk(F_mat @ points_h, dim=-2, chunks=3)
# compute normal and compose equation line
- nu: Tensor = a * a + b * b
- nu = where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
+ nu: torch.Tensor = a * a + b * b
+ nu = torch.where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
line = torch.cat([a * nu, b * nu, c * nu], dim=-2) # *x3xN
return torch.transpose(line, dim0=-2, dim1=-1) # *xNx3
-def get_perpendicular(lines: Tensor, points: Tensor) -> Tensor:
+def get_perpendicular(lines: torch.Tensor, points: torch.Tensor) -> torch.Tensor:
r"""Compute the perpendicular to a line, through the point.
Args:
- lines: tensor containing the set of lines :math:`(*, N, 3)`.
- points: tensor containing the set of points :math:`(*, N, 2)`.
+ lines: torch.tensor containing the set of lines :math:`(*, N, 3)`.
+ points: torch.tensor containing the set of points :math:`(*, N, 2)`.
Returns:
- a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
+ a torch.tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
perpendicular lines. Each line is described as
:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
@@ -321,17 +335,17 @@ def get_perpendicular(lines: Tensor, points: Tensor) -> Tensor:
KORNIA_CHECK_SHAPE(lines, ["*", "N", "3"])
KORNIA_CHECK_SHAPE(points, ["*", "N", "two"])
if points.shape[2] == 2:
- points_h: Tensor = convert_points_to_homogeneous(points)
+ points_h: torch.Tensor = convert_points_to_homogeneous(points)
elif points.shape[2] == 3:
points_h = points
else:
raise AssertionError(points.shape)
infinity_point = lines * torch.tensor([1, 1, 0], dtype=lines.dtype, device=lines.device).view(1, 1, 3)
- perp: Tensor = torch.linalg.cross(points_h, infinity_point, dim=2)
+ perp: torch.Tensor = torch.linalg.cross(points_h, infinity_point, dim=2)
return perp
-def get_closest_point_on_epipolar_line(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:
+def get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor) -> torch.Tensor:
"""Return closest point on the epipolar line to the correspondence, given the fundamental matrix.
Args:
@@ -345,10 +359,10 @@ def get_closest_point_on_epipolar_line(pts1: Tensor, pts2: Tensor, Fm: Tensor) -
point on epipolar line :math:`(*, N, 2)`.
"""
- if not isinstance(Fm, Tensor):
+ if not isinstance(Fm, torch.Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):
- raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")
+ raise ValueError(f"Fm must be a (*, 3, 3) torch.tensor. Got {Fm.shape}")
if pts1.shape[-1] == 2:
pts1 = convert_points_to_homogeneous(pts1)
if pts2.shape[-1] == 2:
@@ -360,7 +374,7 @@ def get_closest_point_on_epipolar_line(pts1: Tensor, pts2: Tensor, Fm: Tensor) -
return points1_in_2
-def fundamental_from_essential(E_mat: Tensor, K1: Tensor, K2: Tensor) -> Tensor:
+def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:
r"""Get the Fundamental matrix from Essential and camera matrices.
Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).
@@ -385,10 +399,11 @@ def fundamental_from_essential(E_mat: Tensor, K1: Tensor, K2: Tensor) -> Tensor:
# adapted from:
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L109
-# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/src/openMVG/multiview/projection.cpp#L134
+# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/
+# src/openMVG/multiview/projection.cpp#L134
-def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:
+def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tensor:
r"""Get the Fundamental matrix from Projection matrices.
Args:
@@ -404,8 +419,8 @@ def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:
if P1.shape[:-2] != P2.shape[:-2]:
raise AssertionError
- def vstack(x: Tensor, y: Tensor) -> Tensor:
- return concatenate([x, y], dim=-2)
+ def vstack(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ return torch.cat([x, y], dim=-2)
input_dtype = P1.dtype
if input_dtype not in (torch.float32, torch.float64):
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 1243c6b2b..b208854a8 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -15,11 +15,9 @@
# limitations under the License.
#
-"""Module containing numerical functionalities for SfM."""
-
import torch
-from kornia.core import stack, zeros_like
+"""nn.Module containing numerical functionalities for SfM."""
def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
@@ -40,8 +38,8 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
x2 = x[..., 2]
# construct the matrix, reshape to 3x3 and return
- zeros = zeros_like(x0)
- cross_product_matrix_flat = stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)
+ zeros = torch.zeros_like(x0)
+ cross_product_matrix_flat = torch.stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)
shape_ = x.shape[:-1] + (3, 3)
return cross_product_matrix_flat.view(*shape_)
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 81c338bd4..d08ffbd20 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -15,14 +15,14 @@
# limitations under the License.
#
-"""Module for image projections."""
+"""nn.Module for image projections."""
from typing import Tuple, Union
import torch
+import torch.nn.functional as F
from torch.linalg import qr as linalg_qr
-from kornia.core import Tensor, concatenate, pad, stack
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.utils import eye_like, vec_like
from kornia.utils.helpers import _torch_svd_cast
@@ -30,15 +30,15 @@ from kornia.utils.helpers import _torch_svd_cast
from .numeric import cross_product_matrix
-def intrinsics_like(focal: float, input: Tensor) -> Tensor:
+def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
r"""Return a 3x3 intrinsics matrix, with same size as the input.
The center of projection will be based in the input image size.
Args:
focal: the focal length for the camera matrix.
- input: image tensor that will determine the batch size and image height
- and width. It is assumed to be a tensor in the shape of :math:`(B, C, H, W)`.
+ input: image torch.tensor that will determine the batch size and image height
+ and width. It is assumed to be a torch.tensor in the shape of :math:`(B, C, H, W)`.
Returns:
The camera matrix with the shape of :math:`(B, 3, 3)`.
@@ -59,7 +59,7 @@ def intrinsics_like(focal: float, input: Tensor) -> Tensor:
return intrinsics
-def random_intrinsics(low: Union[float, Tensor], high: Union[float, Tensor]) -> Tensor:
+def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Generate a random camera matrix based on a given uniform distribution.
Args:
@@ -77,14 +77,14 @@ def random_intrinsics(low: Union[float, Tensor], high: Union[float, Tensor]) ->
return camera_matrix.unsqueeze(0)
-def scale_intrinsics(camera_matrix: Tensor, scale_factor: Union[float, Tensor]) -> Tensor:
+def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Scale a camera matrix containing the intrinsics.
Applies the scaling factor to the focal length and center of projection.
Args:
camera_matrix: the camera calibration matrix containing the intrinsic
- parameters. The expected shape for the tensor is :math:`(B, 3, 3)`.
+ parameters. The expected shape for the torch.tensor is :math:`(B, 3, 3)`.
scale_factor: the scaling factor to be applied.
Returns:
@@ -99,7 +99,7 @@ def scale_intrinsics(camera_matrix: Tensor, scale_factor: Union[float, Tensor])
return K_scale
-def projection_from_KRt(K: Tensor, R: Tensor, t: Tensor) -> Tensor:
+def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
r"""Get the projection matrix P from K, R and t.
This function estimate the projection matrix by solving the following equation: :math:`P = K * [R|t]`.
@@ -119,17 +119,17 @@ def projection_from_KRt(K: Tensor, R: Tensor, t: Tensor) -> Tensor:
if not len(K.shape) == len(R.shape) == len(t.shape):
raise AssertionError
- Rt = concatenate([R, t], dim=-1) # 3x4
- Rt_h = pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
+ Rt = torch.cat([R, t], dim=-1) # 3x4
+ Rt_h = F.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
Rt_h[..., -1, -1] += 1.0
- K_h = pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4
+ K_h = F.pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4
K_h[..., -1, -1] += 1.0
return K @ Rt
-def KRt_from_projection(P: Tensor, eps: float = 1e-6) -> Tuple[Tensor, Tensor, Tensor]:
+def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Decompose the Projection matrix into Camera-Matrix, Rotation Matrix and Translation vector.
Args:
@@ -165,7 +165,7 @@ def KRt_from_projection(P: Tensor, eps: float = 1e-6) -> Tuple[Tensor, Tensor, T
return K, R, t
-def depth_from_point(R: Tensor, t: Tensor, X: Tensor) -> Tensor:
+def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
r"""Return the depth of a point transformed by a rigid transform.
Args:
@@ -185,7 +185,7 @@ def depth_from_point(R: Tensor, t: Tensor, X: Tensor) -> Tensor:
# adapted from:
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L61
# https://github.com/mapillary/OpenSfM/blob/master/opensfm/multiview.py#L14
-def _nullspace(A: Tensor) -> Tuple[Tensor, Tensor]:
+def _nullspace(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute the null space of A.
Return the smallest singular value and the corresponding vector.
@@ -194,7 +194,7 @@ def _nullspace(A: Tensor) -> Tuple[Tensor, Tensor]:
return s[..., -1], v[..., -1]
-def projections_from_fundamental(F_mat: Tensor) -> Tensor:
+def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
r"""Get the projection matrices from the Fundamental Matrix.
Args:
@@ -219,4 +219,4 @@ def projections_from_fundamental(F_mat: Tensor) -> Tensor:
P1 = torch.cat([R1, t1], dim=-1) # Bx3x4
P2 = torch.cat([R2, t2], dim=-1) # Bx3x4
- return stack([P1, P2], dim=-1)
+ return torch.stack([P1, P2], dim=-1)
diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.py
index 22eb82cf3..7c82d2c9d 100644
--- a/kornia/geometry/epipolar/scene.py
+++ b/kornia/geometry/epipolar/scene.py
@@ -15,14 +15,13 @@
# limitations under the License.
#
-"""Module to generate synthetic 3d scenes."""
+"""nn.Module to generate synthetic 3d scenes."""
import math
from typing import Dict
import torch
-from kornia.core import rand, stack, where
from kornia.geometry.conversions import axis_angle_to_rotation_matrix
from kornia.geometry.linalg import transform_points
@@ -32,7 +31,7 @@ from .projection import projection_from_KRt, random_intrinsics
def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
"""Generate 3d scene."""
# Generate the 3d points
- points3d = rand(1, num_points, 3) # NxMx3
+ points3d = torch.rand(1, num_points, 3) # NxMx3
# Create random camera matrix
K = random_intrinsics(0.0, 100.0) # 1x3x3
@@ -49,12 +48,12 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
tx = torch.empty(num_views).uniform_(-0.5, 0.5)
ty = torch.empty(num_views).uniform_(-0.5, 0.5)
tz = torch.empty(num_views).uniform_(-1.0, 2.0)
- tvec = stack([tx, ty, tz], dim=1)[..., None]
+ tvec = torch.stack([tx, ty, tz], dim=1)[..., None]
# Make sure the shape is in front of the camera
points3d_trans = (rot_mat @ points3d.transpose(-2, -1)) + tvec
min_dist = torch.min(points3d_trans[:, 2], dim=1)[0]
- tvec[:, 2, 0] = where(min_dist < 0, tz - min_dist + 1.0, tz)
+ tvec[:, 2, 0] = torch.where(min_dist < 0, tz - min_dist + 1.0, tz)
# compute projection matrices
P = projection_from_KRt(K, rot_mat, tvec)
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 04d7ff235..6656b0206 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -15,11 +15,10 @@
# limitations under the License.
#
-"""Module with the functionalities for triangulation."""
+"""nn.Module with the functionalities for triangulation."""
import torch
-from kornia.core import zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous
from kornia.utils.helpers import _torch_svd_cast
@@ -57,7 +56,7 @@ def triangulate_points(
# allocate and construct the equations matrix with shape (*, 4, 4)
points_shape = max(points1.shape, points2.shape) # this allows broadcasting
- X = zeros(points_shape[:-1] + (4, 4)).type_as(points1)
+ X = torch.zeros(points_shape[:-1] + (4, 4)).type_as(points1)
for i in range(4):
X[..., 0, i] = points1[..., 0] * P1[..., 2:3, i] - P1[..., 0:1, i]
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 3f455d384..713b92859 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -20,7 +20,6 @@ from typing import Optional, Tuple
import torch
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
from kornia.utils.helpers import _torch_svd_cast
@@ -29,10 +28,12 @@ from .conversions import convert_points_from_homogeneous, convert_points_to_homo
from .epipolar import normalize_points
from .linalg import transform_points
-TupleTensor = Tuple[Tensor, Tensor]
+TupleTensor = Tuple[torch.Tensor, torch.Tensor]
-def oneway_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: bool = True, eps: float = 1e-8) -> Tensor:
+def oneway_transfer_error(
+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
r"""Return transfer error in image 2 for correspondences given the homography matrix.
Args:
@@ -58,14 +59,16 @@ def oneway_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: bool =
# From Hartley and Zisserman, Error in one image (4.6)
# dist = \sum_{i} ( d(x', Hx)**2)
- pts1_in_2: Tensor = transform_points(H, pts1)
- error_squared: Tensor = (pts1_in_2 - pts2).pow(2).sum(dim=-1)
+ pts1_in_2: torch.Tensor = transform_points(H, pts1)
+ error_squared: torch.Tensor = (pts1_in_2 - pts2).pow(2).sum(dim=-1)
if squared:
return error_squared
return (error_squared + eps).sqrt()
-def symmetric_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: bool = True, eps: float = 1e-8) -> Tensor:
+def symmetric_transfer_error(
+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
r"""Return Symmetric transfer error for correspondences given the homography matrix.
Args:
@@ -93,16 +96,18 @@ def symmetric_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: boo
# dist = \sum_{i} (d(x, H^-1 x')**2 + d(x', Hx)**2)
H_inv, good_H = safe_inverse_with_mask(H)
- there: Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)
- back: Tensor = oneway_transfer_error(pts2, pts1, H_inv, True, eps)
- good_H_reshape: Tensor = good_H.view(-1, 1).expand_as(there)
+ there: torch.Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)
+ back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv, True, eps)
+ good_H_reshape: torch.Tensor = good_H.view(-1, 1).expand_as(there)
out = (there + back) * good_H_reshape.to(there.dtype) + max_num * (~good_H_reshape).to(there.dtype)
if squared:
return out
return (out + eps).sqrt()
-def line_segment_transfer_error_one_way(ls1: Tensor, ls2: Tensor, H: Tensor, squared: bool = False) -> Tensor:
+def line_segment_transfer_error_one_way(
+ ls1: torch.Tensor, ls2: torch.Tensor, H: torch.Tensor, squared: bool = False
+) -> torch.Tensor:
r"""Return transfer error in image 2 for line segment correspondences given the homography matrix.
Line segment end points are reprojected into image 2, and point-to-line error is calculated w.r.t. line,
@@ -214,8 +219,8 @@ def find_homography_dlt(
def find_homography_dlt_iterated(
- points1: Tensor, points2: Tensor, weights: Tensor, soft_inl_th: float = 3.0, n_iter: int = 5
-) -> Tensor:
+ points1: torch.Tensor, points2: torch.Tensor, weights: torch.Tensor, soft_inl_th: float = 3.0, n_iter: int = 5
+) -> torch.Tensor:
r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS).
The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.
@@ -232,15 +237,15 @@ def find_homography_dlt_iterated(
the computed homography matrix with shape :math:`(B, 3, 3)`.
"""
- H: Tensor = find_homography_dlt(points1, points2, weights)
+ H: torch.Tensor = find_homography_dlt(points1, points2, weights)
for _ in range(n_iter - 1):
- errors: Tensor = symmetric_transfer_error(points1, points2, H, False)
- weights_new: Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))
+ errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, False)
+ weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))
H = find_homography_dlt(points1, points2, weights_new)
return H
-def sample_is_valid_for_homography(points1: Tensor, points2: Tensor) -> Tensor:
+def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:
"""Implement oriented constraint check from :cite:`Marquez-Neila2015`.
Analogous to https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/usac/degeneracy.cpp#L88
@@ -277,7 +282,9 @@ def sample_is_valid_for_homography(points1: Tensor, points2: Tensor) -> Tensor:
return sample_is_valid
-def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor] = None) -> Tensor:
+def find_homography_lines_dlt(
+ ls1: torch.Tensor, ls2: torch.Tensor, weights: Optional[torch.Tensor] = None
+) -> torch.Tensor:
"""Compute the homography matrix using the DLT formulation for line correspondences.
See :cite:`homolines2001` for details.
@@ -349,8 +356,8 @@ def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor
def find_homography_lines_dlt_iterated(
- ls1: Tensor, ls2: Tensor, weights: Tensor, soft_inl_th: float = 4.0, n_iter: int = 5
-) -> Tensor:
+ ls1: torch.Tensor, ls2: torch.Tensor, weights: torch.Tensor, soft_inl_th: float = 4.0, n_iter: int = 5
+) -> torch.Tensor:
r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS) from line segments.
The linear system is solved by using the Reweighted Least Squares Solution for the 4 line segments algorithm.
@@ -367,9 +374,9 @@ def find_homography_lines_dlt_iterated(
the computed homography matrix with shape :math:`(B, 3, 3)`.
"""
- H: Tensor = find_homography_lines_dlt(ls1, ls2, weights)
+ H: torch.Tensor = find_homography_lines_dlt(ls1, ls2, weights)
for _ in range(n_iter - 1):
- errors: Tensor = line_segment_transfer_error_one_way(ls1, ls2, H, False)
- weights_new: Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))
+ errors: torch.Tensor = line_segment_transfer_error_one_way(ls1, ls2, H, False)
+ weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))
H = find_homography_lines_dlt(ls1, ls2, weights_new)
return H
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 4a0095ac1..0875b8f92 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -20,13 +20,12 @@ from typing import List, Optional, Tuple, Union, cast
import torch
from torch import Size
-from kornia.core import Tensor
from kornia.geometry import transform_points
__all__ = ["Keypoints", "Keypoints3D"]
-def _merge_keypoint_list(keypoints: List[Tensor]) -> Tensor:
+def _merge_keypoint_list(keypoints: List[torch.torch.Tensor]) -> torch.torch.Tensor:
raise NotImplementedError
@@ -34,19 +33,21 @@ class Keypoints:
"""2D Keypoints containing Nx2 or BxNx2 points.
Args:
- keypoints: Raw tensor or a list of Tensors with the Nx2 coordinates
- raise_if_not_floating_point: will raise if the Tensor isn't float
+ keypoints: Raw tensor or a list of torch.Tensors with the Nx2 coordinates
+ raise_if_not_floating_point: will raise if the torch.Tensor isn't float
"""
- def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
+ def __init__(
+ self, keypoints: Union[torch.torch.Tensor, List[torch.torch.Tensor]], raise_if_not_floating_point: bool = True
+ ) -> None:
self._N: Optional[List[int]] = None
if isinstance(keypoints, list):
keypoints, self._N = _merge_keypoint_list(keypoints)
- if not isinstance(keypoints, Tensor):
- raise TypeError(f"Input keypoints is not a Tensor. Got: {type(keypoints)}.")
+ if not isinstance(keypoints, torch.torch.Tensor):
+ raise TypeError(f"Input keypoints is not a torch.Tensor. Got: {type(keypoints)}.")
if not keypoints.is_floating_point():
if raise_if_not_floating_point:
@@ -66,11 +67,11 @@ class Keypoints:
self._data = keypoints
- def __getitem__(self, key: Union[slice, int, Tensor]) -> "Keypoints":
+ def __getitem__(self, key: Union[slice, int, torch.torch.Tensor]) -> "Keypoints":
new_obj = type(self)(self._data[key], False)
return new_obj
- def __setitem__(self, key: Union[slice, int, Tensor], value: "Keypoints") -> "Keypoints":
+ def __setitem__(self, key: Union[slice, int, torch.torch.Tensor], value: "Keypoints") -> "Keypoints":
self._data[key] = value._data
return self
@@ -79,7 +80,7 @@ class Keypoints:
return self.data.shape
@property
- def data(self) -> Tensor:
+ def data(self) -> torch.torch.Tensor:
return self._data
@property
@@ -94,8 +95,8 @@ class Keypoints:
def index_put(
self,
- indices: Union[Tuple[Tensor, ...], List[Tensor]],
- values: Union[Tensor, "Keypoints"],
+ indices: Union[Tuple[torch.torch.Tensor, ...], List[torch.torch.Tensor]],
+ values: Union[torch.torch.Tensor, "Keypoints"],
inplace: bool = False,
) -> "Keypoints":
if inplace:
@@ -115,7 +116,7 @@ class Keypoints:
obj._data = _data
return obj
- def pad(self, padding_size: Tensor) -> "Keypoints":
+ def pad(self, padding_size: torch.torch.Tensor) -> "Keypoints":
"""Pad a bounding keypoints.
Args:
@@ -128,7 +129,7 @@ class Keypoints:
self._data[..., 1] += padding_size[..., 2:3] # top padding
return self
- def unpad(self, padding_size: Tensor) -> "Keypoints":
+ def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints":
"""Pad a bounding keypoints.
Args:
@@ -141,7 +142,7 @@ class Keypoints:
self._data[..., 1] -= padding_size[..., 2:3] # top padding
return self
- def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "Keypoints":
+ def transform_keypoints(self, M: torch.torch.Tensor, inplace: bool = False) -> "Keypoints":
r"""Apply a transformation matrix to the 2D keypoints.
Args:
@@ -162,15 +163,15 @@ class Keypoints:
return Keypoints(transformed_boxes, False)
- def transform_keypoints_(self, M: Tensor) -> "Keypoints":
+ def transform_keypoints_(self, M: torch.torch.Tensor) -> "Keypoints":
"""Inplace version of :func:`Keypoints.transform_keypoints`."""
return self.transform_keypoints(M, inplace=True)
@classmethod
- def from_tensor(cls, keypoints: Tensor) -> "Keypoints":
+ def from_tensor(cls, keypoints: torch.torch.Tensor) -> "Keypoints":
return cls(keypoints)
- def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
+ def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:
r"""Cast :class:`Keypoints` to a tensor.
``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.
@@ -199,7 +200,9 @@ class VideoKeypoints(Keypoints):
temporal_channel_size: int
@classmethod
- def from_tensor(cls, boxes: Union[Tensor, List[Tensor]], validate_boxes: bool = True) -> "VideoKeypoints":
+ def from_tensor(
+ cls, boxes: Union[torch.torch.Tensor, List[torch.torch.Tensor]], validate_boxes: bool = True
+ ) -> "VideoKeypoints":
if isinstance(boxes, (list,)) or (boxes.dim() != 4 or boxes.shape[-1] != 2):
raise ValueError("Input box type is not yet supported. Please input an `BxTxNx2` tensor directly.")
@@ -211,12 +214,12 @@ class VideoKeypoints(Keypoints):
out.temporal_channel_size = temporal_channel_size
return out
- def to_tensor(self) -> Tensor: # type: ignore[override]
+ def to_tensor(self) -> torch.torch.Tensor: # type: ignore[override]
out = super().to_tensor(as_padded_sequence=False)
- out = cast(Tensor, out)
+ out = cast(torch.torch.Tensor, out)
return out.view(-1, self.temporal_channel_size, *out.shape[1:])
- def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "VideoKeypoints":
+ def transform_keypoints(self, M: torch.torch.Tensor, inplace: bool = False) -> "VideoKeypoints":
out = super().transform_keypoints(M, inplace=inplace)
if inplace:
return self
@@ -234,19 +237,21 @@ class Keypoints3D:
"""3D Keypoints containing Nx3 or BxNx3 points.
Args:
- keypoints: Raw tensor or a list of Tensors with the Nx3 coordinates
- raise_if_not_floating_point: will raise if the Tensor isn't float
+ keypoints: Raw tensor or a list of torch.Tensors with the Nx3 coordinates
+ raise_if_not_floating_point: will raise if the torch.Tensor isn't float
"""
- def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
+ def __init__(
+ self, keypoints: Union[torch.torch.Tensor, List[torch.torch.Tensor]], raise_if_not_floating_point: bool = True
+ ) -> None:
self._N: Optional[List[int]] = None
if isinstance(keypoints, list):
keypoints, self._N = _merge_keypoint_list(keypoints)
- if not isinstance(keypoints, Tensor):
- raise TypeError(f"Input keypoints is not a Tensor. Got: {type(keypoints)}.")
+ if not isinstance(keypoints, torch.torch.Tensor):
+ raise TypeError(f"Input keypoints is not a torch.Tensor. Got: {type(keypoints)}.")
if not keypoints.is_floating_point():
if raise_if_not_floating_point:
@@ -266,11 +271,11 @@ class Keypoints3D:
self._data = keypoints
- def __getitem__(self, key: Union[slice, int, Tensor]) -> "Keypoints3D":
+ def __getitem__(self, key: Union[slice, int, torch.Tensor]) -> "Keypoints3D":
new_obj = type(self)(self._data[key], False)
return new_obj
- def __setitem__(self, key: Union[slice, int, Tensor], value: "Keypoints3D") -> "Keypoints3D":
+ def __setitem__(self, key: Union[slice, int, torch.Tensor], value: "Keypoints3D") -> "Keypoints3D":
self._data[key] = value._data
return self
@@ -279,10 +284,10 @@ class Keypoints3D:
return self.data.shape
@property
- def data(self) -> Tensor:
+ def data(self) -> torch.torch.Tensor:
return self._data
- def pad(self, padding_size: Tensor) -> "Keypoints3D":
+ def pad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":
"""Pad a bounding keypoints.
Args:
@@ -291,7 +296,7 @@ class Keypoints3D:
"""
raise NotImplementedError
- def unpad(self, padding_size: Tensor) -> "Keypoints3D":
+ def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":
"""Pad a bounding keypoints.
Args:
@@ -300,7 +305,7 @@ class Keypoints3D:
"""
raise NotImplementedError
- def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "Keypoints3D":
+ def transform_keypoints(self, M: torch.Tensor, inplace: bool = False) -> "Keypoints3D":
r"""Apply a transformation matrix to the 2D keypoints.
Args:
@@ -313,15 +318,15 @@ class Keypoints3D:
"""
raise NotImplementedError
- def transform_keypoints_(self, M: Tensor) -> "Keypoints3D":
+ def transform_keypoints_(self, M: torch.Tensor) -> "Keypoints3D":
"""Inplace version of :func:`Keypoints.transform_keypoints`."""
return self.transform_keypoints(M, inplace=True)
@classmethod
- def from_tensor(cls, keypoints: Tensor) -> "Keypoints3D":
+ def from_tensor(cls, keypoints: torch.Tensor) -> "Keypoints3D":
return cls(keypoints)
- def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
+ def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:
r"""Cast :class:`Keypoints` to a tensor.
``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.
diff --git a/kornia/geometry/liegroup/_utils.py b/kornia/geometry/liegroup/_utils.py
index 3efadae1f..95daff3b4 100644
--- a/kornia/geometry/liegroup/_utils.py
+++ b/kornia/geometry/liegroup/_utils.py
@@ -14,26 +14,41 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import torch
-from kornia.core import Tensor
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
# TODO: Temporary shape check functions until KORNIA_CHECK_SHAPE is ready
-def check_so2_z_shape(z: Tensor) -> None:
+def check_so2_z_shape(z: torch.Tensor) -> None:
z_shape = z.shape
len_z_shape = len(z_shape)
if (len_z_shape == 2 and z_shape[1] != 1) or (len_z_shape == 0 and not z.numel()) or (len_z_shape > 2):
raise ValueError(f"Invalid input size, we expect [B]. Got: {z.shape}")
-def check_so2_t_shape(t: Tensor) -> None:
+def check_so2_t_shape(t: torch.Tensor) -> None:
t_shape = t.shape
len_t_shape = len(t_shape)
if ((len_t_shape == 2) and (t_shape[1] != 2)) or ((len_t_shape == 1) and (t_shape[0] != 2)) or (len_t_shape > 2):
raise ValueError(f"Invalid translation shape, we expect [B, 2], or [2] Got: {t_shape}")
-def check_so2_theta_shape(theta: Tensor) -> None:
+def check_so2_theta_shape(theta: torch.Tensor) -> None:
theta_shape = theta.shape
len_theta_shape = len(theta_shape)
if (
@@ -44,7 +59,7 @@ def check_so2_theta_shape(theta: Tensor) -> None:
raise ValueError(f"Invalid input size, we expect [B]. Got: {theta_shape}")
-def check_so2_matrix_shape(matrix: Tensor) -> None:
+def check_so2_matrix_shape(matrix: torch.Tensor) -> None:
matrix_shape = matrix.shape
len_matrix_shape = len(matrix_shape)
if (
@@ -55,24 +70,24 @@ def check_so2_matrix_shape(matrix: Tensor) -> None:
raise ValueError(f"Invalid input size, we expect [B, 2, 2] or [2, 2]. Got: {matrix_shape}")
-def check_so2_matrix(matrix: Tensor) -> None:
+def check_so2_matrix(matrix: torch.Tensor) -> None:
for m in matrix.reshape(-1, 2, 2):
if m[0, 0] != m[1, 1] or m[0, 1] != -m[1, 0]:
raise ValueError("Invalid rotation matrix")
-def check_se2_t_shape(t: Tensor) -> None:
+def check_se2_t_shape(t: torch.Tensor) -> None:
check_so2_t_shape(t)
-def check_v_shape(v: Tensor) -> None:
+def check_v_shape(v: torch.Tensor) -> None:
v_shape = v.shape
len_v_shape = len(v_shape)
if ((len_v_shape == 2) and (v_shape[1] != 3)) or ((len_v_shape == 1) and (v_shape[0] != 3)) or (len_v_shape > 3):
raise ValueError(f"Invalid input shape, we expect [B, 3], [3] Got: {v_shape}")
-def check_se2_omega_shape(matrix: Tensor) -> None:
+def check_se2_omega_shape(matrix: torch.Tensor) -> None:
matrix_shape = matrix.shape
len_matrix_shape = len(matrix_shape)
if (
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 284af6ae8..c62067d06 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -19,29 +19,19 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se2.py
from __future__ import annotations
-from typing import Optional, overload
-
-from kornia.core import (
- Device,
- Dtype,
- Module,
- Parameter,
- Tensor,
- concatenate,
- pad,
- rand,
- stack,
- tensor,
- where,
- zeros_like,
-)
+from typing import Optional, Union, overload
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_t_shape, check_v_shape
from kornia.geometry.liegroup.so2 import So2
from kornia.geometry.vector import Vector2
-def _check_se2_r_t_shape(r: So2, t: Tensor) -> None:
+def _check_se2_r_t_shape(r: So2, t: torch.Tensor) -> None:
z_shape = r.z.shape
if ((len(z_shape) == 1) and (len(t.shape) == 2)) or ((len(z_shape) == 0) and len(t.shape) == 1):
check_se2_t_shape(t)
@@ -51,7 +41,7 @@ def _check_se2_r_t_shape(r: So2, t: Tensor) -> None:
)
-class Se2(Module):
+class Se2(nn.Module):
r"""Base class to represent the Se2 group.
The SE(2) is the group of rigid body transformations about the origin of two-dimensional Euclidean
@@ -70,10 +60,10 @@ class Se2(Module):
"""
- def __init__(self, rotation: So2, translation: Vector2 | Tensor) -> None:
+ def __init__(self, rotation: So2, translation: Vector2 | torch.Tensor) -> None:
"""Construct the base class.
- Internally represented by a complex number `z` and a translation 2-vector.
+ Internally represented by a torch.complex number `z` and a translation 2-vector.
Args:
rotation: So2 group encompassing a rotation.
@@ -93,14 +83,14 @@ class Se2(Module):
super().__init__()
KORNIA_CHECK_TYPE(rotation, So2)
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- # KORNIA_CHECK_TYPE(translation, (Vector3, Tensor))
- if not isinstance(translation, (Vector2, Tensor)):
+ # KORNIA_CHECK_TYPE(translation, (Vector3, torch.Tensor))
+ if not isinstance(translation, (Vector2, torch.Tensor)):
raise TypeError(f"translation type is {type(translation)}")
- self._translation: Vector2 | Parameter
+ self._translation: Vector2 | nn.Parameter
self._rotation: So2 = rotation
- if isinstance(translation, Tensor):
+ if isinstance(translation, torch.Tensor):
_check_se2_r_t_shape(rotation, translation) # TODO remove
- self._translation = Parameter(translation)
+ self._translation = nn.Parameter(translation)
else:
self._translation = translation
@@ -121,9 +111,9 @@ class Se2(Module):
def __mul__(self, right: Se2) -> Se2: ...
@overload
- def __mul__(self, right: Tensor) -> Tensor: ...
+ def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...
- def __mul__(self, right: Se2 | Tensor) -> Se2 | Tensor:
+ def __mul__(self, right: Se2 | torch.Tensor) -> Se2 | torch.Tensor:
"""Compose two Se2 transformations.
Args:
@@ -138,7 +128,7 @@ class Se2(Module):
if isinstance(right, Se2):
KORNIA_CHECK_TYPE(right, Se2)
return self._mul_se2(right)
- elif isinstance(right, (Vector2, Tensor)):
+ elif isinstance(right, (Vector2, torch.Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
# _check_se2_r_t_shape(so2, risght)
return so2 * right + t
@@ -156,7 +146,7 @@ class Se2(Module):
return self._rotation
@property
- def t(self) -> Vector2 | Parameter:
+ def t(self) -> Vector2 | nn.Parameter:
"""Return the underlying translation vector of shape :math:`(B,2)`."""
return self._translation
@@ -166,12 +156,12 @@ class Se2(Module):
return self._rotation
@property
- def translation(self) -> Vector2 | Parameter:
+ def translation(self) -> Vector2 | nn.Parameter:
"""Return the underlying translation vector of shape :math:`(B,2)`."""
return self._translation
@staticmethod
- def exp(v: Tensor) -> Se2:
+ def exp(v: torch.Tensor) -> Se2:
"""Convert elements of lie algebra to elements of lie group.
Args:
@@ -191,16 +181,16 @@ class Se2(Module):
check_v_shape(v)
theta = v[..., 2]
so2 = So2.exp(theta)
- z = tensor(0.0, device=v.device, dtype=v.dtype)
+ z = torch.tensor(0.0, device=v.device, dtype=v.dtype)
theta_nonzeros = theta != 0.0
- a = where(theta_nonzeros, so2.z.imag / theta, z)
- b = where(theta_nonzeros, (1.0 - so2.z.real) / theta, z)
+ a = torch.where(theta_nonzeros, so2.z.imag / theta, z)
+ b = torch.where(theta_nonzeros, (1.0 - so2.z.real) / theta, z)
x = v[..., 0]
y = v[..., 1]
- t = stack((a * x - b * y, b * x + a * y), -1)
+ t = torch.stack((a * x - b * y, b * x + a * y), -1)
return Se2(so2, t)
- def log(self) -> Tensor:
+ def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
Example:
@@ -213,17 +203,19 @@ class Se2(Module):
theta = self.so2.log()
half_theta = 0.5 * theta
denom = self.so2.z.real - 1
- a = where(
- denom != 0, -(half_theta * self.so2.z.imag) / denom, tensor(0.0, device=theta.device, dtype=theta.dtype)
+ a = torch.where(
+ denom != 0,
+ -(half_theta * self.so2.z.imag) / denom,
+ torch.tensor(0.0, device=theta.device, dtype=theta.dtype),
)
- row0 = stack((a, half_theta), -1)
- row1 = stack((-half_theta, a), -1)
- V_inv = stack((row0, row1), -2)
+ row0 = torch.stack((a, half_theta), -1)
+ row1 = torch.stack((-half_theta, a), -1)
+ V_inv = torch.stack((row0, row1), -2)
upsilon = V_inv @ self.t.data[..., None]
- return stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)
+ return torch.stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)
@staticmethod
- def hat(v: Tensor) -> Tensor:
+ def hat(v: torch.Tensor) -> torch.Tensor:
"""Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 3, 3)`.
Args:
@@ -238,13 +230,13 @@ class Se2(Module):
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_v_shape(v)
- upsilon = stack((v[..., 0], v[..., 1]), -1)
+ upsilon = torch.stack((v[..., 0], v[..., 1]), -1)
theta = v[..., 2]
- col0 = concatenate((So2.hat(theta), upsilon.unsqueeze(-2)), -2)
- return pad(col0, (0, 1))
+ col0 = torch.cat((So2.hat(theta), upsilon.unsqueeze(-2)), -2)
+ return F.pad(col0, (0, 1))
@staticmethod
- def vee(omega: Tensor) -> Tensor:
+ def vee(omega: torch.Tensor) -> torch.Tensor:
"""Convert elements from lie algebra to vector space.
Args:
@@ -264,10 +256,15 @@ class Se2(Module):
check_se2_omega_shape(omega)
upsilon = omega[..., 2, :2]
theta = So2.vee(omega[..., :2, :2])
- return concatenate((upsilon, theta[..., None]), -1)
+ return torch.cat((upsilon, theta[..., None]), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se2:
+ def identity(
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
+ ) -> Se2:
"""Create a Se2 group representing an identity rotation and zero translation.
Args:
@@ -285,13 +282,13 @@ class Se2(Module):
y: tensor([0.])
"""
- t: Tensor = tensor([0.0, 0.0], device=device, dtype=dtype)
+ t: torch.Tensor = torch.tensor([0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
t = t.repeat(batch_size, 1)
return cls(So2.identity(batch_size, device, dtype), Vector2(t))
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
"""Return the matrix representation of shape :math:`(B, 3, 3)`.
Example:
@@ -302,17 +299,17 @@ class Se2(Module):
[0., 0., 1.]]], grad_fn=<CopySlices>)
"""
- rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
- rt_3x3 = pad(rt, (0, 0, 0, 1)) # add last row zeros
+ rt = torch.cat((self.r.matrix(), self.t.data[..., None]), -1)
+ rt_3x3 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zeros
rt_3x3[..., -1, -1] = 1.0
return rt_3x3
@classmethod
- def from_matrix(cls, matrix: Tensor) -> Se2:
+ def from_matrix(cls, matrix: torch.Tensor) -> Se2:
"""Create an Se2 group from a matrix.
Args:
- matrix: tensor of shape :math:`(B, 3, 3)`.
+ matrix: torch.tensor of shape :math:`(B, 3, 3)`.
Example:
>>> s = Se2.from_matrix(torch.eye(3).repeat(2, 1, 1))
@@ -352,7 +349,12 @@ class Se2(Module):
return Se2(r_inv, r_inv * _t)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se2:
+ def random(
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
+ ) -> Se2:
"""Create a Se2 group representing a random transformation.
Args:
@@ -372,10 +374,10 @@ class Se2(Module):
else:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
shape = (batch_size, 2)
- return cls(r, Vector2(rand(shape, device=device, dtype=dtype)))
+ return cls(r, Vector2(torch.rand(shape, device=device, dtype=dtype)))
@classmethod
- def trans(cls, x: Tensor, y: Tensor) -> Se2:
+ def trans(cls, x: torch.Tensor, y: torch.Tensor) -> Se2:
"""Construct a translation only Se2 instance.
Args:
@@ -387,31 +389,31 @@ class Se2(Module):
KORNIA_CHECK_SAME_DEVICES([x, y])
batch_size = x.shape[0] if len(x.shape) > 0 else None
rotation = So2.identity(batch_size, x.device, x.dtype)
- return cls(rotation, stack((x, y), -1))
+ return cls(rotation, torch.stack((x, y), -1))
@classmethod
- def trans_x(cls, x: Tensor) -> Se2:
+ def trans_x(cls, x: torch.Tensor) -> Se2:
"""Construct a x-axis translation.
Args:
x: the x-axis translation.
"""
- zs = zeros_like(x)
+ zs = torch.zeros_like(x)
return cls.trans(x, zs)
@classmethod
- def trans_y(cls, y: Tensor) -> Se2:
+ def trans_y(cls, y: torch.Tensor) -> Se2:
"""Construct a y-axis translation.
Args:
y: the y-axis translation.
"""
- zs = zeros_like(y)
+ zs = torch.zeros_like(y)
return cls.trans(zs, y)
- def adjoint(self) -> Tensor:
+ def adjoint(self) -> torch.Tensor:
"""Return the adjoint matrix of shape :math:`(B, 3, 3)`.
Example:
@@ -423,5 +425,5 @@ class Se2(Module):
"""
rt = self.matrix()
- rt[..., 0:2, 2] = stack((self.t.data[..., 1], -self.t.data[..., 0]), -1)
+ rt[..., 0:2, 2] = torch.stack((self.t.data[..., 1], -self.t.data[..., 0]), -1)
return rt
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 19d116911..31bfe5def 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -19,22 +19,12 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
from __future__ import annotations
-from typing import Optional
-
-from kornia.core import (
- Device,
- Dtype,
- Module,
- Parameter,
- Tensor,
- concatenate,
- eye,
- pad,
- stack,
- tensor,
- where,
- zeros_like,
-)
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES
from kornia.geometry.liegroup.so3 import So3
from kornia.geometry.linalg import batched_dot_product
@@ -42,7 +32,7 @@ from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
-class Se3(Module):
+class Se3(nn.Module):
r"""Base class to represent the Se3 group.
The SE(3) is the group of rigid body transformations about the origin of three-dimensional Euclidean
@@ -60,14 +50,14 @@ class Se3(Module):
"""
- def __init__(self, rotation: Quaternion | So3, translation: Vector3 | Tensor) -> None:
+ def __init__(self, rotation: Quaternion | So3, translation: Vector3 | torch.Tensor) -> None:
"""Construct the base class.
Internally represented by a unit quaternion `q` and a translation 3-vector.
Args:
rotation: So3 group encompassing a rotation.
- translation: Vector3 or translation tensor with the shape of :math:`(B, 3)`.
+ translation: Vector3 or translation torch.tensor with the shape of :math:`(B, 3)`.
Example:
>>> from kornia.geometry.quaternion import Quaternion
@@ -84,14 +74,14 @@ class Se3(Module):
# KORNIA_CHECK_TYPE(rotation, (Quaternion, So3))
if not isinstance(rotation, (Quaternion, So3)):
raise TypeError(f"rotation type is {type(rotation)}")
- # KORNIA_CHECK_TYPE(translation, (Vector3, Tensor))
- if not isinstance(translation, (Vector3, Tensor)):
+ # KORNIA_CHECK_TYPE(translation, (Vector3, torch.Tensor))
+ if not isinstance(translation, (Vector3, torch.Tensor)):
raise TypeError(f"translation type is {type(translation)}")
# KORNIA_CHECK_SHAPE(t, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
- self._translation: Vector3 | Parameter
+ self._translation: Vector3 | nn.Parameter
self._rotation: So3
- if isinstance(translation, Tensor):
- self._translation = Parameter(translation)
+ if isinstance(translation, torch.Tensor):
+ self._translation = nn.Parameter(translation)
else:
self._translation = translation
if isinstance(rotation, Quaternion):
@@ -110,7 +100,7 @@ class Se3(Module):
_t = self.t + self.r * right.t
return Se3(_r, _t)
- def __mul__(self, right: Se3) -> Se3 | Vector3 | Tensor:
+ def __mul__(self, right: Se3) -> Se3 | Vector3 | torch.Tensor:
"""Compose two Se3 transformations.
Args:
@@ -125,7 +115,7 @@ class Se3(Module):
if isinstance(right, Se3):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
return self._mul_se3(right)
- elif isinstance(right, (Vector3, Tensor)):
+ elif isinstance(right, (Vector3, torch.Tensor)):
# KORNIA_CHECK_SHAPE(right, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba
return so3 * right + t.data
else:
@@ -147,7 +137,7 @@ class Se3(Module):
return self._rotation
@property
- def t(self) -> Vector3 | Tensor:
+ def t(self) -> Vector3 | torch.Tensor:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@@ -157,12 +147,12 @@ class Se3(Module):
return self._rotation
@property
- def translation(self) -> Vector3 | Tensor:
+ def translation(self) -> Vector3 | torch.Tensor:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@staticmethod
- def exp(v: Tensor) -> Se3:
+ def exp(v: torch.Tensor) -> Se3:
"""Convert elements of lie algebra to elements of lie group.
Args:
@@ -186,14 +176,14 @@ class Se3(Module):
theta = batched_dot_product(omega, omega).sqrt()
R = So3.exp(omega)
V = (
- eye(3, device=v.device, dtype=v.dtype)
- + ((1 - theta.cos()) / (theta**2))[..., None, None] * omega_hat
- + ((theta - theta.sin()) / (theta**3))[..., None, None] * omega_hat_sq
+ torch.eye(3, device=v.device, dtype=v.dtype)
+ + ((1 - torch.cos(theta)) / (theta**2))[..., None, None] * omega_hat
+ + ((theta - torch.sin(theta)) / (theta**3))[..., None, None] * omega_hat_sq
)
- U = where(theta[..., None] != 0.0, (upsilon[..., None, :] * V).sum(-1), upsilon)
+ U = torch.where(theta[..., None] != 0.0, (upsilon[..., None, :] * V).sum(-1), upsilon)
return Se3(R, U)
- def log(self) -> Tensor:
+ def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
Example:
@@ -209,15 +199,16 @@ class Se3(Module):
omega_hat = So3.hat(omega)
omega_hat_sq = omega_hat @ omega_hat
V_inv = (
- eye(3, device=omega.device, dtype=omega.dtype)
+ torch.eye(3, device=omega.device, dtype=omega.dtype)
- 0.5 * omega_hat
- + ((1 - theta * (theta / 2).cos() / (2 * (theta / 2).sin())) / theta.pow(2))[..., None, None] * omega_hat_sq
+ + ((1 - theta * torch.cos(theta / 2) / (2 * torch.sin(theta / 2))) / theta.pow(2))[..., None, None]
+ * omega_hat_sq
)
- t = where(theta[..., None] != 0.0, (t[..., None, :] * V_inv).sum(-1), t)
- return concatenate((t, omega), -1)
+ t = torch.where(theta[..., None] != 0.0, (t[..., None, :] * V_inv).sum(-1), t)
+ return torch.cat((t, omega), -1)
@staticmethod
- def hat(v: Tensor) -> Tensor:
+ def hat(v: torch.Tensor) -> torch.Tensor:
"""Convert elements from vector space to lie algebra.
Args:
@@ -238,11 +229,11 @@ class Se3(Module):
"""
# KORNIA_CHECK_SHAPE(v, ["B", "6"]) # FIXME: resolve shape bugs. @edgarriba
upsilon, omega = v[..., :3], v[..., 3:]
- rt = concatenate((So3.hat(omega), upsilon[..., None]), -1)
- return pad(rt, (0, 0, 0, 1)) # add zeros bottom
+ rt = torch.cat((So3.hat(omega), upsilon[..., None]), -1)
+ return F.pad(rt, (0, 0, 0, 1)) # add torch.zeros bottom
@staticmethod
- def vee(omega: Tensor) -> Tensor:
+ def vee(omega: torch.Tensor) -> torch.Tensor:
"""Convert elements from lie algebra to vector space.
Args:
@@ -261,10 +252,15 @@ class Se3(Module):
# KORNIA_CHECK_SHAPE(omega, ["B", "4", "4"]) # FIXME: resolve shape bugs. @edgarriba
head = omega[..., :3, -1]
tail = So3.vee(omega[..., :3, :3])
- return concatenate((head, tail), -1)
+ return torch.cat((head, tail), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se3:
+ def identity(
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
+ ) -> Se3:
"""Create a Se3 group representing an identity rotation and zero translation.
Args:
@@ -282,13 +278,13 @@ class Se3(Module):
z: 0.0
"""
- t = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
+ t = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
t = t.repeat(batch_size, 1)
return cls(So3.identity(batch_size, device, dtype), Vector3(t))
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
"""Return the matrix representation of shape :math:`(B, 4, 4)`.
Example:
@@ -300,17 +296,17 @@ class Se3(Module):
[0., 0., 0., 1.]])
"""
- rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
- rt_4x4 = pad(rt, (0, 0, 0, 1)) # add last row zeros
+ rt = torch.cat((self.r.matrix(), self.t.data[..., None]), -1)
+ rt_4x4 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zeros
rt_4x4[..., -1, -1] = 1.0
return rt_4x4
@classmethod
- def from_matrix(cls, matrix: Tensor) -> Se3:
+ def from_matrix(cls, matrix: torch.Tensor) -> Se3:
"""Create a Se3 group from a matrix.
Args:
- matrix: tensor of shape :math:`(B, 4, 4)`.
+ matrix: torch.tensor of shape :math:`(B, 4, 4)`.
Example:
>>> s = Se3.from_matrix(torch.eye(4))
@@ -327,11 +323,11 @@ class Se3(Module):
return cls(r, t)
@classmethod
- def from_qxyz(cls, qxyz: Tensor) -> Se3:
+ def from_qxyz(cls, qxyz: torch.Tensor) -> Se3:
"""Create a Se3 group a quaternion and translation vector.
Args:
- qxyz: tensor of shape :math:`(B, 7)`.
+ qxyz: torch.tensor of shape :math:`(B, 7)`.
Example:
>>> qxyz = torch.tensor([1., 2., 3., 0., 0., 0., 1.])
@@ -369,7 +365,12 @@ class Se3(Module):
return Se3(r_inv, r_inv * _t)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se3:
+ def random(
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
+ ) -> Se3:
"""Create a Se3 group representing a random transformation.
Args:
@@ -393,40 +394,40 @@ class Se3(Module):
return cls(r, t)
@classmethod
- def rot_x(cls, x: Tensor) -> Se3:
+ def rot_x(cls, x: torch.Tensor) -> Se3:
"""Construct a x-axis rotation.
Args:
x: the x-axis rotation angle.
"""
- zs = zeros_like(x)
- return cls(So3.rot_x(x), stack((zs, zs, zs), -1))
+ zs = torch.zeros_like(x)
+ return cls(So3.rot_x(x), torch.stack((zs, zs, zs), -1))
@classmethod
- def rot_y(cls, y: Tensor) -> Se3:
+ def rot_y(cls, y: torch.Tensor) -> Se3:
"""Construct a y-axis rotation.
Args:
y: the y-axis rotation angle.
"""
- zs = zeros_like(y)
- return cls(So3.rot_y(y), stack((zs, zs, zs), -1))
+ zs = torch.zeros_like(y)
+ return cls(So3.rot_y(y), torch.stack((zs, zs, zs), -1))
@classmethod
- def rot_z(cls, z: Tensor) -> Se3:
+ def rot_z(cls, z: torch.Tensor) -> Se3:
"""Construct a z-axis rotation.
Args:
z: the z-axis rotation angle.
"""
- zs = zeros_like(z)
- return cls(So3.rot_z(z), stack((zs, zs, zs), -1))
+ zs = torch.zeros_like(z)
+ return cls(So3.rot_z(z), torch.stack((zs, zs, zs), -1))
@classmethod
- def trans(cls, x: Tensor, y: Tensor, z: Tensor) -> Se3:
+ def trans(cls, x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> Se3:
"""Construct a translation only Se3 instance.
Args:
@@ -440,42 +441,42 @@ class Se3(Module):
KORNIA_CHECK_SAME_DEVICES([x, y, z])
batch_size = x.shape[0] if len(x.shape) > 0 else None
rotation = So3.identity(batch_size, x.device, x.dtype)
- return cls(rotation, stack((x, y, z), -1))
+ return cls(rotation, torch.stack((x, y, z), -1))
@classmethod
- def trans_x(cls, x: Tensor) -> Se3:
+ def trans_x(cls, x: torch.Tensor) -> Se3:
"""Construct a x-axis translation.
Args:
x: the x-axis translation.
"""
- zs = zeros_like(x)
+ zs = torch.zeros_like(x)
return cls.trans(x, zs, zs)
@classmethod
- def trans_y(cls, y: Tensor) -> Se3:
+ def trans_y(cls, y: torch.Tensor) -> Se3:
"""Construct a y-axis translation.
Args:
y: the y-axis translation.
"""
- zs = zeros_like(y)
+ zs = torch.zeros_like(y)
return cls.trans(zs, y, zs)
@classmethod
- def trans_z(cls, z: Tensor) -> Se3:
+ def trans_z(cls, z: torch.Tensor) -> Se3:
"""Construct a z-axis translation.
Args:
z: the z-axis translation.
"""
- zs = zeros_like(z)
+ zs = torch.zeros_like(z)
return cls.trans(zs, zs, z)
- def adjoint(self) -> Tensor:
+ def adjoint(self) -> torch.Tensor:
"""Return the adjoint matrix of shape :math:`(B, 6, 6)`.
Example:
@@ -490,7 +491,7 @@ class Se3(Module):
"""
R = self.so3.matrix()
- z = zeros_like(R)
- row0 = concatenate((R, So3.hat(self.t) @ R), -1)
- row1 = concatenate((z, R), -1)
- return concatenate((row0, row1), -2)
+ z = torch.zeros_like(R)
+ row0 = torch.cat((R, So3.hat(self.t) @ R), -1)
+ row1 = torch.cat((z, R), -1)
+ return torch.cat((row0, row1), -2)
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index b34052f52..d7459b7e2 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -19,9 +19,11 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.py
from __future__ import annotations
-from typing import Optional, overload
+from typing import Optional, Union, overload
+
+import torch
+from torch import nn
-from kornia.core import Device, Dtype, Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.geometry.liegroup._utils import (
check_so2_matrix,
@@ -33,14 +35,14 @@ from kornia.geometry.liegroup._utils import (
from kornia.geometry.vector import Vector2
-class So2(Module):
+class So2(nn.Module):
r"""Base class to represent the So2 group.
The SO(2) is the group of all rotations about the origin of two-dimensional Euclidean space
:math:`R^2` under the operation of composition.
See more: https://en.wikipedia.org/wiki/Orthogonal_group#Special_orthogonal_group
- We internally represent the rotation by a complex number.
+ We internally represent the rotation by a torch.complex number.
Example:
>>> real = torch.tensor([1.0])
@@ -51,10 +53,10 @@ class So2(Module):
"""
- def __init__(self, z: Tensor) -> None:
+ def __init__(self, z: torch.Tensor) -> None:
"""Construct the base class.
- Internally represented by complex number `z`.
+ Internally represented by torch.complex number `z`.
Args:
z: Complex number with the shape of :math:`(B, 1)` or :math:`(B)`.
@@ -71,7 +73,7 @@ class So2(Module):
KORNIA_CHECK_IS_TENSOR(z)
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_z_shape(z)
- self._z = Parameter(z)
+ self._z = nn.Parameter(z)
def __repr__(self) -> str:
return f"{self.z}"
@@ -83,9 +85,9 @@ class So2(Module):
def __mul__(self, right: So2) -> So2: ...
@overload
- def __mul__(self, right: Tensor) -> Tensor: ...
+ def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...
- def __mul__(self, right: So2 | Tensor) -> So2 | Tensor:
+ def __mul__(self, right: So2 | torch.Tensor) -> So2 | torch.Tensor:
"""Perform a left-multiplication either rotation concatenation or point-transform.
Args:
@@ -98,29 +100,29 @@ class So2(Module):
z = self.z
if isinstance(right, So2):
return So2(z * right.z)
- elif isinstance(right, (Vector2, Tensor)):
+ elif isinstance(right, (Vector2, torch.Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- if isinstance(right, Tensor):
+ if isinstance(right, torch.Tensor):
check_so2_t_shape(right)
x = right.data[..., 0]
y = right.data[..., 1]
real = z.real
imag = z.imag
- out = stack((real * x - imag * y, imag * x + real * y), -1)
- if isinstance(right, Tensor):
+ out = torch.stack((real * x - imag * y, imag * x + real * y), -1)
+ if isinstance(right, torch.Tensor):
return out
else:
return Vector2(out)
else:
- raise TypeError(f"Not So2 or Tensor type. Got: {type(right)}")
+ raise TypeError(f"Not So2 or torch.Tensor type. Got: {type(right)}")
@property
- def z(self) -> Tensor:
+ def z(self) -> torch.Tensor:
"""Return the underlying data with shape :math:`(B, 1)`."""
return self._z
@staticmethod
- def exp(theta: Tensor) -> So2:
+ def exp(theta: torch.Tensor) -> So2:
"""Convert elements of lie algebra to elements of lie group.
Args:
@@ -136,9 +138,9 @@ class So2(Module):
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_theta_shape(theta)
- return So2(complex(theta.cos(), theta.sin()))
+ return So2(torch.complex(torch.cos(theta), torch.sin(theta)))
- def log(self) -> Tensor:
+ def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
Example:
@@ -151,7 +153,7 @@ class So2(Module):
return self.z.imag.atan2(self.z.real)
@staticmethod
- def hat(theta: Tensor) -> Tensor:
+ def hat(theta: torch.Tensor) -> torch.Tensor:
"""Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 2, 2)`.
Args:
@@ -166,13 +168,13 @@ class So2(Module):
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_theta_shape(theta)
- z = zeros_like(theta)
- row0 = stack((z, theta), -1)
- row1 = stack((theta, z), -1)
- return stack((row0, row1), -1)
+ z = torch.zeros_like(theta)
+ row0 = torch.stack((z, theta), -1)
+ row1 = torch.stack((theta, z), -1)
+ return torch.stack((row0, row1), -1)
@staticmethod
- def vee(omega: Tensor) -> Tensor:
+ def vee(omega: torch.Tensor) -> torch.Tensor:
"""Convert elements from lie algebra to vector space. Returns vector of shape :math:`(B,)`.
Args:
@@ -189,8 +191,8 @@ class So2(Module):
check_so2_matrix_shape(omega)
return omega[..., 0, 1]
- def matrix(self) -> Tensor:
- """Convert the complex number to a rotation matrix of shape :math:`(B, 2, 2)`.
+ def matrix(self) -> torch.Tensor:
+ """Convert the torch.complex number to a rotation matrix of shape :math:`(B, 2, 2)`.
Example:
>>> s = So2.identity()
@@ -200,12 +202,12 @@ class So2(Module):
[0., 1.]], grad_fn=<StackBackward0>)
"""
- row0 = stack((self.z.real, -self.z.imag), -1)
- row1 = stack((self.z.imag, self.z.real), -1)
- return stack((row0, row1), -2)
+ row0 = torch.stack((self.z.real, -self.z.imag), -1)
+ row1 = torch.stack((self.z.imag, self.z.real), -1)
+ return torch.stack((row0, row1), -2)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> So2:
+ def from_matrix(cls, matrix: torch.Tensor) -> So2:
"""Create So2 from a rotation matrix.
Args:
@@ -222,12 +224,15 @@ class So2(Module):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_matrix_shape(matrix)
check_so2_matrix(matrix)
- z = complex(matrix[..., 0, 0], matrix[..., 1, 0])
+ z = torch.complex(matrix[..., 0, 0], matrix[..., 1, 0])
return cls(z)
@classmethod
def identity(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Optional[Union[torch.dtype, None]] = None,
) -> So2:
"""Create a So2 group representing an identity rotation.
@@ -243,13 +248,13 @@ class So2(Module):
tensor([1.+0.j, 1.+0.j], requires_grad=True)
"""
- real_data = tensor(1.0, device=device, dtype=dtype)
- imag_data = tensor(0.0, device=device, dtype=dtype)
+ real_data = torch.tensor(1.0, device=device, dtype=dtype)
+ imag_data = torch.tensor(0.0, device=device, dtype=dtype)
if batch_size is not None:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
real_data = real_data.repeat(batch_size)
imag_data = imag_data.repeat(batch_size)
- return cls(complex(real_data, imag_data))
+ return cls(torch.complex(real_data, imag_data))
def inverse(self) -> So2:
"""Return the inverse transformation.
@@ -265,7 +270,10 @@ class So2(Module):
@classmethod
def random(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Optional[Union[torch.dtype, None]] = None,
) -> So2:
"""Create a So2 group representing a random rotation.
@@ -281,14 +289,14 @@ class So2(Module):
"""
if batch_size is not None:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
- real_data = rand((batch_size,), device=device, dtype=dtype)
- imag_data = rand((batch_size,), device=device, dtype=dtype)
+ real_data = torch.rand((batch_size,), device=device, dtype=dtype)
+ imag_data = torch.rand((batch_size,), device=device, dtype=dtype)
else:
- real_data = rand((), device=device, dtype=dtype)
- imag_data = rand((), device=device, dtype=dtype)
- return cls(complex(real_data, imag_data))
+ real_data = torch.rand((), device=device, dtype=dtype)
+ imag_data = torch.rand((), device=device, dtype=dtype)
+ return cls(torch.complex(real_data, imag_data))
- def adjoint(self) -> Tensor:
+ def adjoint(self) -> torch.Tensor:
"""Return the adjoint matrix of shape :math:`(B, 2, 2)`.
Example:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 99166e0f4..d9db81972 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -19,11 +19,11 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
from __future__ import annotations
-from typing import Optional
+from typing import Optional, Union
import torch
+from torch import nn
-from kornia.core import Device, Dtype, Module, Tensor, concatenate, eye, stack, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.conversions import vector_to_skew_symmetric_matrix
from kornia.geometry.linalg import batched_dot_product
@@ -31,7 +31,7 @@ from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
-class So3(Module):
+class So3(nn.Module):
r"""Base class to represent the So3 group.
The SO(3) is the group of all rotations about the origin of three-dimensional Euclidean space
@@ -87,17 +87,17 @@ class So3(Module):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
if isinstance(right, So3):
return So3(self.q * right.q)
- elif isinstance(right, (Tensor, Vector3)):
+ elif isinstance(right, (torch.Tensor, Vector3)):
# KORNIA_CHECK_SHAPE(right, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
- w = zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
- quat = Quaternion(concatenate((w, right.data), -1))
+ w = torch.zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
+ quat = Quaternion(torch.cat((w, right.data), -1))
out = (self.q * quat * self.q.conj()).vec
- if isinstance(right, Tensor):
+ if isinstance(right, torch.Tensor):
return out
elif isinstance(right, Vector3):
return Vector3(out)
else:
- raise TypeError(f"Not So3 or Tensor type. Got: {type(right)}")
+ raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")
@property
def q(self) -> Quaternion:
@@ -105,7 +105,7 @@ class So3(Module):
return self._q
@staticmethod
- def exp(v: Tensor) -> So3:
+ def exp(v: torch.Tensor) -> So3:
"""Convert elements of lie algebra to elements of lie group.
See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf
@@ -134,7 +134,7 @@ class So3(Module):
q = torch.cat((w, xyz), dim=-1)
return So3(Quaternion(q))
- def log(self) -> Tensor:
+ def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
Example:
@@ -147,7 +147,7 @@ class So3(Module):
"""
theta = batched_dot_product(self.q.vec, self.q.vec).sqrt()
# NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33
- omega = where(
+ omega = torch.where(
theta[..., None] != 0,
2 * self.q.real[..., None].acos() * self.q.vec / theta[..., None],
2 * self.q.vec / self.q.real[..., None],
@@ -155,11 +155,11 @@ class So3(Module):
return omega
@staticmethod
- def hat(v: Vector3 | Tensor) -> Tensor:
+ def hat(v: Vector3 | torch.Tensor) -> torch.Tensor:
"""Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
Args:
- v: Vector3 or tensor of shape :math:`(B,3)`.
+ v: Vector3 or torch.tensor of shape :math:`(B,3)`.
Example:
>>> v = torch.ones((1,3))
@@ -171,19 +171,19 @@ class So3(Module):
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
- if isinstance(v, Tensor):
+ if isinstance(v, torch.Tensor):
# TODO: Figure out why mypy think `v` can be a Vector3 which didn't allow ellipsis on index
a, b, c = v[..., 0], v[..., 1], v[..., 2] # type: ignore[index]
else:
a, b, c = v.x, v.y, v.z
- z = zeros_like(a)
- row0 = stack((z, -c, b), -1)
- row1 = stack((c, z, -a), -1)
- row2 = stack((-b, a, z), -1)
- return stack((row0, row1, row2), -2)
+ z = torch.zeros_like(a)
+ row0 = torch.stack((z, -c, b), -1)
+ row1 = torch.stack((c, z, -a), -1)
+ row2 = torch.stack((-b, a, z), -1)
+ return torch.stack((row0, row1, row2), -2)
@staticmethod
- def vee(omega: Tensor) -> Tensor:
+ def vee(omega: torch.Tensor) -> torch.Tensor:
r"""Convert elements from lie algebra to vector space. Returns vector of shape :math:`(B,3)`.
.. math::
@@ -203,9 +203,9 @@ class So3(Module):
"""
# KORNIA_CHECK_SHAPE(omega, ["B", "3", "3"]) # FIXME: resolve shape bugs. @edgarriba
a, b, c = omega[..., 2, 1], omega[..., 0, 2], omega[..., 1, 0]
- return stack((a, b, c), -1)
+ return torch.stack((a, b, c), -1)
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
r"""Convert the quaternion to a rotation matrix of shape :math:`(B,3,3)`.
The matrix is of the form:
@@ -229,19 +229,19 @@ class So3(Module):
q0 = 1 - 2 * y**2 - 2 * z**2
q1 = 2 * x * y - 2 * z * w
q2 = 2 * x * z + 2 * y * w
- row0 = concatenate((q0, q1, q2), -1)
+ row0 = torch.cat((q0, q1, q2), -1)
q0 = 2 * x * y + 2 * z * w
q1 = 1 - 2 * x**2 - 2 * z**2
q2 = 2 * y * z - 2 * x * w
- row1 = concatenate((q0, q1, q2), -1)
+ row1 = torch.cat((q0, q1, q2), -1)
q0 = 2 * x * z - 2 * y * w
q1 = 2 * y * z + 2 * x * w
q2 = 1 - 2 * x**2 - 2 * y**2
- row2 = concatenate((q0, q1, q2), -1)
- return stack((row0, row1, row2), -2)
+ row2 = torch.cat((q0, q1, q2), -1)
+ return torch.stack((row0, row1, row2), -2)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> So3:
+ def from_matrix(cls, matrix: torch.Tensor) -> So3:
"""Create So3 from a rotation matrix.
Args:
@@ -257,8 +257,8 @@ class So3(Module):
return cls(Quaternion.from_matrix(matrix))
@classmethod
- def from_wxyz(cls, wxyz: Tensor) -> So3:
- """Create So3 from a tensor representing a quaternion.
+ def from_wxyz(cls, wxyz: torch.Tensor) -> So3:
+ """Create So3 from a torch.tensor representing a quaternion.
Args:
wxyz: the quaternion to convert of shape :math:`(B,4)`.
@@ -275,7 +275,10 @@ class So3(Module):
@classmethod
def identity(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Optional[Union[torch.dtype, None]] = None,
) -> So3:
"""Create a So3 group representing an identity rotation.
@@ -310,7 +313,10 @@ class So3(Module):
@classmethod
def random(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Optional[Union[torch.dtype, None]] = None,
) -> So3:
"""Create a So3 group representing a random rotation.
@@ -327,39 +333,39 @@ class So3(Module):
return cls(Quaternion.random(batch_size, device, dtype))
@classmethod
- def rot_x(cls, x: Tensor) -> So3:
+ def rot_x(cls, x: torch.Tensor) -> So3:
"""Construct a x-axis rotation.
Args:
x: the x-axis rotation angle.
"""
- zs = zeros_like(x)
- return cls.exp(stack((x, zs, zs), -1))
+ zs = torch.zeros_like(x)
+ return cls.exp(torch.stack((x, zs, zs), -1))
@classmethod
- def rot_y(cls, y: Tensor) -> So3:
+ def rot_y(cls, y: torch.Tensor) -> So3:
"""Construct a z-axis rotation.
Args:
y: the y-axis rotation angle.
"""
- zs = zeros_like(y)
- return cls.exp(stack((zs, y, zs), -1))
+ zs = torch.zeros_like(y)
+ return cls.exp(torch.stack((zs, y, zs), -1))
@classmethod
- def rot_z(cls, z: Tensor) -> So3:
+ def rot_z(cls, z: torch.Tensor) -> So3:
"""Construct a z-axis rotation.
Args:
z: the z-axis rotation angle.
"""
- zs = zeros_like(z)
- return cls.exp(stack((zs, zs, z), -1))
+ zs = torch.zeros_like(z)
+ return cls.exp(torch.stack((zs, zs, z), -1))
- def adjoint(self) -> Tensor:
+ def adjoint(self) -> torch.Tensor:
"""Return the adjoint matrix of shape :math:`(B, 3, 3)`.
Example:
@@ -373,7 +379,7 @@ class So3(Module):
return self.matrix()
@staticmethod
- def right_jacobian(vec: Tensor) -> Tensor:
+ def right_jacobian(vec: torch.Tensor) -> torch.Tensor:
"""Compute the right Jacobian of So3.
Args:
@@ -390,12 +396,16 @@ class So3(Module):
# KORNIA_CHECK_SHAPE(vec, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
R_skew = vector_to_skew_symmetric_matrix(vec)
theta = vec.norm(dim=-1, keepdim=True)[..., None]
- I = eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741
- Jr = I - ((1 - theta.cos()) / theta**2) * R_skew + ((theta - theta.sin()) / theta**3) * (R_skew @ R_skew)
+ I = torch.eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741
+ Jr = (
+ I
+ - ((1 - torch.cos(theta)) / theta**2) * R_skew
+ + ((theta - torch.sin(theta)) / theta**3) * (R_skew @ R_skew)
+ )
return Jr
@staticmethod
- def Jr(vec: Tensor) -> Tensor:
+ def Jr(vec: torch.Tensor) -> torch.Tensor:
"""Alias for right jacobian.
Args:
@@ -405,7 +415,7 @@ class So3(Module):
return So3.right_jacobian(vec)
@staticmethod
- def left_jacobian(vec: Tensor) -> Tensor:
+ def left_jacobian(vec: torch.Tensor) -> torch.Tensor:
"""Compute the left Jacobian of So3.
Args:
@@ -422,12 +432,16 @@ class So3(Module):
# KORNIA_CHECK_SHAPE(vec, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
R_skew = vector_to_skew_symmetric_matrix(vec)
theta = vec.norm(dim=-1, keepdim=True)[..., None]
- I = eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741
- Jl = I + ((1 - theta.cos()) / theta**2) * R_skew + ((theta - theta.sin()) / theta**3) * (R_skew @ R_skew)
+ I = torch.eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741
+ Jl = (
+ I
+ + ((1 - torch.cos(theta)) / theta**2) * R_skew
+ + ((theta - torch.sin(theta)) / theta**3) * (R_skew @ R_skew)
+ )
return Jl
@staticmethod
- def Jl(vec: Tensor) -> Tensor:
+ def Jl(vec: torch.Tensor) -> torch.Tensor:
"""Alias for left jacobian.
Args:
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 59497c1a8..c6ff9f1ea 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -19,7 +19,6 @@ from __future__ import annotations
import torch
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
@@ -36,7 +35,7 @@ __all__ = [
]
-def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
+def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> torch.Tensor:
r"""Compose two homogeneous transformations.
.. math::
@@ -89,7 +88,7 @@ def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
return trans_02
-def inverse_transformation(trans_12: Tensor) -> Tensor:
+def inverse_transformation(trans_12: torch.Tensor) -> torch.Tensor:
r"""Invert a 4x4 homogeneous transformation.
:math:`T_1^{2} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}`
@@ -132,7 +131,7 @@ def inverse_transformation(trans_12: Tensor) -> Tensor:
return trans_21
-def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
+def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> torch.Tensor:
r"""Compute the relative homogeneous transformation from a reference transformation.
:math:`T_1^{0} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}` to destination :math:`T_2^{0} =
@@ -181,7 +180,7 @@ def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
return trans_12
-def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
+def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tensor:
r"""Apply transformations to a set of points.
Args:
@@ -231,7 +230,7 @@ def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
return points_0
-def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tensor:
+def point_line_distance(point: torch.Tensor, line: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
r"""Return the distance from points to lines.
Args:
@@ -264,19 +263,19 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tenso
return numerator / (denom_norm + eps)
-def batched_dot_product(x: Tensor, y: Tensor, keepdim: bool = False) -> Tensor:
+def batched_dot_product(x: torch.Tensor, y: torch.Tensor, keepdim: bool = False) -> torch.Tensor:
"""Return a batched version of .dot()."""
KORNIA_CHECK_SHAPE(x, ["*", "N"])
KORNIA_CHECK_SHAPE(y, ["*", "N"])
return (x * y).sum(-1, keepdim)
-def batched_squared_norm(x: Tensor, keepdim: bool = False) -> Tensor:
+def batched_squared_norm(x: torch.Tensor, keepdim: bool = False) -> torch.Tensor:
"""Return the squared norm of a vector."""
return batched_dot_product(x, x, keepdim)
-def euclidean_distance(x: Tensor, y: Tensor, keepdim: bool = False, eps: float = 1e-6) -> Tensor:
+def euclidean_distance(x: torch.Tensor, y: torch.Tensor, keepdim: bool = False, eps: float = 1e-6) -> torch.Tensor:
"""Compute the Euclidean distance between two set of n-dimensional points.
More: https://en.wikipedia.org/wiki/Euclidean_distance
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 2a7d93cc3..7510f9d97 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -20,8 +20,9 @@
from typing import Iterator, Optional, Tuple, Union
import torch
+import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Parameter, Tensor, normalize, where
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.plane import Hyperplane
@@ -30,7 +31,7 @@ from kornia.utils.helpers import _torch_svd_cast
__all__ = ["ParametrizedLine", "fit_line"]
-class ParametrizedLine(Module):
+class ParametrizedLine(nn.Module):
"""Class that describes a parametrize line.
A parametrized line is defined by an origin point :math:`o` and a unit
@@ -41,7 +42,7 @@ class ParametrizedLine(Module):
l(t) = o + t * d
"""
- def __init__(self, origin: Tensor, direction: Tensor) -> None:
+ def __init__(self, origin: torch.Tensor, direction: torch.Tensor) -> None:
"""Initialize a parametrized line of direction and origin.
Args:
@@ -55,8 +56,8 @@ class ParametrizedLine(Module):
"""
super().__init__()
- self._origin = Parameter(origin)
- self._direction = Parameter(direction)
+ self._origin = nn.Parameter(origin)
+ self._direction = nn.Parameter(direction)
def __str__(self) -> str:
return f"Origin: {self.origin}\nDirection: {self.direction}"
@@ -64,19 +65,19 @@ class ParametrizedLine(Module):
def __repr__(self) -> str:
return str(self)
- def __getitem__(self, idx: int) -> Tensor:
+ def __getitem__(self, idx: int) -> torch.Tensor:
return self.origin if idx == 0 else self.direction
- def __iter__(self) -> Iterator[Tensor]:
+ def __iter__(self) -> Iterator[torch.Tensor]:
yield from (self.origin, self.direction)
@property
- def origin(self) -> Tensor:
+ def origin(self) -> torch.Tensor:
"""Return the line origin point."""
return self._origin
@property
- def direction(self) -> Tensor:
+ def direction(self) -> torch.Tensor:
"""Return the line direction vector."""
return self._direction
@@ -85,7 +86,7 @@ class ParametrizedLine(Module):
return self.direction.shape[-1]
@classmethod
- def through(cls, p0: Tensor, p1: Tensor) -> "ParametrizedLine":
+ def through(cls, p0: torch.Tensor, p1: torch.Tensor) -> "ParametrizedLine":
"""Construct a parametrized line going from a point :math:`p0` to :math:`p1`.
Args:
@@ -98,9 +99,9 @@ class ParametrizedLine(Module):
>>> l = ParametrizedLine.through(p0, p1)
"""
- return ParametrizedLine(p0, normalize((p1 - p0), p=2, dim=-1))
+ return ParametrizedLine(p0, F.normalize((p1 - p0), p=2, dim=-1))
- def point_at(self, t: Union[float, Tensor]) -> Tensor:
+ def point_at(self, t: Union[float, torch.Tensor]) -> torch.Tensor:
"""Get the point at :math:`t` along this line.
Args:
@@ -118,7 +119,7 @@ class ParametrizedLine(Module):
"""
return self.origin + self.direction * t
- def projection(self, point: Tensor) -> Tensor:
+ def projection(self, point: torch.Tensor) -> torch.Tensor:
"""Return the projection of a point onto the line.
Args:
@@ -127,7 +128,7 @@ class ParametrizedLine(Module):
"""
return self.origin + (self.direction @ (point - self.origin)) * self.direction
- def squared_distance(self, point: Tensor) -> Tensor:
+ def squared_distance(self, point: torch.Tensor) -> torch.Tensor:
"""Return the squared distance of a point to its projection onte the line.
Args:
@@ -138,7 +139,7 @@ class ParametrizedLine(Module):
sq_norm_d = torch.sum(d * d, dim=-1)
return sq_norm_d - proj * proj
- def distance(self, point: Tensor) -> Tensor:
+ def distance(self, point: torch.Tensor) -> torch.Tensor:
"""Return the distance of a point to its projections onto the line.
Args:
@@ -152,7 +153,7 @@ class ParametrizedLine(Module):
# - intersection_point
# TODO: add tests, and possibly return a mask
- def intersect(self, plane: Hyperplane, eps: float = 1e-6) -> Tuple[Tensor, Tensor]:
+ def intersect(self, plane: Hyperplane, eps: float = 1e-6) -> Tuple[torch.Tensor, torch.Tensor]:
"""Return the intersection point between the line and a given plane.
Args:
@@ -168,7 +169,7 @@ class ParametrizedLine(Module):
dot_prod_mask = dot_prod.abs() >= eps
# TODO: add check for dot product
- res_lambda = where(
+ res_lambda = torch.where(
dot_prod_mask,
-(plane.offset + batched_dot_product(plane.normal.data, self.origin.data)) / dot_prod,
torch.empty_like(dot_prod),
@@ -178,7 +179,7 @@ class ParametrizedLine(Module):
return res_lambda, res_point
-def _fit_line_ols_2d(points: Tensor) -> ParametrizedLine:
+def _fit_line_ols_2d(points: torch.Tensor) -> ParametrizedLine:
x = points[..., 0]
y = points[..., 1]
x_mean = x.mean(dim=-1, keepdim=True)
@@ -201,7 +202,7 @@ def _fit_line_ols_2d(points: Tensor) -> ParametrizedLine:
return ParametrizedLine(origin, direction)
-def _fit_line_weighted_ols_2d(points: Tensor, weights: Tensor) -> ParametrizedLine:
+def _fit_line_weighted_ols_2d(points: torch.Tensor, weights: torch.Tensor) -> ParametrizedLine:
x = points[..., 0] # (B, N)
y = points[..., 1] # (B, N)
@@ -221,7 +222,7 @@ def _fit_line_weighted_ols_2d(points: Tensor, weights: Tensor) -> ParametrizedLi
# Replace NaNs or infs from division by zero
slope = torch.where(torch.isfinite(slope), slope, torch.zeros_like(slope))
- # direction = normalize([1, slope]) or [0,1] if vertical
+ # direction = F.normalize([1, slope]) or [0,1] if vertical
is_vertical = denom <= 1e-8
direction = torch.cat([torch.ones_like(slope), slope], dim=-1) # (B, 2)
replacement = torch.tensor([0.0, 1.0], device=points.device, dtype=points.dtype)
@@ -233,7 +234,7 @@ def _fit_line_weighted_ols_2d(points: Tensor, weights: Tensor) -> ParametrizedLi
return ParametrizedLine(origin, direction)
-def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLine:
+def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:
"""Fit a line from a set of points.
Args:
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index f7410e196..1dfa5ef63 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -21,8 +21,8 @@
from typing import Optional
import torch
+from torch import nn
-from kornia.core import Module, Tensor, stack, where
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.core.tensor_wrapper import unwrap, wrap # type: ignore[attr-defined]
from kornia.geometry.linalg import batched_dot_product
@@ -32,12 +32,12 @@ from kornia.utils.helpers import _torch_svd_cast
__all__ = ["Hyperplane", "fit_plane"]
-def normalized(v: Tensor, eps: float = 1e-6) -> Tensor:
+def normalized(v: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
norm_sq = (v * v).sum(dim=-1, keepdim=True) + eps
return v * norm_sq.rsqrt()
-class Hyperplane(Module):
+class Hyperplane(nn.Module):
def __init__(self, n: Vector3, d: Scalar) -> None:
super().__init__()
KORNIA_CHECK_TYPE(n, Vector3)
@@ -68,7 +68,7 @@ class Hyperplane(Module):
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L145
# TODO: tests
def signed_distance(self, p: Vector3) -> Scalar:
- KORNIA_CHECK(isinstance(p, (Vector3, Tensor)))
+ KORNIA_CHECK(isinstance(p, (Vector3, torch.Tensor)))
return self.normal.dot(p) + self.offset
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L154
@@ -90,7 +90,7 @@ class Hyperplane(Module):
return Hyperplane(normal, Scalar(offset))
@classmethod
- def through(cls, p0: Tensor, p1: Tensor, p2: Optional[Tensor] = None) -> "Hyperplane":
+ def through(cls, p0: torch.Tensor, p1: torch.Tensor, p2: Optional[torch.Tensor] = None) -> "Hyperplane":
# 2d case
if p2 is None:
# TODO: improve tests
@@ -109,14 +109,14 @@ class Hyperplane(Module):
norm = normal.norm(-1)
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108
- def compute_normal_svd(v0: Tensor, v1: Tensor) -> "Vector3":
- # NOTE: for reason TensorWrapper does not stack well
- m = stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3
+ def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> "Vector3":
+ # NOTE: for reason torch.TensorWrapper does not stack well
+ m = torch.stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
return wrap(V[..., :, -1], Vector3) # Bx3
normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6
- normal = where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))
+ normal = torch.where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))
offset = -batched_dot_product(p0, normal)
return Hyperplane(wrap(normal, Vector3), wrap(offset, Scalar))
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index 785b788f2..d25c966cb 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -19,12 +19,13 @@ from __future__ import annotations
import uuid
-from kornia.core import Tensor, eye
+import torch
+
from kornia.geometry.liegroup import Se2, Se3, So2, So3
from kornia.geometry.quaternion import Quaternion
-def check_matrix_shape(matrix: Tensor, matrix_type: str = "R") -> None:
+def check_matrix_shape(matrix: torch.Tensor, matrix_type: str = "R") -> None:
"""Verify matrix shape based on type."""
target_shapes = []
if matrix_type == "R":
@@ -113,7 +114,7 @@ class NamedPose:
return self._dst_from_src.rotation
@property
- def translation(self) -> Tensor:
+ def translation(self) -> torch.Tensor:
"""Translation part of the pose."""
return self._dst_from_src.translation
@@ -130,8 +131,8 @@ class NamedPose:
@classmethod
def from_rt(
cls,
- rotation: So3 | So2 | Tensor | Quaternion,
- translation: Tensor,
+ rotation: So3 | So2 | torch.Tensor | Quaternion,
+ translation: torch.Tensor,
frame_src: str | None = None,
frame_dst: str | None = None,
) -> NamedPose | None:
@@ -161,10 +162,10 @@ class NamedPose:
return cls(Se3(rotation, translation), frame_src, frame_dst)
elif isinstance(rotation, So2):
return cls(Se2(rotation, translation), frame_src, frame_dst)
- elif isinstance(rotation, Tensor):
+ elif isinstance(rotation, torch.Tensor):
check_matrix_shape(rotation)
dim = rotation.shape[-1]
- RT = eye(dim + 1, device=rotation.device, dtype=rotation.dtype)
+ RT = torch.eye(dim + 1, device=rotation.device, dtype=rotation.dtype)
RT[..., :dim, :dim] = rotation
RT[..., :dim, dim] = translation
if dim == 2:
@@ -177,7 +178,7 @@ class NamedPose:
@classmethod
def from_matrix(
- cls, matrix: Tensor, frame_src: str | None = None, frame_dst: str | None = None
+ cls, matrix: torch.Tensor, frame_src: str | None = None, frame_dst: str | None = None
) -> NamedPose | None:
"""Construct NamedPose from a matrix.
@@ -225,7 +226,7 @@ class NamedPose:
"""
return NamedPose(self._dst_from_src.inverse(), self._frame_dst, self._frame_src)
- def transform_points(self, points_in_src: Tensor) -> Tensor:
+ def transform_points(self, points_in_src: torch.Tensor) -> torch.Tensor:
"""Transform points from source frame to destination frame.
Args:
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index dd7530ad6..fb023cb34 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -23,8 +23,8 @@ from math import pi
from typing import Any, Optional, Tuple, Union
import torch
+from torch import nn
-from kornia.core import Device, Dtype, Module, Parameter, Tensor, concatenate, rand, stack, tensor, where
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.conversions import (
axis_angle_to_quaternion,
@@ -38,7 +38,7 @@ from kornia.geometry.conversions import (
from kornia.geometry.linalg import batched_dot_product
-class Quaternion(Module):
+class Quaternion(nn.Module):
r"""Base class to represent a Quaternion.
A quaternion is a four dimensional vector representation of a rotation transformation in 3d.
@@ -50,7 +50,7 @@ class Quaternion(Module):
Q = a + b \cdot \mathbf{i} + c \cdot \mathbf{j} + d \cdot \mathbf{k}
- Thus, we represent a rotation quaternion as a contiguous tensor structure to
+ Thus, we represent a rotation quaternion as a contiguous torch.tensor structure to
perform rigid bodies transformations:
.. math::
@@ -74,16 +74,16 @@ class Quaternion(Module):
"""
- _data: Union[Tensor, Parameter]
+ _data: Union[torch.Tensor, nn.Parameter]
- def __init__(self, data: Union[Tensor, Parameter]) -> None:
- """Construct a quaternion from tensor or parameter data.
+ def __init__(self, data: Union[torch.Tensor, nn.Parameter]) -> None:
+ """Construct a quaternion from torch.tensor or parameter data.
Args:
- data: tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
+ data: torch.tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
Example:
- >>> # Create with tensor (no gradients tracked by default)
+ >>> # Create with torch.tensor(no gradients tracked by default)
>>> data = torch.tensor([1., 0., 0., 0.])
>>> q1 = Quaternion(data)
>>> # Create with parameter (gradients tracked)
@@ -92,8 +92,8 @@ class Quaternion(Module):
"""
super().__init__()
- if not isinstance(data, (Tensor, Parameter)):
- raise TypeError(f"Expected Tensor or Parameter, got {type(data)}")
+ if not isinstance(data, (torch.Tensor, nn.Parameter)):
+ raise TypeError(f"Expected torch.Tensor or nn.Parameter, got {type(data)}")
# KORNIA_CHECK_SHAPE(data, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba
self._data = data
@@ -101,21 +101,21 @@ class Quaternion(Module):
"""Move and/or cast the quaternion data.
Args:
- *args: Arguments to pass to tensor.to()
- **kwargs: Keyword arguments to pass to tensor.to()
+ *args: Arguments to pass to torch.tensor.to()
+ **kwargs: Keyword arguments to pass to torch.tensor.to()
Returns:
A new Quaternion with converted data.
"""
return Quaternion(self._data.to(*args, **kwargs))
- def _to_scalar_quaternion(self, value: Union[Tensor, float]) -> "Quaternion":
- """Convert a scalar, tensor, or numeric value to a scalar quaternion.
+ def _to_scalar_quaternion(self, value: Union[torch.Tensor, float]) -> "Quaternion":
+ """Convert a scalar, torch.tensor, or numeric value to a scalar quaternion.
- A scalar quaternion has the form [real, 0, 0, 0] where real is the input value.
+ A scalar quaternion has the form [real, 0, 0, 0] torch.where real is the input value.
Args:
- value: The scalar, tensor, or numeric value to convert.
+ value: The scalar, torch.tensor, or numeric value to convert.
Returns:
A Quaternion object representing the scalar quaternion.
@@ -166,15 +166,15 @@ class Quaternion(Module):
"""
return Quaternion(-self.data)
- def __add__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
- """Add a given quaternion, scalar, or tensor.
+ def __add__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
+ """Add a given quaternion, scalar, or torch.tensor.
Args:
- right: the quaternion, scalar, or tensor to add.
+ right: the quaternion, scalar, or torch.tensor to add.
Example:
>>> q1 = Quaternion.identity()
- >>> q2 = Quaternion(tensor([2., 0., 1., 1.]))
+ >>> q2 = Quaternion(torch.tensor([2., 0., 1., 1.]))
>>> q3 = q1 + q2
>>> q3.data
tensor([3., 0., 1., 1.])
@@ -186,14 +186,14 @@ class Quaternion(Module):
right_quat = self._to_scalar_quaternion(right)
return Quaternion(self.data + right_quat.data)
- def __sub__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
- """Subtract a given quaternion, scalar, or tensor.
+ def __sub__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
+ """Subtract a given quaternion, scalar, or torch.tensor.
Args:
- right: the quaternion, scalar, or tensor to subtract.
+ right: the quaternion, scalar, or torch.tensor to subtract.
Example:
- >>> q1 = Quaternion(tensor([2., 0., 1., 1.]))
+ >>> q1 = Quaternion(torch.tensor([2., 0., 1., 1.]))
>>> q2 = Quaternion.identity()
>>> q3 = q1 - q2
>>> q3.data
@@ -204,13 +204,13 @@ class Quaternion(Module):
return Quaternion(self.data - right.data)
else:
right_quat = self._to_scalar_quaternion(right)
- # For scalar operations, ensure we return a tensor to preserve gradients
+ # For scalar operations, ensure we return a torch.tensor to preserve gradients
result_data = self.data - right_quat.data
- if isinstance(result_data, Parameter):
- result_data = result_data.data # Convert to tensor to preserve gradients
+ if isinstance(result_data, nn.Parameter):
+ result_data = result_data.data # Convert to torch.tensor to preserve gradients
return Quaternion(result_data)
- def __mul__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
+ def __mul__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
# If right is a Quaternion, do quaternion multiplication
if isinstance(right, Quaternion):
new_real = self.real * right.real - batched_dot_product(self.vec, right.vec)
@@ -219,9 +219,9 @@ class Quaternion(Module):
+ right.real[..., None] * self.vec
+ torch.linalg.cross(self.vec, right.vec, dim=-1)
)
- return Quaternion(concatenate((new_real[..., None], new_vec), -1))
+ return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
- # If right is a scalar/tensor, convert to scalar quaternion and multiply
+ # If right is a scalar/torch.tensor, convert to scalar quaternion and multiply
else:
right_quat = self._to_scalar_quaternion(right)
new_real = self.real * right_quat.real - batched_dot_product(self.vec, right_quat.vec)
@@ -230,10 +230,10 @@ class Quaternion(Module):
+ right_quat.real[..., None] * self.vec
+ torch.linalg.cross(self.vec, right_quat.vec, dim=-1)
)
- return Quaternion(concatenate((new_real[..., None], new_vec), -1))
+ return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
- def __rmul__(self, left: Union[Tensor, float]) -> "Quaternion":
- """Right multiplication (left * self) where left is a scalar or tensor."""
+ def __rmul__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
+ """Right multiplication (left * self) torch.where left is a scalar or torch.tensor."""
left_quat = self._to_scalar_quaternion(left)
new_real = left_quat.real * self.real - batched_dot_product(left_quat.vec, self.vec)
new_vec = (
@@ -241,9 +241,9 @@ class Quaternion(Module):
+ self.real[..., None] * left_quat.vec
+ torch.linalg.cross(left_quat.vec, self.vec, dim=-1)
)
- return Quaternion(concatenate((new_real[..., None], new_vec), -1))
+ return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
- def __div__(self, right: Union[Tensor, "Quaternion", float]) -> "Quaternion":
+ def __div__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":
if isinstance(right, Quaternion):
return self * right.inv()
else:
@@ -257,35 +257,35 @@ class Quaternion(Module):
if right_tensor.dim() == 0: # scalar
divisor = right_tensor.expand_as(self.data[..., 0]).unsqueeze(-1).expand_as(self.data)
else:
- # Broadcast the tensor to match the quaternion dimensions
+ # Broadcast the torch.tensor to match the quaternion dimensions
divisor = right_tensor.unsqueeze(-1).expand_as(self.data)
- # For scalar operations, ensure we return a tensor to preserve gradients
+ # For scalar operations, ensure we return a torch.tensor to preserve gradients
result_data = self.data / divisor
- if isinstance(result_data, Parameter):
- result_data = result_data.data # Convert to tensor to preserve gradients
+ if isinstance(result_data, nn.Parameter):
+ result_data = result_data.data # Convert to torch.tensor to preserve gradients
return Quaternion(result_data)
- def __truediv__(self, right: Union[Tensor, "Quaternion", float]) -> "Quaternion":
+ def __truediv__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":
return self.__div__(right)
- def __radd__(self, left: Union[Tensor, float]) -> "Quaternion":
- """Right addition (left + self) where left is a scalar or tensor."""
+ def __radd__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
+ """Right addition (left + self) torch.where left is a scalar or torch.tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat + self
- def __rsub__(self, left: Union[Tensor, float]) -> "Quaternion":
- """Right subtraction (left - self) where left is a scalar or tensor."""
+ def __rsub__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
+ """Right subtraction (left - self) torch.where left is a scalar or torch.tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat - self
- def __rtruediv__(self, left: Union[Tensor, float]) -> "Quaternion":
- """Right division (left / self) where left is a scalar or tensor."""
+ def __rtruediv__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
+ """Right division (left / self) torch.where left is a scalar or torch.tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat / self
- def __rdiv__(self, left: Union[Tensor, float]) -> "Quaternion":
- """Right division (left / self) where left is a scalar or tensor."""
+ def __rdiv__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
+ """Right division (left / self) torch.where left is a scalar or torch.tensor."""
return self.__rtruediv__(left)
def __pow__(self, t: float) -> "Quaternion":
@@ -295,29 +295,29 @@ class Quaternion(Module):
t: raised exponent.
Example:
- >>> q = Quaternion(tensor([1., .5, 0., 0.]))
+ >>> q = Quaternion(torch.tensor([1., .5, 0., 0.]))
>>> q_pow = q**2
"""
theta = self.polar_angle[..., None]
vec_norm = self.vec.norm(dim=-1, keepdim=True)
- n = where(vec_norm != 0, self.vec / vec_norm, self.vec * 0)
+ n = torch.where(vec_norm != 0, self.vec / vec_norm, self.vec * 0)
w = (t * theta).cos()
xyz = (t * theta).sin() * n
- return Quaternion(concatenate((w, xyz), -1))
+ return Quaternion(torch.cat((w, xyz), -1))
@property
- def data(self) -> Tensor:
+ def data(self) -> torch.Tensor:
"""Return the underlying data with shape :math:`(B, 4)`."""
return self._data
@property
- def coeffs(self) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+ def coeffs(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Return a tuple with the underlying coefficients in WXYZ order."""
return self.w, self.x, self.y, self.z
@property
- def real(self) -> Tensor:
+ def real(self) -> torch.Tensor:
"""Return the real part with shape :math:`(B,)`.
Alias for
@@ -326,12 +326,12 @@ class Quaternion(Module):
return self.w
@property
- def vec(self) -> Tensor:
+ def vec(self) -> torch.Tensor:
"""Return the vector with the imaginary part with shape :math:`(B, 3)`."""
return self.data[..., 1:]
@property
- def q(self) -> Tensor:
+ def q(self) -> torch.Tensor:
"""Return the underlying data with shape :math:`(B, 4)`.
Alias for :func:`~kornia.geometry.quaternion.Quaternion.data`
@@ -339,7 +339,7 @@ class Quaternion(Module):
return self.data
@property
- def scalar(self) -> Tensor:
+ def scalar(self) -> torch.Tensor:
"""Return a scalar with the real with shape :math:`(B,)`.
Alias for
@@ -348,22 +348,22 @@ class Quaternion(Module):
return self.real
@property
- def w(self) -> Tensor:
+ def w(self) -> torch.Tensor:
"""Return the :math:`q_w` with shape :math:`(B,)`."""
return self.data[..., 0]
@property
- def x(self) -> Tensor:
+ def x(self) -> torch.Tensor:
"""Return the :math:`q_x` with shape :math:`(B,)`."""
return self.data[..., 1]
@property
- def y(self) -> Tensor:
+ def y(self) -> torch.Tensor:
"""Return the :math:`q_y` with shape :math:`(B,)`."""
return self.data[..., 2]
@property
- def z(self) -> Tensor:
+ def z(self) -> torch.Tensor:
"""Return the :math:`q_z` with shape :math:`(B,)`."""
return self.data[..., 3]
@@ -373,7 +373,7 @@ class Quaternion(Module):
return tuple(self.data.shape)
@property
- def polar_angle(self) -> Tensor:
+ def polar_angle(self) -> torch.Tensor:
"""Return the polar angle with shape :math:`(B,1)`.
Example:
@@ -384,7 +384,7 @@ class Quaternion(Module):
"""
return (self.scalar / self.norm()).acos()
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
"""Convert the quaternion to a rotation matrix of shape :math:`(B, 3, 3)`.
Example:
@@ -399,7 +399,7 @@ class Quaternion(Module):
return quaternion_to_rotation_matrix(self.data)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> "Quaternion":
+ def from_matrix(cls, matrix: torch.Tensor) -> "Quaternion":
"""Create a quaternion from a rotation matrix.
Args:
@@ -415,7 +415,7 @@ class Quaternion(Module):
return cls(rotation_matrix_to_quaternion(matrix))
@classmethod
- def from_euler(cls, roll: Tensor, pitch: Tensor, yaw: Tensor) -> "Quaternion":
+ def from_euler(cls, roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) -> "Quaternion":
"""Create a quaternion from Euler angles.
Args:
@@ -424,21 +424,21 @@ class Quaternion(Module):
yaw: the yaw euler angle.
Example:
- >>> roll, pitch, yaw = tensor(0), tensor(1), tensor(0)
+ >>> roll, pitch, yaw = torch.tensor(0), torch.tensor(1), torch.tensor(0)
>>> q = Quaternion.from_euler(roll, pitch, yaw)
>>> q.data
tensor([0.8776, 0.0000, 0.4794, 0.0000])
"""
w, x, y, z = quaternion_from_euler(roll=roll, pitch=pitch, yaw=yaw)
- q = stack((w, x, y, z), -1)
+ q = torch.stack((w, x, y, z), -1)
return cls(q)
- def to_euler(self) -> Tuple[Tensor, Tensor, Tensor]:
+ def to_euler(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert the quaternion to a triple of Euler angles (roll, pitch, yaw).
Example:
- >>> q = Quaternion(tensor([2., 0., 1., 1.]))
+ >>> q = Quaternion(torch.tensor([2., 0., 1., 1.]))
>>> roll, pitch, yaw = q.to_euler()
>>> roll
tensor(2.0344)
@@ -451,7 +451,7 @@ class Quaternion(Module):
return euler_from_quaternion(self.w, self.x, self.y, self.z)
@classmethod
- def from_axis_angle(cls, axis_angle: Tensor) -> "Quaternion":
+ def from_axis_angle(cls, axis_angle: torch.Tensor) -> "Quaternion":
"""Create a quaternion from axis-angle representation.
Args:
@@ -466,7 +466,7 @@ class Quaternion(Module):
"""
return cls(axis_angle_to_quaternion(axis_angle))
- def to_axis_angle(self) -> Tensor:
+ def to_axis_angle(self) -> torch.Tensor:
"""Convert the quaternion to an axis-angle representation.
Example:
@@ -480,7 +480,10 @@ class Quaternion(Module):
@classmethod
def identity(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
) -> "Quaternion":
"""Create a quaternion representing an identity rotation.
@@ -495,7 +498,7 @@ class Quaternion(Module):
tensor([1., 0., 0., 0.])
"""
- data = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+ data = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
data = data.repeat(batch_size, 1)
return cls(data)
@@ -516,13 +519,16 @@ class Quaternion(Module):
tensor([1., 0., 0., 0.])
"""
- return cls(tensor([w, x, y, z]))
+ return cls(torch.tensor([w, x, y, z]))
# TODO: update signature
# def random(cls, shape: Optional[List] = None, device = None, dtype = None) -> 'Quaternion':
@classmethod
def random(
- cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
+ cls,
+ batch_size: Optional[int] = None,
+ device: Optional[Union[str, torch.device, None]] = None,
+ dtype: Union[torch.dtype, None] = None,
) -> "Quaternion":
"""Create a random unit quaternion of shape :math:`(B, 4)`.
@@ -540,12 +546,12 @@ class Quaternion(Module):
"""
rand_shape = (batch_size,) if batch_size is not None else ()
- r1, r2, r3 = rand((3, *rand_shape), device=device, dtype=dtype)
+ r1, r2, r3 = torch.rand((3, *rand_shape), device=device, dtype=dtype)
q1 = (1.0 - r1).sqrt() * ((2 * pi * r2).sin())
q2 = (1.0 - r1).sqrt() * ((2 * pi * r2).cos())
q3 = r1.sqrt() * (2 * pi * r3).sin()
q4 = r1.sqrt() * (2 * pi * r3).cos()
- return cls(stack((q1, q2, q3, q4), -1))
+ return cls(torch.stack((q1, q2, q3, q4), -1))
def slerp(self, q1: "Quaternion", t: float) -> "Quaternion":
"""Return a unit quaternion spherically interpolated between quaternions self.q and q1.
@@ -567,14 +573,14 @@ class Quaternion(Module):
q1 = q1.normalize()
return q0 * (q0.inv() * q1) ** t
- def norm(self, keepdim: bool = False) -> Tensor:
+ def norm(self, keepdim: bool = False) -> torch.Tensor:
"""Compute the norm (magnitude) of the quaternion.
Args:
keepdim: whether to retain the last dimension.
Returns:
- The norm of the quaternion(s) as a tensor.
+ The norm of the quaternion(s) as a torch.tensor.
Example:
>>> q = Quaternion.identity()
@@ -592,7 +598,7 @@ class Quaternion(Module):
The normalized quaternion.
Example:
- >>> q = Quaternion(tensor([2., 1., 0., 0.]))
+ >>> q = Quaternion(torch.tensor([2., 1., 0., 0.]))
>>> q_norm = q.normalize()
"""
@@ -605,11 +611,11 @@ class Quaternion(Module):
The conjugate quaternion, with the vector part negated.
Example:
- >>> q = Quaternion(tensor([1., 2., 3., 4.]))
+ >>> q = Quaternion(torch.tensor([1., 2., 3., 4.]))
>>> q_conj = q.conj()
"""
- return Quaternion(concatenate((self.real[..., None], -self.vec), -1))
+ return Quaternion(torch.cat((self.real[..., None], -self.vec), -1))
def inv(self) -> "Quaternion":
"""Compute the inverse of the quaternion.
@@ -624,11 +630,11 @@ class Quaternion(Module):
"""
return self.conj() / self.squared_norm()
- def squared_norm(self) -> Tensor:
+ def squared_norm(self) -> torch.Tensor:
"""Compute the squared norm (magnitude) of the quaternion.
Returns:
- The squared norm of the quaternion(s) as a tensor.
+ The squared norm of the quaternion(s) as a torch.tensor.
Example:
>>> q = Quaternion.identity()
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 3eafb3f74..1462c7761 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -15,15 +15,15 @@
# limitations under the License.
#
-"""Module containing RANSAC modules."""
+"""nn.Module containing RANSAC modules."""
import math
from functools import partial
-from typing import Callable, Optional, Tuple
+from typing import Callable, Optional, Tuple, Union
import torch
+from torch import nn
-from kornia.core import Device, Module, Tensor, zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry import (
find_fundamental,
@@ -42,8 +42,8 @@ from kornia.geometry.homography import (
__all__ = ["RANSAC"]
-class RANSAC(Module):
- """Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.
+class RANSAC(nn.Module):
+ """nn.Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.
Args:
model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",
@@ -87,9 +87,9 @@ class RANSAC(Module):
self.max_lo_iters = max_lo_iters
self.model_type = model_type
- self.error_fn: Callable[..., Tensor]
- self.minimal_solver: Callable[..., Tensor]
- self.polisher_solver: Callable[..., Tensor]
+ self.error_fn: Callable[..., torch.Tensor]
+ self.minimal_solver: Callable[..., torch.Tensor]
+ self.polisher_solver: Callable[..., torch.Tensor]
if model_type == "homography":
self.error_fn = oneway_transfer_error
@@ -114,7 +114,9 @@ class RANSAC(Module):
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
- def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Optional[Device] = None) -> Tensor:
+ def sample(
+ self, sample_size: int, pop_size: int, batch_size: int, device: Optional[Union[str, torch.device, None]] = None
+ ) -> torch.Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches.
Yields the benefit of the parallel processing, esp. on GPU.
@@ -126,13 +128,13 @@ class RANSAC(Module):
device: device to place the samples on.
Returns:
- Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.
+ torch.Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.
"""
if device is None:
device = torch.device("cpu")
- rand = torch.rand(batch_size, pop_size, device=device)
- _, out = rand.topk(k=sample_size, dim=1)
+ rand_tensor = torch.rand(batch_size, pop_size, device=device)
+ _, out = rand_tensor.topk(k=sample_size, dim=1)
return out
@staticmethod
@@ -156,7 +158,7 @@ class RANSAC(Module):
return 1.0
return math.log(1.0 - conf) / min(-eps, math.log(max(eps, 1.0 - math.pow(n_inl / num_tc, sample_size))))
- def estimate_model_from_minsample(self, kp1: Tensor, kp2: Tensor) -> Tensor:
+ def estimate_model_from_minsample(self, kp1: torch.Tensor, kp2: torch.Tensor) -> torch.Tensor:
"""Estimate models from minimal samples.
Args:
@@ -164,14 +166,16 @@ class RANSAC(Module):
kp2: target keypoints with shape :math:`(batch_size, sample_size, 2)`.
Returns:
- Estimated models tensor.
+ Estimated models torch.tensor.
"""
batch_size, sample_size = kp1.shape[:2]
H = self.minimal_solver(kp1, kp2, torch.ones(batch_size, sample_size, dtype=kp1.dtype, device=kp1.device))
return H
- def verify(self, kp1: Tensor, kp2: Tensor, models: Tensor, inl_th: float) -> Tuple[Tensor, Tensor, float]:
+ def verify(
+ self, kp1: torch.Tensor, kp2: torch.Tensor, models: torch.Tensor, inl_th: float
+ ) -> Tuple[torch.Tensor, torch.Tensor, float]:
"""Verify models by computing inliers and selecting the best model.
Args:
@@ -204,7 +208,7 @@ class RANSAC(Module):
inliers_best = inl[best_model_idx]
return model_best, inliers_best, best_model_score
- def remove_bad_samples(self, kp1: Tensor, kp2: Tensor) -> Tuple[Tensor, Tensor]:
+ def remove_bad_samples(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Remove degenerate samples based on model-specific constraints.
Args:
@@ -222,14 +226,14 @@ class RANSAC(Module):
return kp1[mask], kp2[mask]
return kp1, kp2
- def remove_bad_models(self, models: Tensor) -> Tensor:
+ def remove_bad_models(self, models: torch.Tensor) -> torch.Tensor:
"""Remove degenerate models based on simple heuristics.
Args:
models: candidate models to filter.
Returns:
- Filtered models tensor.
+ Filtered models torch.tensor.
"""
# ToDo: add more and better degenerate model rejection
@@ -238,7 +242,7 @@ class RANSAC(Module):
mask = main_diagonal.abs().min(dim=1)[0] > 1e-4
return models[mask]
- def polish_model(self, kp1: Tensor, kp2: Tensor, inliers: Tensor) -> Tensor:
+ def polish_model(self, kp1: torch.Tensor, kp2: torch.Tensor, inliers: torch.Tensor) -> torch.Tensor:
"""Polish the model using inliers through local optimization.
Args:
@@ -247,7 +251,7 @@ class RANSAC(Module):
inliers: boolean mask indicating inlier correspondences.
Returns:
- Polished model tensor.
+ Polished model torch.tensor.
"""
# TODO: Replace this with MAGSAC++ polisher
@@ -259,7 +263,7 @@ class RANSAC(Module):
)
return model
- def validate_inputs(self, kp1: Tensor, kp2: Tensor, weights: Optional[Tensor] = None) -> None:
+ def validate_inputs(self, kp1: torch.Tensor, kp2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> None:
"""Validate input tensors for shape and size requirements.
Args:
@@ -289,7 +293,9 @@ class RANSAC(Module):
f" {kp2.shape}"
)
- def forward(self, kp1: Tensor, kp2: Tensor, weights: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ def forward(
+ self, kp1: torch.Tensor, kp2: torch.Tensor, weights: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Call main forward method to execute the RANSAC algorithm.
Args:
@@ -299,14 +305,14 @@ class RANSAC(Module):
Returns:
- Estimated model, shape of :math:`(1, 3, 3)`.
- - The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences.
+ - The inlier/outlier mask, shape of :math:`(1, N)`, torch.where N is number of input correspondences.
"""
self.validate_inputs(kp1, kp2, weights)
best_score_total: float = float(self.minimal_sample_size)
num_tc: int = len(kp1)
- best_model_total = zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
- inliers_best_total: Tensor = zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
+ best_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
+ inliers_best_total: torch.Tensor = torch.zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
for i in range(self.max_iter):
# Sample minimal samples in batch to estimate models
idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, kp1.device)
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index aa3edf12d..6f1530172 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -15,18 +15,17 @@
# limitations under the License.
#
-"""Module containing the functionalities for computing the real roots of polynomial equation."""
+"""nn.Module containing the functionalities for computing the real roots of polynomial equation."""
import math
import torch
-from kornia.core import Tensor, cos, ones_like, stack, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_SHAPE
# Reference : https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/polynom_solver.cpp
-def solve_quadratic(coeffs: Tensor) -> Tensor:
+def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:
r"""Solve given quadratic equation.
The function takes the coefficients of quadratic equation and returns the real roots.
@@ -37,15 +36,15 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
coeffs : The coefficients of quadratic equation :`(B, 3)`
Returns:
- A tensor of shape `(B, 2)` containing the real roots to the quadratic equation.
+ A torch.tensor of shape `(B, 2)` containing the real roots to the quadratic equation.
Example:
>>> coeffs = torch.tensor([[1., 4., 4.]])
>>> roots = solve_quadratic(coeffs)
.. note::
- In cases where a quadratic polynomial has only one real root, the output will be in the format
- [real_root, 0]. And for the complex roots should be represented as 0. This is done to maintain
+ In cases torch.where a quadratic polynomial has only one real root, the output will be in the format
+ [real_root, 0]. And for the torch.complex roots should be represented as 0. This is done to maintain
a consistent output shape for all cases.
"""
@@ -66,15 +65,15 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
# Calculate 1/(2*a) for efficient computation
inv_2a = 0.5 / a
- # Initialize solutions tensor
- solutions = zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
+ # Initialize solutions torch.tensor
+ solutions = torch.zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
# Handle cases with zero discriminant
if torch.any(mask_zero):
solutions[mask_zero, 0] = -b[mask_zero] * inv_2a[mask_zero]
solutions[mask_zero, 1] = solutions[mask_zero, 0]
- # Negative discriminant cases are automatically handled since solutions is initialized with zeros.
+ # Negative discriminant cases are automatically handled since solutions is initialized with torch.zeros.
sqrt_delta = torch.sqrt(delta)
@@ -87,7 +86,7 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
return solutions
-def solve_cubic(coeffs: Tensor) -> Tensor:
+def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
r"""Solve given cubic equation.
The function takes the coefficients of cubic equation and returns
@@ -99,14 +98,14 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
coeffs : The coefficients cubic equation : `(B, 4)`
Returns:
- A tensor of shape `(B, 3)` containing the real roots to the cubic equation.
+ A torch.tensor of shape `(B, 3)` containing the real roots to the cubic equation.
Example:
>>> coeffs = torch.tensor([[32., 3., -11., -6.]])
>>> roots = solve_cubic(coeffs)
.. note::
- In cases where a cubic polynomial has only one or two real roots, the output for the non-real
+ In cases torch.where a cubic polynomial has only one or two real roots, the output for the non-real
roots should be represented as 0. Thus, the output for a single real root should be in the
format [real_root, 0, 0], and for two real roots, it should be [real_root_1, real_root_2, 0].
@@ -121,14 +120,14 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
c = coeffs[:, 2] # coefficient of x
d = coeffs[:, 3] # constant term
- solutions = zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
+ solutions = torch.zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
mask_a_zero = a == 0
mask_b_zero = b == 0
mask_c_zero = c == 0
- # Zero order cases are automatically handled since solutions is initialized with zeros.
- # No need for explicit handling of mask_zero_order as solutions already contains zeros by default.
+ # Zero order cases are automatically handled since solutions is initialized with torch.zeros.
+ # No need for explicit handling of mask_zero_order as solutions already contains torch.zeros by default.
mask_first_order = mask_a_zero & mask_b_zero & ~mask_c_zero
mask_second_order = mask_a_zero & ~mask_b_zero & ~mask_c_zero
@@ -154,9 +153,9 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
D = Q3 + R * R
b_a_3 = (1.0 / 3.0) * b_a
- a_Q_zero = ones_like(a)
- a_R_zero = ones_like(a)
- a_D_zero = ones_like(a)
+ a_Q_zero = torch.ones_like(a)
+ a_R_zero = torch.ones_like(a)
+ a_D_zero = torch.ones_like(a)
a_Q_zero[~mask_a_zero] = Q
a_R_zero[~mask_a_zero] = R
@@ -174,7 +173,7 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
mask_QR_zero_solutions = (a_Q_zero == 0) & (a_R_zero == 0)
if torch.any(mask_QR_zero):
- solutions[mask_QR_zero_solutions] = stack(
+ solutions[mask_QR_zero_solutions] = torch.stack(
[-b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero]], dim=1
)
@@ -185,19 +184,19 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
if torch.any(mask_D_zero):
theta_D_zero = torch.acos(R[mask_D_zero] / torch.sqrt(-Q3[mask_D_zero]))
sqrt_Q_D_zero = torch.sqrt(-Q[mask_D_zero])
- x0_D_zero = 2 * sqrt_Q_D_zero * cos(theta_D_zero / 3.0) - b_a_3[mask_D_zero]
- x1_D_zero = 2 * sqrt_Q_D_zero * cos((theta_D_zero + 2 * _PI) / 3.0) - b_a_3[mask_D_zero]
- x2_D_zero = 2 * sqrt_Q_D_zero * cos((theta_D_zero + 4 * _PI) / 3.0) - b_a_3[mask_D_zero]
- solutions[mask_D_zero_solutions] = stack([x0_D_zero, x1_D_zero, x2_D_zero], dim=1)
+ x0_D_zero = 2 * sqrt_Q_D_zero * torch.cos(theta_D_zero / 3.0) - b_a_3[mask_D_zero]
+ x1_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 2 * _PI) / 3.0) - b_a_3[mask_D_zero]
+ x2_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 4 * _PI) / 3.0) - b_a_3[mask_D_zero]
+ solutions[mask_D_zero_solutions] = torch.stack([x0_D_zero, x1_D_zero, x2_D_zero], dim=1)
- a_D_positive = zeros_like(a)
+ a_D_positive = torch.zeros_like(a)
a_D_positive[~mask_a_zero] = D
# D > 0
mask_D_positive_solution = (a_D_positive > 0) & (a_Q_zero != 0)
mask_D_positive = (D > 0) & (Q != 0)
if torch.any(mask_D_positive):
- AD = zeros_like(R)
- BD = zeros_like(R)
+ AD = torch.zeros_like(R)
+ BD = torch.zeros_like(R)
R_abs = torch.abs(R)
mask_R_positive = R_abs > 1e-16
if torch.any(mask_R_positive):
@@ -214,7 +213,7 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
return solutions
-# def solve_quartic(coeffs: Tensor) -> Tensor:
+# def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
# TODO: Quartic equation solver
# return solutions
@@ -1794,12 +1793,12 @@ coefficient_map = torch.tensor(
def determinant_to_polynomial(
- A: Tensor,
-) -> Tensor:
+ A: torch.Tensor,
+) -> torch.Tensor:
r"""Represent the determinant by the 10th polynomial, used for 5PC solver [@nister2004efficient].
Args:
- A: Tensor :math:`(*, 3, 13)`.
+ A: torch.Tensor :math:`(*, 3, 13)`.
Returns:
a degree 10 poly, representing determinant (Eqn. 14 in the paper).
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 498e90cc4..017727682 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -25,25 +25,25 @@ from __future__ import annotations
from typing import Optional
import torch
+import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, softmax
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils.grid import create_meshgrid
-def _validate_batched_image_tensor_input(tensor: Tensor) -> None:
+def _validate_batched_image_tensor_input(tensor: torch.Tensor) -> None:
KORNIA_CHECK_IS_TENSOR(tensor)
KORNIA_CHECK_SHAPE(tensor, ["B", "C", "H", "W"])
-def spatial_softmax2d(input: Tensor, temperature: Optional[Tensor] = None) -> Tensor:
+def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Apply the Softmax function over features in each image channel.
Note that this function behaves differently to :py:class:`torch.nn.Softmax2d`, which
instead applies Softmax over features at each spatial location.
Args:
- input: the input tensor with shape :math:`(B, N, H, W)`.
+ input: the input torch.tensor with shape :math:`(B, N, H, W)`.
temperature: factor to apply to input, adjusting the "smoothness" of the output distribution.
Returns:
@@ -68,19 +68,19 @@ def spatial_softmax2d(input: Tensor, temperature: Optional[Tensor] = None) -> Te
temperature = temperature.to(device=input.device, dtype=input.dtype)
x = input.view(batch_size, channels, -1)
- x_soft = softmax(x * temperature, dim=-1)
+ x_soft = F.softmax(x * temperature, dim=-1)
return x_soft.view(batch_size, channels, height, width)
-def spatial_expectation2d(input: Tensor, normalized_coordinates: bool = True) -> Tensor:
+def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = True) -> torch.Tensor:
r"""Compute the expectation of coordinate values using spatial probabilities.
The input heatmap is assumed to represent a valid spatial probability distribution,
which can be achieved using :func:`~kornia.geometry.subpixel.spatial_softmax2d`.
Args:
- input: the input tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.
+ input: the input torch.tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.
normalized_coordinates: whether to return the coordinates normalized in the range
of :math:`[-1, 1]`. Otherwise, it will return the coordinates in the range of the input shape.
@@ -113,12 +113,14 @@ def spatial_expectation2d(input: Tensor, normalized_coordinates: bool = True) ->
expected_y = torch.sum(pos_y * input_flat, -1, keepdim=True)
expected_x = torch.sum(pos_x * input_flat, -1, keepdim=True)
- output = concatenate([expected_x, expected_y], -1)
+ output = torch.cat([expected_x, expected_y], -1)
return output.view(batch_size, channels, 2) # BxNx2
-def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normalized_coordinates: bool = True) -> Tensor:
+def render_gaussian2d(
+ mean: torch.Tensor, std: torch.Tensor, size: tuple[int, int], normalized_coordinates: bool = True
+) -> torch.Tensor:
r"""Render the PDF of a 2D Gaussian distribution.
Args:
@@ -130,7 +132,7 @@ def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normaliz
in the range of :math:`[-1, 1]`. Otherwise, coordinates are assumed to be in the range of the output shape.
Returns:
- tensor including rendered points with shape :math:`(*, H, W)`.
+ torch.tensor including rendered points with shape :math:`(*, H, W)`.
"""
if not (std.dtype == mean.dtype and std.device == mean.device):
@@ -155,7 +157,7 @@ def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normaliz
# Gaussian PDF = exp(-(x - \mu)^2 / (2 \sigma^2))
# = exp(dists * ks),
- # where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
+ # torch.where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
# dists <- (x - \mu)^2
dist_x_sq = (xs - mu_x) ** 2
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 80f456f50..fa035a0e9 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -19,35 +19,34 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor, eye, pad, zeros
-
-def _get_nms_kernel2d(kx: int, ky: int) -> Tensor:
+def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:
"""Return neigh2channels conv kernel."""
numel: int = ky * kx
center: int = numel // 2
- weight = eye(numel)
+ weight = torch.eye(numel)
weight[center, center] = 0
return weight.view(numel, 1, ky, kx)
-def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> Tensor:
+def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
"""Return neigh2channels conv kernel."""
numel: int = kd * ky * kx
center: int = numel // 2
- weight = eye(numel)
+ weight = torch.eye(numel)
weight[center, center] = 0
return weight.view(numel, 1, kd, ky, kx)
-class NonMaximaSuppression2d(Module):
+class NonMaximaSuppression2d(nn.Module):
r"""Apply non maxima suppression to filter.
Flag `minima_are_also_good` is useful, when you want to detect both maxima and minima, e.g. for DoG
"""
- kernel: Tensor
+ kernel: torch.Tensor
def __init__(self, kernel_size: tuple[int, int]) -> None:
super().__init__()
@@ -67,14 +66,14 @@ class NonMaximaSuppression2d(Module):
return (x - 1) // 2 # zero padding function
ky, kx = kernel_size # we assume a cubic kernel
- return pad(ky), pad(ky), pad(kx), pad(kx)
+ return (pad(ky), pad(kx), pad(ky), pad(kx))
- def forward(self, x: Tensor, mask_only: bool = False) -> Tensor:
+ def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
if len(x.shape) != 4:
raise AssertionError(x.shape)
B, CH, H, W = x.size()
# find local maximum values
- x_padded = pad(x, list(self.padding)[::-1], mode="replicate")
+ x_padded = F.pad(x, list(self.padding)[::-1], mode="replicate")
B, CH, HP, WP = x_padded.size()
neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(
@@ -87,7 +86,7 @@ class NonMaximaSuppression2d(Module):
return x * (mask.to(x.dtype))
-class NonMaximaSuppression3d(Module):
+class NonMaximaSuppression3d(nn.Module):
r"""Apply non maxima suppression to filter."""
def __init__(self, kernel_size: tuple[int, int, int]) -> None:
@@ -108,15 +107,15 @@ class NonMaximaSuppression3d(Module):
return (x - 1) // 2 # zero padding function
kd, ky, kx = kernel_size # we assume a cubic kernel
- return pad(kd), pad(kd), pad(ky), pad(ky), pad(kx), pad(kx)
+ return (kd, kd, ky, ky, kx, kx)
- def forward(self, x: Tensor, mask_only: bool = False) -> Tensor:
+ def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
if len(x.shape) != 5:
raise AssertionError(x.shape)
# find local maximum values
B, CH, D, H, W = x.size()
if self.kernel_size == (3, 3, 3):
- mask = zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)
+ mask = torch.zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)
center = slice(1, -1)
left = slice(0, -2)
right = slice(2, None)
@@ -152,7 +151,7 @@ class NonMaximaSuppression3d(Module):
else:
max_non_center = (
F.conv3d(
- pad(x, list(self.padding)[::-1], mode="replicate"),
+ F.pad(x, list(self.padding)[::-1], mode="replicate"),
self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
stride=1,
groups=CH,
@@ -169,7 +168,7 @@ class NonMaximaSuppression3d(Module):
# functional api
-def nms2d(input: Tensor, kernel_size: tuple[int, int], mask_only: bool = False) -> Tensor:
+def nms2d(input: torch.Tensor, kernel_size: tuple[int, int], mask_only: bool = False) -> torch.Tensor:
r"""Apply non maxima suppression to filter.
See :class:`~kornia.geometry.subpix.NonMaximaSuppression2d` for details.
@@ -177,7 +176,7 @@ def nms2d(input: Tensor, kernel_size: tuple[int, int], mask_only: bool = False)
return NonMaximaSuppression2d(kernel_size)(input, mask_only)
-def nms3d(input: Tensor, kernel_size: tuple[int, int, int], mask_only: bool = False) -> Tensor:
+def nms3d(input: torch.Tensor, kernel_size: tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
r"""Apply non maxima suppression to filter.
See
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 4890608ac..dd960e2c6 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -21,8 +21,8 @@ from typing import Optional
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor, concatenate, rand, stack, tensor, where, zeros, zeros_like
from kornia.filters.sobel import spatial_gradient3d
from kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d
from kornia.utils import create_meshgrid, create_meshgrid3d
@@ -33,7 +33,7 @@ from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
-def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
+def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to with window coordinates, residual to window center.
Args:
@@ -53,7 +53,7 @@ def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = N
return conv_kernel
-def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
+def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to return center coordinates, when applied with F.conv2d to 2d coordinates grid.
Args:
@@ -67,7 +67,7 @@ def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None)
"""
if device is None:
device = torch.device("cpu")
- center_kernel = zeros(2, 2, h, w, device=device)
+ center_kernel = torch.zeros(2, 2, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
if h % 2 != 0:
@@ -86,7 +86,7 @@ def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None)
return center_kernel
-def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
+def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to return center coordinates, when applied with F.conv2d to 3d coordinates grid.
Args:
@@ -101,7 +101,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device]
"""
if device is None:
torch.device("cpu")
- center_kernel = zeros(3, 3, d, h, w, device=device)
+ center_kernel = torch.zeros(3, 3, d, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
if h % 2 != 0:
h_i1 = h // 2
@@ -126,7 +126,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device]
return center_kernel
-def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
+def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to return coordinates, residual to window center.
Args:
@@ -145,14 +145,14 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.dev
if d > 1:
z = torch.linspace(-1, 1, d, device=device).view(d, 1, 1, 1)
else: # only onr channel with index == 0
- z = zeros(1, 1, 1, 1, device=device)
- grid3d = concatenate([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], 3)
+ z = torch.zeros(1, 1, 1, 1, device=device)
+ grid3d = torch.cat([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], 3)
conv_kernel = grid3d.permute(3, 0, 1, 2).unsqueeze(1)
return conv_kernel
-class ConvSoftArgmax2d(Module):
- r"""Module that calculates soft argmax 2d per window.
+class ConvSoftArgmax2d(nn.Module):
+ r"""nn.Module that calculates soft argmax 2d per window.
See
:func: `~kornia.geometry.subpix.conv_soft_argmax2d` for details.
@@ -163,7 +163,7 @@ class ConvSoftArgmax2d(Module):
kernel_size: tuple[int, int] = (3, 3),
stride: tuple[int, int] = (1, 1),
padding: tuple[int, int] = (1, 1),
- temperature: Tensor | float = 1.0,
+ temperature: torch.Tensor | float = 1.0,
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
@@ -189,7 +189,7 @@ class ConvSoftArgmax2d(Module):
f"output_value={self.output_value})"
)
- def forward(self, x: Tensor) -> Tensor | tuple[Tensor, Tensor]:
+ def forward(self, x: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
return conv_soft_argmax2d(
x,
self.kernel_size,
@@ -202,8 +202,8 @@ class ConvSoftArgmax2d(Module):
)
-class ConvSoftArgmax3d(Module):
- r"""Module that calculates soft argmax 3d per window.
+class ConvSoftArgmax3d(nn.Module):
+ r"""nn.Module that calculates soft argmax 3d per window.
See
:func: `~kornia.geometry.subpix.conv_soft_argmax3d` for details.
@@ -214,7 +214,7 @@ class ConvSoftArgmax3d(Module):
kernel_size: tuple[int, int, int] = (3, 3, 3),
stride: tuple[int, int, int] = (1, 1, 1),
padding: tuple[int, int, int] = (1, 1, 1),
- temperature: Tensor | float = 1.0,
+ temperature: torch.Tensor | float = 1.0,
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
@@ -243,7 +243,7 @@ class ConvSoftArgmax3d(Module):
f"output_value={self.output_value})"
)
- def forward(self, x: Tensor) -> Tensor | tuple[Tensor, Tensor]:
+ def forward(self, x: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
return conv_soft_argmax3d(
x,
self.kernel_size,
@@ -258,15 +258,15 @@ class ConvSoftArgmax3d(Module):
def conv_soft_argmax2d(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int] = (3, 3),
stride: tuple[int, int] = (1, 1),
padding: tuple[int, int] = (1, 1),
- temperature: Tensor | float = 1.0,
+ temperature: torch.Tensor | float = 1.0,
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
-) -> Tensor | tuple[Tensor, Tensor]:
+) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
r"""Compute the convolutional spatial Soft-Argmax 2D over the windows of a given heatmap.
.. math::
@@ -275,7 +275,7 @@ def conv_soft_argmax2d(
.. math::
val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
- where :math:`T` is temperature.
+ torch.where :math:`T` is temperature.
Args:
input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.
@@ -293,7 +293,7 @@ def conv_soft_argmax2d(
On each window, the function computed returns with shapes :math:`(N, C, 2, H_{out},
W_{out})`, :math:`(N, C, H_{out}, W_{out})`,
- where
+ torch.where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -
@@ -309,13 +309,13 @@ def conv_soft_argmax2d(
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
if temperature <= 0:
- raise ValueError(f"Temperature should be positive float or tensor. Got: {temperature}")
+ raise ValueError(f"Temperature should be positive float or torch.tensor. Got: {temperature}")
b, c, h, w = input.shape
ky, kx = kernel_size
@@ -323,11 +323,11 @@ def conv_soft_argmax2d(
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, h, w)
- center_kernel: Tensor = _get_center_kernel2d(ky, kx, device).to(dtype)
- window_kernel: Tensor = _get_window_grid_kernel2d(ky, kx, device).to(dtype)
+ center_kernel: torch.Tensor = _get_center_kernel2d(ky, kx, device).to(dtype)
+ window_kernel: torch.Tensor = _get_window_grid_kernel2d(ky, kx, device).to(dtype)
# applies exponential normalization trick
- # https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/
+ # https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/
# https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44
x_max = F.adaptive_max_pool2d(input, (1, 1))
@@ -338,7 +338,7 @@ def conv_soft_argmax2d(
# Not available yet in version 1.0, so let's do manually
pool_coef: float = float(kx * ky)
- # softmax denominator
+ # F.softmax denominator
den = pool_coef * F.avg_pool2d(x_exp, kernel_size, stride=stride, padding=padding) + eps
x_softmaxpool = pool_coef * F.avg_pool2d(x_exp * input, kernel_size, stride=stride, padding=padding) / den
@@ -346,13 +346,13 @@ def conv_soft_argmax2d(
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)
+ grid_global: torch.Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)
grid_global_pooled = F.conv2d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
+ coords_max: torch.Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -372,16 +372,16 @@ def conv_soft_argmax2d(
def conv_soft_argmax3d(
- input: Tensor,
+ input: torch.Tensor,
kernel_size: tuple[int, int, int] = (3, 3, 3),
stride: tuple[int, int, int] = (1, 1, 1),
padding: tuple[int, int, int] = (1, 1, 1),
- temperature: Tensor | float = 1.0,
+ temperature: torch.Tensor | float = 1.0,
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
strict_maxima_bonus: float = 0.0,
-) -> Tensor | tuple[Tensor, Tensor]:
+) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
r"""Compute the convolutional spatial Soft-Argmax 3D over the windows of a given heatmap.
.. math::
@@ -390,7 +390,7 @@ def conv_soft_argmax3d(
.. math::
val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
- where ``T`` is temperature.
+ torch.where ``T`` is temperature.
Args:
input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.
@@ -410,7 +410,7 @@ def conv_soft_argmax3d(
On each window, the function computed returns with shapes :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`,
:math:`(N, C, D_{out}, H_{out}, W_{out})`,
- where
+ torch.where
.. math::
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
@@ -430,13 +430,13 @@ def conv_soft_argmax3d(
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not len(input.shape) == 5:
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
if temperature <= 0:
- raise ValueError(f"Temperature should be positive float or tensor. Got: {temperature}")
+ raise ValueError(f"Temperature should be positive float or torch.tensor. Got: {temperature}")
b, c, d, h, w = input.shape
kz, ky, kx = kernel_size
@@ -444,11 +444,11 @@ def conv_soft_argmax3d(
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, d, h, w)
- center_kernel: Tensor = _get_center_kernel3d(kz, ky, kx, device).to(dtype)
- window_kernel: Tensor = _get_window_grid_kernel3d(kz, ky, kx, device).to(dtype)
+ center_kernel: torch.Tensor = _get_center_kernel3d(kz, ky, kx, device).to(dtype)
+ window_kernel: torch.Tensor = _get_window_grid_kernel3d(kz, ky, kx, device).to(dtype)
# applies exponential normalization trick
- # https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/
+ # https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/
# https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44
x_max = F.adaptive_max_pool3d(input, (1, 1, 1))
@@ -457,18 +457,18 @@ def conv_soft_argmax3d(
pool_coef: float = float(kx * ky * kz)
- # softmax denominator
+ # F.softmax denominator
den = pool_coef * F.avg_pool3d(x_exp.view_as(input), kernel_size, stride=stride, padding=padding) + eps
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
+ grid_global: torch.Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
+ coords_max: torch.Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -493,7 +493,7 @@ def conv_soft_argmax3d(
in_levels: int = input.size(2)
out_levels: int = x_softmaxpool.size(2)
skip_levels: int = (in_levels - out_levels) // 2
- strict_maxima: Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)
+ strict_maxima: torch.Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)
strict_maxima = strict_maxima[:, :, skip_levels : out_levels - skip_levels]
x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maxima
x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))
@@ -501,8 +501,8 @@ def conv_soft_argmax3d(
def spatial_soft_argmax2d(
- input: Tensor, temperature: Optional[Tensor] = None, normalized_coordinates: bool = True
-) -> Tensor:
+ input: torch.Tensor, temperature: Optional[torch.Tensor] = None, normalized_coordinates: bool = True
+) -> torch.Tensor:
r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.
Args:
@@ -525,23 +525,23 @@ def spatial_soft_argmax2d(
"""
if temperature is None:
- temperature = tensor(1.0)
- input_soft: Tensor = spatial_softmax2d(input, temperature)
- output: Tensor = spatial_expectation2d(input_soft, normalized_coordinates)
+ temperature = torch.tensor(1.0)
+ input_soft: torch.Tensor = spatial_softmax2d(input, temperature)
+ output: torch.Tensor = spatial_expectation2d(input_soft, normalized_coordinates)
return output
-class SpatialSoftArgmax2d(Module):
+class SpatialSoftArgmax2d(nn.Module):
r"""Compute the Spatial Soft-Argmax 2D of a given heatmap.
See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
"""
- def __init__(self, temperature: Optional[Tensor] = None, normalized_coordinates: bool = True) -> None:
+ def __init__(self, temperature: Optional[torch.Tensor] = None, normalized_coordinates: bool = True) -> None:
super().__init__()
if temperature is None:
- temperature = tensor(1.0)
- self.temperature: Tensor = temperature
+ temperature = torch.tensor(1.0)
+ self.temperature: torch.Tensor = temperature
self.normalized_coordinates: bool = normalized_coordinates
def __repr__(self) -> str:
@@ -551,11 +551,13 @@ class SpatialSoftArgmax2d(Module):
f"normalized_coordinates={self.normalized_coordinates})"
)
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)
-def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> tuple[Tensor, Tensor]:
+def conv_quad_interp3d(
+ input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7
+) -> tuple[torch.Tensor, torch.Tensor]:
r"""Compute the single iteration of quadratic interpolation of the extremum (max or min).
Args:
@@ -568,7 +570,7 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
the location and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT.
:math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`,
- where
+ torch.where
.. math::
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
@@ -588,20 +590,20 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not len(input.shape) == 5:
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
B, CH, D, H, W = input.shape
- grid_global: Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
+ grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
grid_global = grid_global.to(input.dtype)
- # to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
+ # to determine the location we are solving system of linear equations Ax = b, torch.where b is 1st order gradient
# and A is Hessian matrix
- b: Tensor = spatial_gradient3d(input, order=1, mode="diff")
+ b: torch.Tensor = spatial_gradient3d(input, order=1, mode="diff")
b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)
- A: Tensor = spatial_gradient3d(input, order=2, mode="diff")
+ A: torch.Tensor = spatial_gradient3d(input, order=2, mode="diff")
A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)
dxx = A[..., 0]
dyy = A[..., 1]
@@ -610,40 +612,40 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation
dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
- Hes = stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], -1).view(-1, 3, 3)
+ Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], -1).view(-1, 3, 3)
if not torch_version_ge(1, 10):
# The following is needed to avoid singular cases
- Hes += rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
+ Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
- nms_mask: Tensor = nms3d(input, (3, 3, 3), True)
- x_solved: Tensor = zeros_like(b)
+ nms_mask: torch.Tensor = nms3d(input, (3, 3, 3), True)
+ x_solved: torch.Tensor = torch.zeros_like(b)
x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
- # Kill those points, where we cannot solve
+ # Kill those points, torch.where we cannot solve
new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)
- x_solved[where(new_nms_mask.view(-1, 1, 1))[0]] = x_solved_masked[solved_correctly]
+ x_solved[torch.where(new_nms_mask.view(-1, 1, 1))[0]] = x_solved_masked[solved_correctly]
- dx: Tensor = -x_solved
+ dx: torch.Tensor = -x_solved
- # Ignore ones, which are far from window center
+ # Ignore torch.ones, which are far from window center
mask1 = dx.abs().max(dim=1, keepdim=True)[0] > 0.7
dx.masked_fill_(mask1.expand_as(dx), 0)
- dy: Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
+ dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
y_max = input + dy.view(B, CH, D, H, W)
if strict_maxima_bonus > 0:
y_max += strict_maxima_bonus * new_nms_mask.to(input.dtype)
- dx_res: Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
+ dx_res: torch.Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
dx_res[:, :, (1, 2)] = dx_res[:, :, (2, 1)]
- coords_max: Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
+ coords_max: torch.Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
coords_max = coords_max + dx_res
return coords_max, y_max
-class ConvQuadInterp3d(Module):
+class ConvQuadInterp3d(nn.Module):
r"""Calculate soft argmax 3d per window.
See
@@ -658,5 +660,5 @@ class ConvQuadInterp3d(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(strict_maxima_bonus={self.strict_maxima_bonus})"
- def forward(self, x: Tensor) -> tuple[Tensor, Tensor]:
+ def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
return conv_quad_interp3d(x, self.strict_maxima_bonus, self.eps)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 19d774871..a737325ea 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -19,9 +19,8 @@ import warnings
from typing import Optional, Tuple, Union
import torch
+from torch import nn
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor, ones, ones_like, zeros
from kornia.filters import gaussian_blur2d
from kornia.utils import _extract_device_dtype
from kornia.utils.image import perform_keep_shape_image
@@ -52,18 +51,18 @@ __all__ = [
# utilities to compute affine matrices
-def _compute_tensor_center(tensor: Tensor) -> Tensor:
+def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
"""Compute the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W)."""
if not 2 <= len(tensor.shape) <= 4:
raise AssertionError(f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}.")
height, width = tensor.shape[-2:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
- center: Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
+ center: torch.Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
return center
-def _compute_tensor_center3d(tensor: Tensor) -> Tensor:
+def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
"""Compute the center of tensor plane for (D, H, W), (C, D, H, W) and (B, C, D, H, W)."""
if not 3 <= len(tensor.shape) <= 5:
raise AssertionError(f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}.")
@@ -71,18 +70,20 @@ def _compute_tensor_center3d(tensor: Tensor) -> Tensor:
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
center_z: float = float(depth - 1) / 2
- center: Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
+ center: torch.Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
return center
-def _compute_rotation_matrix(angle: Tensor, center: Tensor) -> Tensor:
+def _compute_rotation_matrix(angle: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Compute a pure affine rotation matrix."""
- scale: Tensor = ones_like(center)
- matrix: Tensor = get_rotation_matrix2d(center, angle, scale)
+ scale: torch.Tensor = torch.ones_like(center)
+ matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
-def _compute_rotation_matrix3d(yaw: Tensor, pitch: Tensor, roll: Tensor, center: Tensor) -> Tensor:
+def _compute_rotation_matrix3d(
+ yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor, center: torch.Tensor
+) -> torch.Tensor:
"""Compute a pure affine rotation matrix."""
if len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 0:
yaw = yaw.unsqueeze(dim=0)
@@ -97,15 +98,15 @@ def _compute_rotation_matrix3d(yaw: Tensor, pitch: Tensor, roll: Tensor, center:
if not (len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2):
raise AssertionError(f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}.")
- angles: Tensor = torch.cat([yaw, pitch, roll], dim=1)
- scales: Tensor = ones_like(yaw)
- matrix: Tensor = get_projective_transform(center, angles, scales)
+ angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)
+ scales: torch.Tensor = torch.ones_like(yaw)
+ matrix: torch.Tensor = get_projective_transform(center, angles, scales)
return matrix
-def _compute_translation_matrix(translation: Tensor) -> Tensor:
+def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for translation."""
- matrix: Tensor = eye_like(3, translation, shared_memory=False)
+ matrix: torch.Tensor = eye_like(3, translation, shared_memory=False)
dx, dy = torch.chunk(translation, chunks=2, dim=-1)
matrix[..., 0, 2:3] += dx
@@ -113,16 +114,16 @@ def _compute_translation_matrix(translation: Tensor) -> Tensor:
return matrix
-def _compute_scaling_matrix(scale: Tensor, center: Tensor) -> Tensor:
+def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for scaling."""
- angle: Tensor = zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)
- matrix: Tensor = get_rotation_matrix2d(center, angle, scale)
+ angle: torch.Tensor = torch.zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)
+ matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
-def _compute_shear_matrix(shear: Tensor) -> Tensor:
+def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for shearing."""
- matrix: Tensor = eye_like(3, shear, shared_memory=False)
+ matrix: torch.Tensor = eye_like(3, shear, shared_memory=False)
shx, shy = torch.chunk(shear, chunks=2, dim=-1)
matrix[..., 0, 1:2] += shx
@@ -135,12 +136,12 @@ def _compute_shear_matrix(shear: Tensor) -> Tensor:
def affine(
- tensor: Tensor,
- matrix: Tensor,
+ tensor: torch.Tensor,
+ matrix: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Apply an affine transformation to the image.
.. image:: _static/img/warp_affine.png
@@ -151,7 +152,7 @@ def affine(
matrix: The 2x3 affine transformation matrix.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -180,7 +181,7 @@ def affine(
# warp the input tensor
height: int = tensor.shape[-2]
width: int = tensor.shape[-1]
- warped: Tensor = warp_affine(tensor, matrix, (height, width), mode, padding_mode, align_corners)
+ warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode, padding_mode, align_corners)
# return in the original shape
if is_unbatched:
@@ -190,12 +191,12 @@ def affine(
def affine3d(
- tensor: Tensor,
- matrix: Tensor,
+ tensor: torch.Tensor,
+ matrix: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Apply an affine transformation to the 3d volume.
Args:
@@ -205,7 +206,7 @@ def affine3d(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- `` 'zeros'`` | ``'border'`` | ``'reflection'``.
+ `` 'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -232,7 +233,7 @@ def affine3d(
depth: int = tensor.shape[-3]
height: int = tensor.shape[-2]
width: int = tensor.shape[-1]
- warped: Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode, padding_mode, align_corners)
+ warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode, padding_mode, align_corners)
# return in the original shape
if is_unbatched:
@@ -246,13 +247,13 @@ def affine3d(
def rotate(
- tensor: Tensor,
- angle: Tensor,
- center: Union[None, Tensor] = None,
+ tensor: torch.Tensor,
+ angle: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Rotate the tensor anti-clockwise about the center.
.. image:: _static/img/rotate.png
@@ -260,14 +261,14 @@ def rotate(
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
angle: The angle through which to rotate. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B), torch.where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), where B is batch size and last
+ must have a shape of (B, 2), torch.where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -284,14 +285,14 @@ def rotate(
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
- if not isinstance(angle, Tensor):
- raise TypeError(f"Input angle type is not a Tensor. Got {type(angle)}")
+ if not isinstance(angle, torch.Tensor):
+ raise TypeError(f"Input angle type is not a torch.Tensor. Got {type(angle)}")
- if center is not None and not isinstance(center, Tensor):
- raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")
+ if center is not None and not isinstance(center, torch.Tensor):
+ raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")
if len(tensor.shape) not in (3, 4):
raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")
@@ -304,59 +305,59 @@ def rotate(
# TODO: add broadcasting to get_rotation_matrix2d for center
angle = angle.expand(tensor.shape[0])
center = center.expand(tensor.shape[0], -1)
- rotation_matrix: Tensor = _compute_rotation_matrix(angle, center)
+ rotation_matrix: torch.Tensor = _compute_rotation_matrix(angle, center)
# warp using the affine transform
return affine(tensor, rotation_matrix[..., :2, :3], mode, padding_mode, align_corners)
def rotate3d(
- tensor: Tensor,
- yaw: Tensor,
- pitch: Tensor,
- roll: Tensor,
- center: Union[None, Tensor] = None,
+ tensor: torch.Tensor,
+ yaw: torch.Tensor,
+ pitch: torch.Tensor,
+ roll: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Rotate 3D the tensor anti-clockwise about the centre.
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.
yaw: The yaw angle through which to rotate. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B), torch.where B is batch size.
pitch: The pitch angle through which to rotate. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B), torch.where B is batch size.
roll: The roll angle through which to rotate. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B), torch.where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), where B is batch size and last
+ must have a shape of (B, 2), torch.where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
- Tensor: The rotated tensor with shape as input.
+ torch.Tensor: The rotated tensor with shape as input.
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
- if not isinstance(yaw, Tensor):
- raise TypeError(f"yaw is not a Tensor. Got {type(yaw)}")
+ if not isinstance(yaw, torch.Tensor):
+ raise TypeError(f"yaw is not a torch.Tensor. Got {type(yaw)}")
- if not isinstance(pitch, Tensor):
- raise TypeError(f"pitch is not a Tensor. Got {type(pitch)}")
+ if not isinstance(pitch, torch.Tensor):
+ raise TypeError(f"pitch is not a torch.Tensor. Got {type(pitch)}")
- if not isinstance(roll, Tensor):
- raise TypeError(f"roll is not a Tensor. Got {type(roll)}")
+ if not isinstance(roll, torch.Tensor):
+ raise TypeError(f"roll is not a torch.Tensor. Got {type(roll)}")
- if center is not None and not isinstance(center, Tensor):
- raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")
+ if center is not None and not isinstance(center, torch.Tensor):
+ raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")
if len(tensor.shape) not in (4, 5):
raise ValueError(f"Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. Got: {tensor.shape}")
@@ -371,19 +372,19 @@ def rotate3d(
pitch = pitch.expand(tensor.shape[0])
roll = roll.expand(tensor.shape[0])
center = center.expand(tensor.shape[0], -1)
- rotation_matrix: Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)
+ rotation_matrix: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)
# warp using the affine transform
return affine3d(tensor, rotation_matrix[..., :3, :4], mode, padding_mode, align_corners)
def translate(
- tensor: Tensor,
- translation: Tensor,
+ tensor: torch.Tensor,
+ translation: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Translate the tensor in pixel units.
.. image:: _static/img/translate.png
@@ -392,11 +393,11 @@ def translate(
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
translation: tensor containing the amount of pixels to
translate in the x and y direction. The tensor must have a shape of
- (B, 2), where B is batch size, last dimension contains dx dy.
+ (B, 2), torch.where B is batch size, last dimension contains dx dy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -410,30 +411,30 @@ def translate(
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
- if not isinstance(translation, Tensor):
- raise TypeError(f"Input translation type is not a Tensor. Got {type(translation)}")
+ if not isinstance(translation, torch.Tensor):
+ raise TypeError(f"Input translation type is not a torch.Tensor. Got {type(translation)}")
if len(tensor.shape) not in (3, 4):
raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")
# compute the translation matrix
- translation_matrix: Tensor = _compute_translation_matrix(translation)
+ translation_matrix: torch.Tensor = _compute_translation_matrix(translation)
# warp using the affine transform
return affine(tensor, translation_matrix[..., :2, :3], mode, padding_mode, align_corners)
def scale(
- tensor: Tensor,
- scale_factor: Tensor,
- center: Union[None, Tensor] = None,
+ tensor: torch.Tensor,
+ scale_factor: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Scale the tensor by a factor.
.. image:: _static/img/scale.png
@@ -441,16 +442,16 @@ def scale(
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
scale_factor: The scale factor apply. The tensor
- must have a shape of (B) or (B, 2), where B is batch size.
+ must have a shape of (B) or (B, 2), torch.where B is batch size.
If (B), isotropic scaling will perform.
If (B, 2), x-y-direction specific scaling will perform.
center: The center through which to scale. The tensor
- must have a shape of (B, 2), where B is batch size and last
+ must have a shape of (B, 2), torch.where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -464,11 +465,11 @@ def scale(
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
- if not isinstance(scale_factor, Tensor):
- raise TypeError(f"Input scale_factor type is not a Tensor. Got {type(scale_factor)}")
+ if not isinstance(scale_factor, torch.Tensor):
+ raise TypeError(f"Input scale_factor type is not a torch.Tensor. Got {type(scale_factor)}")
if len(scale_factor.shape) == 1:
# convert isotropic scaling to x-y direction
@@ -482,19 +483,19 @@ def scale(
# TODO: add broadcasting to get_rotation_matrix2d for center
center = center.expand(tensor.shape[0], -1)
scale_factor = scale_factor.expand(tensor.shape[0], 2)
- scaling_matrix: Tensor = _compute_scaling_matrix(scale_factor, center)
+ scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)
# warp using the affine transform
return affine(tensor, scaling_matrix[..., :2, :3], mode, padding_mode, align_corners)
def shear(
- tensor: Tensor,
- shear: Tensor,
+ tensor: torch.Tensor,
+ shear: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Shear the tensor.
.. image:: _static/img/shear.png
@@ -503,11 +504,11 @@ def shear(
tensor: The image tensor to be skewed with shape of :math:`(B, C, H, W)`.
shear: tensor containing the angle to shear
in the x and y direction. The tensor must have a shape of
- (B, 2), where B is batch size, last dimension contains shx shy.
+ (B, 2), torch.where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -521,17 +522,17 @@ def shear(
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
- if not isinstance(shear, Tensor):
- raise TypeError(f"Input shear type is not a Tensor. Got {type(shear)}")
+ if not isinstance(shear, torch.Tensor):
+ raise TypeError(f"Input shear type is not a torch.Tensor. Got {type(shear)}")
if len(tensor.shape) not in (3, 4):
raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")
# compute the translation matrix
- shear_matrix: Tensor = _compute_shear_matrix(shear)
+ shear_matrix: torch.Tensor = _compute_shear_matrix(shear)
# warp using the affine transform
return affine(tensor, shear_matrix[..., :2, :3], mode, padding_mode, align_corners)
@@ -551,14 +552,14 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"
@perform_keep_shape_image
def resize(
- input: Tensor,
+ input: torch.Tensor,
size: Union[int, Tuple[int, int]],
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
side: str = "short",
antialias: bool = False,
-) -> Tensor:
- r"""Resize the input Tensor to the given size.
+) -> torch.Tensor:
+ r"""Resize the input torch.Tensor to the given size.
.. image:: _static/img/resize.png
@@ -587,8 +588,8 @@ def resize(
torch.Size([1, 3, 6, 8])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(input)}")
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) < 2:
raise ValueError(f"Input tensor must have at least two dimensions. Got {len(input.shape)}")
@@ -636,17 +637,17 @@ def resize(
def resize_to_be_divisible(
- input: Tensor,
+ input: torch.Tensor,
divisible_factor: int,
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
side: str = "short",
antialias: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
"""Resize the input tensor to be divisible by a certain factor.
Args:
- input (Tensor): Input tensor to be resized.
+ input (torch.Tensor): Input tensor to be resized.
divisible_factor (int): The factor to which the image should be divisible.
interpolation (str, optional): Interpolation flag. Defaults to "bilinear".
align_corners (Optional[bool], optional):
@@ -656,12 +657,12 @@ def resize_to_be_divisible(
If True, then image will be filtered with Gaussian before downscaling. Defaults to False.
Returns:
- Tensor: The resized tensor.
+ torch.Tensor: The resized tensor.
"""
- if isinstance(input, Tensor) and len(input.shape) == 4:
+ if isinstance(input, torch.Tensor) and len(input.shape) == 4:
height, width = input.shape[2], input.shape[3]
- if isinstance(input, Tensor) and len(input.shape) == 3:
+ if isinstance(input, torch.Tensor) and len(input.shape) == 3:
height, width = input.shape[1], input.shape[2]
height = round(height / divisible_factor) * divisible_factor
@@ -670,13 +671,13 @@ def resize_to_be_divisible(
def rescale(
- input: Tensor,
+ input: torch.Tensor,
factor: Union[float, Tuple[float, float]],
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
antialias: bool = False,
-) -> Tensor:
- r"""Rescale the input Tensor with the given factor.
+) -> torch.Tensor:
+ r"""Rescale the input torch.Tensor with the given factor.
.. image:: _static/img/rescale.png
@@ -712,8 +713,8 @@ def rescale(
return resize(input, size, interpolation=interpolation, align_corners=align_corners, antialias=antialias)
-class Resize(Module):
- r"""Resize the input Tensor to the given size.
+class Resize(nn.Module):
+ r"""Resize the input torch.Tensor to the given size.
Args:
size: Desired output size. If size is a sequence like (h, w),
@@ -758,7 +759,7 @@ class Resize(Module):
self.side: str = side
self.antialias: bool = antialias
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return resize(
input,
self.size,
@@ -769,25 +770,26 @@ class Resize(Module):
)
-class Affine(Module):
+class Affine(nn.Module):
r"""Apply multiple elementary affine transforms simultaneously.
Args:
angle: Angle in degrees for counter-clockwise rotation around the center. The tensor
- must have a shape of (B), where B is the batch size.
+ must have a shape of (B), torch.where B is the batch size.
translation: Amount of pixels for translation in x- and y-direction. The tensor must
- have a shape of (B, 2), where B is the batch size and the last dimension contains dx and dy.
- scale_factor: Factor for scaling. The tensor must have a shape of (B,2), where B is the
+ have a shape of (B, 2), torch.where B is the batch size and the last dimension contains dx and dy.
+ scale_factor: Factor for scaling. The tensor must have a shape of (B,2), torch.where B is the
batch size and the last dimension contains scale factors for x and y direction.
shear: Factor for shearing in x- and y-direction around the center. The
- tensor must have a shape of (B, 2), where B is the batch size and the last dimension contains sx and sy.
- center: Transformation center in pixels. The tensor must have a shape of (B, 2), where
+ tensor must have a shape of (B, 2), torch.where B is the batch size and the last dimension
+ contains sx and sy.
+ center: Transformation center in pixels. The tensor must have a shape of (B, 2), torch.where
B is the batch size and the last dimension contains cx and cy. Defaults to the center of image to be
transformed.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Raises:
@@ -807,11 +809,11 @@ class Affine(Module):
def __init__(
self,
- angle: Optional[Tensor] = None,
- translation: Optional[Tensor] = None,
- scale_factor: Optional[Tensor] = None,
- shear: Optional[Tensor] = None,
- center: Optional[Tensor] = None,
+ angle: Optional[torch.Tensor] = None,
+ translation: Optional[torch.Tensor] = None,
+ scale_factor: Optional[torch.Tensor] = None,
+ shear: Optional[torch.Tensor] = None,
+ center: Optional[torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
@@ -834,15 +836,15 @@ class Affine(Module):
device, dtype = _extract_device_dtype([angle, translation, scale_factor])
if angle is None:
- angle = zeros(batch_size, device=device, dtype=dtype)
+ angle = torch.zeros(batch_size, device=device, dtype=dtype)
self.angle = angle
if translation is None:
- translation = zeros(batch_size, 2, device=device, dtype=dtype)
+ translation = torch.zeros(batch_size, 2, device=device, dtype=dtype)
self.translation = translation
if scale_factor is None:
- scale_factor = ones(batch_size, 2, device=device, dtype=dtype)
+ scale_factor = torch.ones(batch_size, 2, device=device, dtype=dtype)
self.scale_factor = scale_factor
self.shear = shear
@@ -851,7 +853,7 @@ class Affine(Module):
self.padding_mode = padding_mode
self.align_corners = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
if self.shear is None:
sx = sy = None
else:
@@ -866,8 +868,8 @@ class Affine(Module):
return affine(input, matrix[..., :2, :3], self.mode, self.padding_mode, self.align_corners)
-class Rescale(Module):
- r"""Rescale the input Tensor with the given factor.
+class Rescale(nn.Module):
+ r"""Rescale the input torch.Tensor with the given factor.
Args:
factor: Desired scaling factor in each direction. If scalar, the value is used
@@ -904,25 +906,25 @@ class Rescale(Module):
self.align_corners: Optional[bool] = align_corners
self.antialias: bool = antialias
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return rescale(
input, self.factor, self.interpolation, align_corners=self.align_corners, antialias=self.antialias
)
-class Rotate(Module):
+class Rotate(nn.Module):
r"""Rotate the tensor anti-clockwise about the centre.
Args:
angle: The angle through which to rotate. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B), torch.where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), where B is batch size and last
+ must have a shape of (B, 2), torch.where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -939,34 +941,34 @@ class Rotate(Module):
def __init__(
self,
- angle: Tensor,
- center: Union[None, Tensor] = None,
+ angle: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
super().__init__()
- self.angle: Tensor = angle
- self.center: Union[None, Tensor] = center
+ self.angle: torch.Tensor = angle
+ self.center: Union[None, torch.Tensor] = center
self.mode: str = mode
self.padding_mode: str = padding_mode
self.align_corners: bool = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return rotate(input, self.angle, self.center, self.mode, self.padding_mode, self.align_corners)
-class Translate(Module):
+class Translate(nn.Module):
r"""Translate the tensor in pixel units.
Args:
translation: tensor containing the amount of pixels to
translate in the x and y direction. The tensor must have a shape of
- (B, 2), where B is batch size, last dimension contains dx dy.
+ (B, 2), torch.where B is batch size, last dimension contains dx dy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -982,33 +984,37 @@ class Translate(Module):
"""
def __init__(
- self, translation: Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True
+ self,
+ translation: torch.Tensor,
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
+ align_corners: bool = True,
) -> None:
super().__init__()
- self.translation: Tensor = translation
+ self.translation: torch.Tensor = translation
self.mode: str = mode
self.padding_mode: str = padding_mode
self.align_corners: bool = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return translate(input, self.translation, self.mode, self.padding_mode, self.align_corners)
-class Scale(Module):
+class Scale(nn.Module):
r"""Scale the tensor by a factor.
Args:
scale_factor: The scale factor apply. The tensor
- must have a shape of (B) or (B, 2), where B is batch size.
+ must have a shape of (B) or (B, 2), torch.where B is batch size.
If (B), isotropic scaling will perform.
If (B, 2), x-y-direction specific scaling will perform.
center: The center through which to scale. The tensor
- must have a shape of (B, 2), where B is batch size and last
+ must have a shape of (B, 2), torch.where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -1025,34 +1031,34 @@ class Scale(Module):
def __init__(
self,
- scale_factor: Tensor,
- center: Union[None, Tensor] = None,
+ scale_factor: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
super().__init__()
- self.scale_factor: Tensor = scale_factor
- self.center: Union[None, Tensor] = center
+ self.scale_factor: torch.Tensor = scale_factor
+ self.center: Union[None, torch.Tensor] = center
self.mode: str = mode
self.padding_mode: str = padding_mode
self.align_corners: bool = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return scale(input, self.scale_factor, self.center, self.mode, self.padding_mode, self.align_corners)
-class Shear(Module):
+class Shear(nn.Module):
r"""Shear the tensor.
Args:
shear: tensor containing the angle to shear
in the x and y direction. The tensor must have a shape of
- (B, 2), where B is batch size, last dimension contains shx shy.
+ (B, 2), torch.where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
Returns:
@@ -1068,13 +1074,13 @@ class Shear(Module):
"""
def __init__(
- self, shear: Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True
+ self, shear: torch.Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True
) -> None:
super().__init__()
- self.shear: Tensor = shear
+ self.shear: torch.Tensor = shear
self.mode: str = mode
self.padding_mode: str = padding_mode
self.align_corners: bool = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return shear(input, self.shear, self.mode, self.padding_mode, self.align_corners)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 2b1f16ae9..49b904ca6 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -18,9 +18,10 @@
from typing import Optional, Tuple, Union
import torch
+import torch.nn.functional as F
+from torch import nn
from kornia.constants import Resample
-from kornia.core import Module, Tensor, as_tensor, pad, tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.bbox import infer_bbox_shape, validate_bbox
@@ -38,19 +39,19 @@ __all__ = [
def crop_and_resize(
- input_tensor: Tensor,
- boxes: Tensor,
+ input_tensor: torch.Tensor,
+ boxes: torch.Tensor,
size: Tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
- r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
+) -> torch.Tensor:
+ r"""Extract crops from 2D images (4D torch.tensor) and resize given a bounding box.
Args:
- input_tensor: the 2D image tensor with shape (B, C, H, W).
- boxes : a tensor containing the coordinates of the bounding boxes to be extracted.
- The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
+ input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
+ boxes : a torch.tensor containing the coordinates of the bounding boxes to be extracted.
+ The torch.tensor must have the shape of Bx4x2, torch.where each box is defined in the following (clockwise)
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
The coordinates would compose a rectangle with a shape of (N1, N2).
size: a tuple with the height and width that will be
@@ -58,11 +59,11 @@ def crop_and_resize(
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | 'reflection'.
+ ``'torch.zeros'`` | ``'border'`` | 'reflection'.
align_corners: mode for grid_generation.
Returns:
- Tensor: tensor containing the patches with shape BxCxN1xN2.
+ torch.Tensor: torch.tensor containing the patches with shape BxCxN1xN2.
Example:
>>> input = torch.tensor([[[
@@ -82,17 +83,17 @@ def crop_and_resize(
[10., 11.]]]])
"""
- if not isinstance(input_tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
+ if not isinstance(input_tensor, torch.Tensor):
+ raise TypeError(f"Input torch.tensor type is not a torch.Tensor. Got {type(input_tensor)}")
- if not isinstance(boxes, Tensor):
- raise TypeError(f"Input boxes type is not a Tensor. Got {type(boxes)}")
+ if not isinstance(boxes, torch.Tensor):
+ raise TypeError(f"Input boxes type is not a torch.Tensor. Got {type(boxes)}")
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input data
dst_h, dst_w = size
@@ -103,7 +104,7 @@ def crop_and_resize(
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst = tensor(
+ points_dst = torch.tensor(
[[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]],
device=input_tensor.device,
dtype=input_tensor.dtype,
@@ -113,26 +114,26 @@ def crop_and_resize(
def center_crop(
- input_tensor: Tensor,
+ input_tensor: torch.Tensor,
size: Tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
- r"""Crop the 2D images (4D tensor) from the center.
+) -> torch.Tensor:
+ r"""Crop the 2D images (4D torch.tensor) from the center.
Args:
- input_tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
size: a tuple with the expected height and width
of the output patch.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
Returns:
- the output tensor with patches.
+ the output torch.tensor with patches.
Examples:
>>> input = torch.tensor([[[
@@ -146,14 +147,14 @@ def center_crop(
[ 9., 10., 11., 12.]]]])
"""
- if not isinstance(input_tensor, Tensor):
- raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
+ if not isinstance(input_tensor, torch.Tensor):
+ raise TypeError(f"Input torch.tensor type is not a torch.Tensor. Got {type(input_tensor)}")
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input sizes
dst_h, dst_w = size
@@ -173,7 +174,7 @@ def center_crop(
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: Tensor = tensor(
+ points_src: torch.Tensor = torch.tensor(
[[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]],
device=input_tensor.device,
dtype=input_tensor.dtype,
@@ -181,7 +182,7 @@ def center_crop(
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: Tensor = tensor(
+ points_dst: torch.Tensor = torch.tensor(
[[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]],
device=input_tensor.device,
dtype=input_tensor.dtype,
@@ -191,38 +192,40 @@ def center_crop(
def crop_by_boxes(
- input_tensor: Tensor,
- src_box: Tensor,
- dst_box: Tensor,
+ input_tensor: torch.Tensor,
+ src_box: torch.Tensor,
+ dst_box: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
validate_boxes: bool = True,
-) -> Tensor:
- """Perform crop transform on 2D images (4D tensor) given two bounding boxes.
+) -> torch.Tensor:
+ """Perform crop transform on 2D images (4D torch.tensor) given two bounding boxes.
- Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
+ Given an input torch.tensor, this function selected the interested areas by the provided bounding boxes (src_box).
Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
- So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes
- in a batch must be rectangles with same width and height.
+ So far, the ragged torch.tensor is not supported by PyTorch right now. This function hereby requires
+ the bounding boxes in a batch must be rectangles with same width and height.
Args:
- input_tensor: the 2D image tensor with shape (B, C, H, W).
- src_box: a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
- order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
- dst_box: a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be placed. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
- order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
+ input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
+ src_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be extracted. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ in the clockwise order: top-left, top-right, bottom-right and bottom-left.
+ The coordinates must be in x, y order.
+ dst_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be placed. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ in the clockwise order: top-left, top-right, bottom-right and bottom-left.
+ The coordinates must be in x, y order.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
validate_boxes: flag to perform validation on boxes.
Returns:
- Tensor: the output tensor with patches.
+ torch.Tensor: the output torch.tensor with patches.
Examples:
>>> input = torch.arange(16, dtype=torch.float32).reshape((1, 1, 4, 4))
@@ -252,13 +255,13 @@ def crop_by_boxes(
validate_bbox(dst_box)
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# compute transformation between points and warp
- # Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
- dst_trans_src: Tensor = get_perspective_transform(src_box.to(input_tensor), dst_box.to(input_tensor))
+ # Note: torch.Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
+ dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(input_tensor), dst_box.to(input_tensor))
- bbox: Tuple[Tensor, Tensor] = infer_bbox_shape(dst_box)
+ bbox: Tuple[torch.Tensor, torch.Tensor] = infer_bbox_shape(dst_box)
if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
raise AssertionError(
f"Cropping height, width and depth must be exact same in a batch. Got height {bbox[0]} and width {bbox[1]}."
@@ -273,35 +276,35 @@ def crop_by_boxes(
def crop_by_transform_mat(
- input_tensor: Tensor,
- transform: Tensor,
+ input_tensor: torch.Tensor,
+ transform: torch.Tensor,
out_size: Tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
- """Perform crop transform on 2D images (4D tensor) given a perspective transformation matrix.
+) -> torch.Tensor:
+ """Perform crop transform on 2D images (4D torch.tensor) given a perspective transformation matrix.
Args:
- input_tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
transform: a perspective transformation matrix with shape (B, 3, 3).
out_size: size of the output image (height, width).
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode (str): padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
Returns:
- the output tensor with patches.
+ the output torch.tensor with patches.
"""
# simulate broadcasting
- dst_trans_src = as_tensor(
+ dst_trans_src = torch.as_tensor(
transform.expand(input_tensor.shape[0], -1, -1), device=input_tensor.device, dtype=input_tensor.dtype
)
- patches: Tensor = warp_affine(
+ patches: torch.Tensor = warp_affine(
input_tensor,
dst_trans_src[:, :2, :],
out_size,
@@ -314,22 +317,23 @@ def crop_by_transform_mat(
def crop_by_indices(
- input_tensor: Tensor,
- src_box: Tensor,
+ input_tensor: torch.Tensor,
+ src_box: torch.Tensor,
size: Optional[Tuple[int, int]] = None,
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
antialias: bool = False,
shape_compensation: str = "resize",
-) -> Tensor:
+) -> torch.Tensor:
"""Crop tensors with naive indices.
Args:
- input_tensor: the 2D image tensor with shape (B, C, H, W).
- src_box: a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
- order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
- size: output size. An auto resize or pad will be performed according to ``shape_compensation``
+ input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
+ src_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be extracted. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ in the clockwise order: top-left, top-right, bottom-right and bottom-left.
+ The coordinates must be in x, y order.
+ size: output size. An auto resize or F.pad will be performed according to ``shape_compensation``
if the cropped slice sizes are not exactly align `size`.
If None, will auto-infer from src_box.
interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |
@@ -345,7 +349,7 @@ def crop_by_indices(
KORNIA_CHECK_SHAPE(src_box, ["B", "4", "2"])
B, C, _, _ = input_tensor.shape
- src = as_tensor(src_box, device=input_tensor.device, dtype=torch.long)
+ src = torch.as_tensor(src_box, device=input_tensor.device, dtype=torch.long)
x1 = src[:, 0, 0]
x2 = src[:, 1, 0] + 1
y1 = src[:, 0, 1]
@@ -382,14 +386,14 @@ def crop_by_indices(
antialias=antialias,
)
else:
- out[i] = pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])
+ out[i] = F.pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])
else:
out[i] = _out
return out
-class CenterCrop2D(Module):
- """Center crop the input tensor.
+class CenterCrop2D(nn.Module):
+ """Center crop the input torch.tensor.
Args:
size: Size (h, w) in pixels of the resized region or just one side.
@@ -429,7 +433,7 @@ class CenterCrop2D(Module):
"padding_mode": "zeros",
}
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
batch_size = input.shape[0]
dst_h, dst_w = self.size
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index c8837392b..17f08b8c3 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -17,9 +17,9 @@
from typing import Tuple, Union
+import torch
import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, tensor
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d
from kornia.filters.kernels import get_gaussian_kernel2d
@@ -29,15 +29,15 @@ __all__ = ["elastic_transform2d"]
def elastic_transform2d(
- image: Tensor,
- noise: Tensor,
+ image: torch.Tensor,
+ noise: torch.Tensor,
kernel_size: Tuple[int, int] = (63, 63),
- sigma: Union[Tuple[float, float], Tensor] = (32.0, 32.0),
- alpha: Union[Tuple[float, float], Tensor] = (1.0, 1.0),
+ sigma: Union[Tuple[float, float], torch.Tensor] = (32.0, 32.0),
+ alpha: Union[Tuple[float, float], torch.Tensor] = (1.0, 1.0),
align_corners: bool = False,
mode: str = "bilinear",
padding_mode: str = "zeros",
-) -> Tensor:
+) -> torch.Tensor:
r"""Apply elastic transform of images as described in :cite:`Simard2003BestPF`.
.. image:: _static/img/elastic_transform2d.png
@@ -54,7 +54,7 @@ def elastic_transform2d(
in the y and x directions, respectively.
align_corners: Interpolation flag used by ```grid_sample```.
mode: Interpolation mode used by ```grid_sample```. Either ``'bilinear'`` or ``'nearest'``.
- padding_mode: The padding used by ```grid_sample```. Either ``'zeros'``, ``'border'`` or ``'refection'``.
+ padding_mode: The padding used by ```grid_sample```. Either ``'torch.zeros'``, ``'border'`` or ``'refection'``.
Returns:
the elastically transformed input image with shape :math:`(B,C,H,W)`.
@@ -85,8 +85,8 @@ def elastic_transform2d(
device, dtype = image.device, image.dtype
# if isinstance(sigma, tuple):
- # sigma_t = tensor(sigma, device=device, dtype=dtype)
- if isinstance(sigma, Tensor):
+ # sigma_t = torch.tensor(sigma, device=device, dtype=dtype)
+ if isinstance(sigma, torch.Tensor):
sigma = sigma.expand(2)[None, ...]
# sigma = sigma.to(device=device, dtype=dtype)
@@ -94,12 +94,12 @@ def elastic_transform2d(
kernel_x = get_gaussian_kernel2d(kernel_size, sigma) # _t[0].expand(2).unsqueeze(0))
kernel_y = get_gaussian_kernel2d(kernel_size, sigma) # _t[1].expand(2).unsqueeze(0))
- if isinstance(alpha, Tensor):
+ if isinstance(alpha, torch.Tensor):
alpha_x = alpha[0]
alpha_y = alpha[1]
else:
- alpha_x = tensor(alpha[0], device=device, dtype=dtype)
- alpha_y = tensor(alpha[1], device=device, dtype=dtype)
+ alpha_x = torch.tensor(alpha[0], device=device, dtype=dtype)
+ alpha_y = torch.tensor(alpha[1], device=device, dtype=dtype)
# Convolve over a random displacement matrix and scale them with 'alpha'
disp_x = noise[:, :1]
@@ -108,8 +108,8 @@ def elastic_transform2d(
disp_x = filter2d(disp_x, kernel=kernel_y, border_type="constant") * alpha_x
disp_y = filter2d(disp_y, kernel=kernel_x, border_type="constant") * alpha_y
- # stack and normalize displacement
- disp = concatenate([disp_x, disp_y], 1).permute(0, 2, 3, 1)
+ # torch.stack and F.normalize displacement
+ disp = torch.cat([disp_x, disp_y], 1).permute(0, 2, 3, 1)
# Warp image based on displacement matrix
_, _, h, w = image.shape
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index e2ebed488..878eaf7e6 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -16,23 +16,21 @@
#
import torch
-
-from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+from torch import nn
__all__ = ["Hflip", "Rot180", "Vflip", "hflip", "rot180", "vflip"]
-class Vflip(Module):
- r"""Vertically flip a tensor image or a batch of tensor images.
+class Vflip(nn.Module):
+ r"""Vertically flip a torch.tensor image or a batch of torch.tensor images.
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Returns:
- The vertically flipped image tensor.
+ The vertically flipped image torch.tensor.
Examples:
>>> vflip = Vflip()
@@ -48,23 +46,23 @@ class Vflip(Module):
"""
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return vflip(input)
def __repr__(self) -> str:
return self.__class__.__name__
-class Hflip(Module):
- r"""Horizontally flip a tensor image or a batch of tensor images.
+class Hflip(nn.Module):
+ r"""Horizontally flip a torch.tensor image or a batch of torch.tensor images.
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Returns:
- The horizontally flipped image tensor.
+ The horizontally flipped image torch.tensor.
Examples:
>>> hflip = Hflip()
@@ -80,20 +78,20 @@ class Hflip(Module):
"""
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return hflip(input)
def __repr__(self) -> str:
return self.__class__.__name__
-class Rot180(Module):
- r"""Rotate a tensor image or a batch of tensor images 180 degrees.
+class Rot180(nn.Module):
+ r"""Rotate a torch.tensor image or a batch of torch.tensor images 180 degrees.
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Examples:
>>> rot180 = Rot180()
@@ -109,59 +107,59 @@ class Rot180(Module):
"""
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return rot180(input)
def __repr__(self) -> str:
return self.__class__.__name__
-def rot180(input: Tensor) -> Tensor:
- r"""Rotate a tensor image or a batch of tensor images 180 degrees.
+def rot180(input: torch.Tensor) -> torch.Tensor:
+ r"""Rotate a torch.tensor image or a batch of torch.tensor images 180 degrees.
.. image:: _static/img/rot180.png
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Returns:
- The rotated image tensor.
+ The rotated image torch.tensor.
"""
return torch.flip(input, [-2, -1])
-def hflip(input: Tensor) -> Tensor:
- r"""Horizontally flip a tensor image or a batch of tensor images.
+def hflip(input: torch.Tensor) -> torch.Tensor:
+ r"""Horizontally flip a torch.tensor image or a batch of torch.tensor images.
.. image:: _static/img/hflip.png
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Returns:
- The horizontally flipped image tensor.
+ The horizontally flipped image torch.tensor.
"""
return input.flip(-1).contiguous()
-def vflip(input: Tensor) -> Tensor:
- r"""Vertically flip a tensor image or a batch of tensor images.
+def vflip(input: torch.Tensor) -> torch.Tensor:
+ r"""Vertically flip a torch.tensor image or a batch of torch.tensor images.
.. image:: _static/img/vflip.png
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input tensor.
+ input: input torch.tensor.
Returns:
- The vertically flipped image tensor.
+ The vertically flipped image torch.tensor.
"""
return input.flip(-2).contiguous()
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 716b42488..f9f8a0f14 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -20,9 +20,10 @@ from __future__ import annotations
from abc import abstractmethod
from typing import Any, Optional
+import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor
from kornia.utils import create_meshgrid
from .imgwarp import homography_warp, warp_grid
@@ -30,17 +31,17 @@ from .imgwarp import homography_warp, warp_grid
__all__ = ["BaseWarper", "HomographyWarper"]
-class BaseWarper(Module):
+class BaseWarper(nn.Module):
def __init__(self, height: int, width: int, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.height = height
self.width = width
@abstractmethod
- def forward(self, patch_src: Tensor, src_homo_dst: Optional[Tensor] = None) -> Tensor: ...
+ def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor: ...
@abstractmethod
- def precompute_warp_grid(self, src_homo_dst: Tensor) -> None: ...
+ def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None: ...
class HomographyWarper(BaseWarper):
@@ -51,17 +52,17 @@ class HomographyWarper(BaseWarper):
X_{dst} = H_{src}^{\{dst\}} * X_{src}
Args:
- height: The height of the destination tensor.
- width: The width of the destination tensor.
+ height: The height of the destination torch.tensor.
+ width: The width of the destination torch.tensor.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
"""
- _warped_grid: Optional[Tensor]
+ _warped_grid: Optional[torch.Tensor]
def __init__(
self,
@@ -83,7 +84,7 @@ class HomographyWarper(BaseWarper):
# initialice the warped destination grid
self._warped_grid = None
- def precompute_warp_grid(self, src_homo_dst: Tensor) -> None:
+ def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
r"""Compute and store internally the transformations of the points.
Useful when the same homography/homographies are reused.
@@ -98,12 +99,12 @@ class HomographyWarper(BaseWarper):
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
- def forward(self, patch_src: Tensor, src_homo_dst: Optional[Tensor] = None) -> Tensor:
- r"""Warp a tensor from source into reference frame.
+ def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
+ r"""Warp a torch.tensor from source into reference frame.
Args:
- patch_src: The tensor to warp.
- src_homo_dst: The homography or stack of
+ patch_src: The torch.tensor to warp.
+ src_homo_dst: The homography or torch.stack of
homographies from destination to source. The homography assumes
normalized coordinates [-1, 1] if normalized_coordinates is True.
@@ -153,8 +154,8 @@ class HomographyWarper(BaseWarper):
)
else:
raise RuntimeError(
- "Unknown warping. If homographies are not provided they must be preset"
- " using the method: precompute_warp_grid()."
+ "Unknown warping. If homographies are not provided they must be preset"
+ " using the method: precompute_warp_grid()."
)
return warped_patch
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 808890bc2..2c86d31fa 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -22,7 +22,6 @@ import torch
import torch.nn.functional as F
from torch import nn, optim
-from kornia.core import Module, Tensor
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_affinematrix_to_homography
from .homography_warper import BaseWarper, HomographyWarper
@@ -31,15 +30,15 @@ from .pyramid import build_pyramid
__all__ = ["BaseModel", "Homography", "ImageRegistrator", "Similarity"]
-class BaseModel(Module):
+class BaseModel(nn.Module):
@abstractmethod
def reset_model(self) -> None: ...
@abstractmethod
- def forward(self) -> Tensor: ...
+ def forward(self) -> torch.Tensor: ...
@abstractmethod
- def forward_inverse(self) -> Tensor: ...
+ def forward_inverse(self) -> torch.Tensor: ...
class Homography(BaseModel):
@@ -57,7 +56,7 @@ class Homography(BaseModel):
"""Initialize the model with identity transform."""
torch.nn.init.eye_(self.model)
- def forward(self) -> Tensor:
+ def forward(self) -> torch.Tensor:
r"""Single-batch homography".
Returns:
@@ -66,7 +65,7 @@ class Homography(BaseModel):
"""
return torch.unsqueeze(self.model / self.model[2, 2], dim=0) # 1x3x3
- def forward_inverse(self) -> Tensor:
+ def forward_inverse(self) -> torch.Tensor:
r"""Interted Single-batch homography".
Returns:
@@ -113,7 +112,7 @@ class Similarity(BaseModel):
torch.nn.init.zeros_(self.shift)
torch.nn.init.ones_(self.scale)
- def forward(self) -> Tensor:
+ def forward(self) -> torch.Tensor:
r"""Single-batch similarity transform".
Returns:
@@ -124,7 +123,7 @@ class Similarity(BaseModel):
out = convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
return out
- def forward_inverse(self) -> Tensor:
+ def forward_inverse(self) -> torch.Tensor:
r"""Single-batch inverse similarity transform".
Returns:
@@ -134,11 +133,11 @@ class Similarity(BaseModel):
return torch.inverse(self.forward())
-class ImageRegistrator(Module):
- r"""Module, which performs optimization-based image registration.
+class ImageRegistrator(nn.Module):
+ r"""nn.Module, which performs optimization-based image registration.
Args:
- model_type: Geometrical model for registration. Can be string or Module.
+ model_type: Geometrical model for registration. Can be string or nn.Module.
optimizer: optimizer class used for the optimization.
loss_fn: torch loss function.
pyramid_levels: number of scale pyramid levels.
@@ -161,7 +160,7 @@ class ImageRegistrator(Module):
self,
model_type: Union[str, BaseModel] = "homography",
optimizer: Type[optim.Optimizer] = optim.Adam,
- loss_fn: Callable[..., Tensor] = F.l1_loss,
+ loss_fn: Callable[..., torch.Tensor] = F.l1_loss,
pyramid_levels: int = 5,
lr: float = 1e-3,
num_iterations: int = 100,
@@ -201,7 +200,9 @@ class ImageRegistrator(Module):
self.num_iterations = num_iterations
self.tolerance = tolerance
- def get_single_level_loss(self, img_src: Tensor, img_dst: Tensor, transform_model: Tensor) -> Tensor:
+ def get_single_level_loss(
+ self, img_src: torch.Tensor, img_dst: torch.Tensor, transform_model: torch.Tensor
+ ) -> torch.Tensor:
"""Warp img_src into img_dst with transform_model and returns loss."""
# ToDo: Make possible registration of images of different shape
if img_src.shape != img_dst.shape:
@@ -214,8 +215,8 @@ class ImageRegistrator(Module):
img_src_to_dst = warper(img_src, transform_model)
# compute and mask loss
loss = self.loss_fn(img_src_to_dst, img_dst, reduction="none") # 1xCxHxW
- ones = warper(torch.ones_like(img_src), transform_model)
- loss = loss.masked_select(ones > 0.9).mean()
+ ones_tensor = warper(torch.ones_like(img_src), transform_model)
+ loss = loss.masked_select(ones_tensor > 0.9).mean()
return loss
def reset_model(self) -> None:
@@ -223,21 +224,25 @@ class ImageRegistrator(Module):
self.model.reset_model()
def register(
- self, src_img: Tensor, dst_img: Tensor, verbose: bool = False, output_intermediate_models: bool = False
- ) -> Union[Tensor, Tuple[Tensor, List[Tensor]]]:
+ self,
+ src_img: torch.Tensor,
+ dst_img: torch.Tensor,
+ verbose: bool = False,
+ output_intermediate_models: bool = False,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
r"""Estimate the transformation which warps src_img into dst_img by gradient descent.
The shape of the tensors is not checked, because it may depend on the model, e.g. volume registration.
Args:
- src_img: Input image tensor.
- dst_img: Input image tensor.
+ src_img: Input image torch.tensor.
+ dst_img: Input image torch.tensor.
verbose: if True, outputs loss every 10 iterations.
output_intermediate_models: if True with intermediate models
Returns:
the transformation between two images, shape depends on the model,
- typically [1x3x3] tensor for string model_types.
+ typically [1x3x3] torch.tensor for string model_types.
"""
self.reset_model()
@@ -274,14 +279,14 @@ class ImageRegistrator(Module):
return self.model(), aux_models
return self.model()
- def warp_src_into_dst(self, src_img: Tensor) -> Tensor:
+ def warp_src_into_dst(self, src_img: torch.Tensor) -> torch.Tensor:
r"""Warp src_img with estimated model."""
_height, _width = src_img.shape[-2:]
warper = self.warper(_height, _width)
img_src_to_dst = warper(src_img, self.model())
return img_src_to_dst
- def warp_dst_inro_src(self, dst_img: Tensor) -> Tensor:
+ def warp_dst_inro_src(self, dst_img: torch.Tensor) -> torch.Tensor:
r"""Warp src_img with inverted estimated model."""
_height, _width = dst_img.shape[-2:]
warper = self.warper(_height, _width)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 9da426de5..d76c2812d 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -22,14 +22,12 @@ from typing import Optional
import torch
import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, ones, ones_like, stack, tan, tensor, zeros
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import (
angle_to_rotation_matrix,
axis_angle_to_rotation_matrix,
convert_affinematrix_to_homography,
convert_affinematrix_to_homography3d,
- deg2rad,
normalize_homography,
normalize_homography3d,
normalize_pixel_coordinates,
@@ -63,14 +61,14 @@ __all__ = [
def warp_perspective(
- src: Tensor,
- M: Tensor,
+ src: torch.Tensor,
+ M: torch.Tensor,
dsize: tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
- fill_value: Optional[Tensor] = None, # needed for jit
-) -> Tensor:
+ fill_value: Optional[torch.Tensor] = None, # needed for jit
+) -> torch.Tensor:
r"""Apply a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -87,9 +85,10 @@ def warp_perspective(
M: transformation matrix with shape :math:`(B, 3, 3)`.
dsize: size of the output image (height, width).
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
- padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'`` | ``'fill'``.
+ padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``
+ | ``'fill'``.
align_corners: interpolation flag.
- fill_value: tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.
+ fill_value: torch.tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.
Returns:
the warped input image :math:`(B, C, H, W)`.
@@ -108,30 +107,30 @@ def warp_perspective(
See a working example `here <https://kornia.github.io/tutorials/nbs/warp_perspective.html>`_.
"""
- if not isinstance(src, Tensor):
- raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
+ if not isinstance(src, torch.Tensor):
+ raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
- if not isinstance(M, Tensor):
- raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
+ if not isinstance(M, torch.Tensor):
+ raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 4:
- raise ValueError(f"Input src must be a BxCxHxW tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxHxW torch.tensor. Got {src.shape}")
if not (len(M.shape) == 3 and M.shape[-2:] == (3, 3)):
- raise ValueError(f"Input M must be a Bx3x3 tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx3x3 torch.tensor. Got {M.shape}")
# fill padding is only supported for 3 channels because we can't set fill_value default
# to None as this gives jit issues.
if fill_value is None:
- fill_value = zeros(3)
+ fill_value = torch.zeros(3)
if padding_mode == "fill" and fill_value.shape != torch.Size([3]):
raise ValueError(f"Padding_tensor only supported for 3 channels. Got {fill_value.shape}")
B, _, H, W = src.size()
h_out, w_out = dsize
- # we normalize the 3x3 transformation matrix and convert to 3x4
- dst_norm_trans_src_norm: Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
+ # we F.normalize the 3x3 transformation matrix and convert to 3x4
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm) # Bx3x3
@@ -149,19 +148,19 @@ def warp_perspective(
def warp_affine(
- src: Tensor,
- M: Tensor,
+ src: torch.Tensor,
+ M: torch.Tensor,
dsize: tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
- fill_value: Optional[Tensor] = None,
-) -> Tensor:
- r"""Apply an affine transformation to a tensor.
+ fill_value: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
+ r"""Apply an affine transformation to a torch.tensor.
.. image:: _static/img/warp_affine.png
- The function warp_affine transforms the source tensor using
+ The function warp_affine transforms the source torch.tensor using
the specified matrix:
.. math::
@@ -169,16 +168,17 @@ def warp_affine(
M_{21} x + M_{22} y + M_{23} \right )
Args:
- src: input tensor of shape :math:`(B, C, H, W)`.
+ src: input torch.tensor of shape :math:`(B, C, H, W)`.
M: affine transformation of shape :math:`(B, 2, 3)`.
dsize: size of the output image (height, width).
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
- padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'`` | ``'fill'``.
+ padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``
+ | ``'fill'``.
align_corners : mode for grid_generation.
- fill_value: tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
+ fill_value: torch.tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
Returns:
- the warped tensor with shape :math:`(B, C, H, W)`.
+ the warped torch.tensor with shape :math:`(B, C, H, W)`.
.. note::
This function is often used in conjunction with :func:`get_rotation_matrix2d`,
@@ -195,22 +195,22 @@ def warp_affine(
torch.Size([1, 4, 4, 2])
"""
- if not isinstance(src, Tensor):
- raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
+ if not isinstance(src, torch.Tensor):
+ raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
- if not isinstance(M, Tensor):
- raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
+ if not isinstance(M, torch.Tensor):
+ raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 4:
- raise ValueError(f"Input src must be a BxCxHxW tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxHxW torch.tensor. Got {src.shape}")
if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):
- raise ValueError(f"Input M must be a Bx2x3 tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx2x3 torch.tensor. Got {M.shape}")
B, C, H, W = src.size()
- M_3x3: Tensor = convert_affinematrix_to_homography(M)
- dst_norm_trans_src_norm: Tensor = normalize_homography(M_3x3, (H, W), dsize)
+ M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize)
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
@@ -224,18 +224,20 @@ def warp_affine(
return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
-def _fill_and_warp(src: Tensor, grid: Tensor, mode: str, align_corners: bool, fill_value: Tensor) -> Tensor:
- r"""Warp a mask of ones, then multiply with fill_value and add to default warp.
+def _fill_and_warp(
+ src: torch.Tensor, grid: torch.Tensor, mode: str, align_corners: bool, fill_value: torch.Tensor
+) -> torch.Tensor:
+ r"""Warp a mask of torch.ones, then multiply with fill_value and add to default warp.
Args:
- src: input tensor of shape :math:`(B, C, H, W)`.
- grid: grid tensor from `transform_points`.
+ src: input torch.tensor of shape :math:`(B, C, H, W)`.
+ grid: grid torch.tensor from `transform_points`.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
align_corners: interpolation flag.
- fill_value: tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
+ fill_value: torch.tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
Returns:
- the warped and filled tensor with shape :math:`(B, C, H, W)`.
+ the warped and filled torch.tensor with shape :math:`(B, C, H, W)`.
"""
ones_mask = torch.ones_like(src)
fill_value = fill_value.to(ones_mask)
@@ -252,7 +254,7 @@ def _fill_and_warp(src: Tensor, grid: Tensor, mode: str, align_corners: bool, fi
return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode="zeros") + inv_color_mask
-def warp_grid(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
+def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
r"""Compute the grid to warp the coordinates grid by the homography/ies.
Args:
@@ -273,11 +275,11 @@ def warp_grid(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
src_homo_dst = src_homo_dst.view(batch_size, 1, 3, 3) # Nx1x3x3
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
return flow.view(batch_size, height, width, 2) # NxHxWx2
-def warp_grid3d(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
+def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
r"""Compute the grid to warp the coordinates grid by the homography/ies.
Args:
@@ -298,7 +300,7 @@ def warp_grid3d(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # Nx1x3x3
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
@@ -309,7 +311,7 @@ def warp_grid3d(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
# super().__init__()
-def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
+def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> torch.Tensor:
r"""Calculate a perspective transform from four pairs of the corresponding points.
The algorithm is a vanilla implementation of the Direct Linear transform (DLT).
@@ -364,27 +366,27 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
# system is solved with the least square method, so here
# we could even pass more correspondence
- # create the lhs tensor with shape # Bx8x8
+ # create the lhs torch.tensor with shape # Bx8x8
B: int = points_src.shape[0] # batch_size
A = torch.empty(B, 8, 8, device=points_src.device, dtype=points_src.dtype)
# we need to perform in batch
- _zeros = zeros(B, device=points_src.device, dtype=points_src.dtype)
- _ones = ones(B, device=points_src.device, dtype=points_src.dtype)
+ _zeros = torch.zeros(B, device=points_src.device, dtype=points_src.dtype)
+ _ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)
for i in range(4):
x1, y1 = points_src[..., i, 0], points_src[..., i, 1] # Bx4
x2, y2 = points_dst[..., i, 0], points_dst[..., i, 1] # Bx4
- A[:, 2 * i] = stack([x1, y1, _ones, _zeros, _zeros, _zeros, -x1 * x2, -y1 * x2], -1)
- A[:, 2 * i + 1] = stack([_zeros, _zeros, _zeros, x1, y1, _ones, -x1 * y2, -y1 * y2], -1)
+ A[:, 2 * i] = torch.stack([x1, y1, _ones, _zeros, _zeros, _zeros, -x1 * x2, -y1 * x2], -1)
+ A[:, 2 * i + 1] = torch.stack([_zeros, _zeros, _zeros, x1, y1, _ones, -x1 * y2, -y1 * y2], -1)
- # the rhs tensor
+ # the rhs torch.tensor
b = points_dst.view(-1, 8, 1)
# solve the system Ax = b
- X: Tensor = _torch_solve_cast(A, b)
+ X: torch.Tensor = _torch_solve_cast(A, b)
# create variable to return the Bx3x3 transform
M = torch.empty(B, 9, device=points_src.device, dtype=points_src.dtype)
@@ -395,7 +397,7 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
# TODO: move to kornia.geometry.affine
-def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tensor:
+def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
r"""Calculate an affine matrix of 2D rotation.
The function calculates the following matrix:
@@ -408,11 +410,11 @@ def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tenso
+ (1 - \alpha) \cdot \text{y}
\end{bmatrix}
- where
+ torch.where
.. math::
- \alpha = \text{scale} \cdot cos(\text{angle}) \\
- \beta = \text{scale} \cdot sin(\text{angle})
+ \alpha = \text{scale} \cdot torch.cos(\text{angle}) \\
+ \beta = \text{scale} \cdot torch.sin(\text{angle})
The transformation maps the rotation center to itself
If this is not the target, adjust the shift.
@@ -428,7 +430,7 @@ def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tenso
the affine matrix of 2D rotation with shape :math:`(B, 2, 3)`.
Example:
- >>> center = zeros(1, 2)
+ >>> center = torch.zeros(1, 2)
>>> scale = torch.ones((1, 2))
>>> angle = 45. * torch.ones(1)
>>> get_rotation_matrix2d(center, angle, scale)
@@ -439,23 +441,23 @@ def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tenso
This function is often used in conjunction with :func:`warp_affine`.
"""
- if not isinstance(center, Tensor):
- raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")
+ if not isinstance(center, torch.Tensor):
+ raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")
- if not isinstance(angle, Tensor):
- raise TypeError(f"Input angle type is not a Tensor. Got {type(angle)}")
+ if not isinstance(angle, torch.Tensor):
+ raise TypeError(f"Input angle type is not a torch.Tensor. Got {type(angle)}")
- if not isinstance(scale, Tensor):
- raise TypeError(f"Input scale type is not a Tensor. Got {type(scale)}")
+ if not isinstance(scale, torch.Tensor):
+ raise TypeError(f"Input scale type is not a torch.Tensor. Got {type(scale)}")
if not (len(center.shape) == 2 and center.shape[1] == 2):
- raise ValueError(f"Input center must be a Bx2 tensor. Got {center.shape}")
+ raise ValueError(f"Input center must be a Bx2 torch.tensor. Got {center.shape}")
if not len(angle.shape) == 1:
- raise ValueError(f"Input angle must be a B tensor. Got {angle.shape}")
+ raise ValueError(f"Input angle must be a B torch.tensor. Got {angle.shape}")
if not (len(scale.shape) == 2 and scale.shape[1] == 2):
- raise ValueError(f"Input scale must be a Bx2 tensor. Got {scale.shape}")
+ raise ValueError(f"Input scale must be a Bx2 torch.tensor. Got {scale.shape}")
if not (center.shape[0] == angle.shape[0] == scale.shape[0]):
raise ValueError(
@@ -487,40 +489,40 @@ def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tenso
def remap(
- image: Tensor,
- map_x: Tensor,
- map_y: Tensor,
+ image: torch.Tensor,
+ map_x: torch.Tensor,
+ map_y: torch.Tensor,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: Optional[bool] = None,
normalized_coordinates: bool = False,
-) -> Tensor:
- r"""Apply a generic geometrical transformation to an image tensor.
+) -> torch.Tensor:
+ r"""Apply a generic geometrical transformation to an image torch.tensor.
.. image:: _static/img/remap.png
- The function remap transforms the source tensor using the specified map:
+ The function remap transforms the source torch.tensor using the specified map:
.. math::
\text{dst}(x, y) = \text{src}(map_x(x, y), map_y(x, y))
Args:
- image: the tensor to remap with shape (B, C, H, W).
+ image: the torch.tensor to remap with shape (B, C, H, W).
Where C is the number of channels.
map_x: the flow in the x-direction in pixel coordinates.
- The tensor must be in the shape of (B, H, W).
+ The torch.tensor must be in the shape of (B, H, W).
map_y: the flow in the y-direction in pixel coordinates.
- The tensor must be in the shape of (B, H, W).
+ The torch.tensor must be in the shape of (B, H, W).
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
normalized_coordinates: whether the input coordinates are
normalized in the range of [-1, 1].
Returns:
- the warped tensor with same shape as the input grid maps.
+ the warped torch.tensor with same shape as the input grid maps.
Example:
>>> import torch
@@ -543,20 +545,24 @@ def remap(
batch_size, _, height, width = image.shape
# grid_sample need the grid between -1/1
- map_xy: Tensor = stack([map_x, map_y], -1)
+ map_xy: torch.Tensor = torch.stack([map_x, map_y], -1)
- # normalize coordinates if not already normalized
+ # F.normalize coordinates if not already normalized
if not normalized_coordinates:
map_xy = normalize_pixel_coordinates(map_xy, height, width)
# simulate broadcasting since grid_sample does not support it
map_xy = map_xy.expand(batch_size, -1, -1, -1)
+ # Default to False if align_corners is None to avoid PyTorch warning
+ if align_corners is None:
+ align_corners = False
+
# warp the image tensor and return
return F.grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
-def invert_affine_transform(matrix: Tensor) -> Tensor:
+def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
r"""Invert an affine transformation.
The function computes an inverse affine transformation represented by
@@ -571,7 +577,7 @@ def invert_affine_transform(matrix: Tensor) -> Tensor:
The result is also a 2x3 matrix of the same type as M.
Args:
- matrix: original affine transform. The tensor must be
+ matrix: original affine transform. The torch.tensor must be
in the shape of :math:`(B, 2, 3)`.
Return:
@@ -581,35 +587,35 @@ def invert_affine_transform(matrix: Tensor) -> Tensor:
This function is often used in conjunction with :func:`warp_affine`.
"""
- if not isinstance(matrix, Tensor):
- raise TypeError(f"Input matrix type is not a Tensor. Got {type(matrix)}")
+ if not isinstance(matrix, torch.Tensor):
+ raise TypeError(f"Input matrix type is not a torch.Tensor. Got {type(matrix)}")
if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):
- raise ValueError(f"Input matrix must be a Bx2x3 tensor. Got {matrix.shape}")
+ raise ValueError(f"Input matrix must be a Bx2x3 torch.tensor. Got {matrix.shape}")
- matrix_tmp: Tensor = convert_affinematrix_to_homography(matrix)
- matrix_inv: Tensor = _torch_inverse_cast(matrix_tmp)
+ matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)
+ matrix_inv: torch.Tensor = _torch_inverse_cast(matrix_tmp)
return matrix_inv[..., :2, :3]
def get_affine_matrix2d(
- translations: Tensor,
- center: Tensor,
- scale: Tensor,
- angle: Tensor,
- sx: Optional[Tensor] = None,
- sy: Optional[Tensor] = None,
-) -> Tensor:
+ translations: torch.Tensor,
+ center: torch.Tensor,
+ scale: torch.Tensor,
+ angle: torch.Tensor,
+ sx: Optional[torch.Tensor] = None,
+ sy: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
r"""Compose affine matrix from the components.
Args:
- translations: tensor containing the translation vector with shape :math:`(B, 2)`.
- center: tensor containing the center vector with shape :math:`(B, 2)`.
- scale: tensor containing the scale factor with shape :math:`(B, 2)`.
- angle: tensor of angles in degrees :math:`(B)`.
- sx: tensor containing the shear factor in the x-direction with shape :math:`(B)`.
- sy: tensor containing the shear factor in the y-direction with shape :math:`(B)`.
+ translations: torch.tensor containing the translation vector with shape :math:`(B, 2)`.
+ center: torch.tensor containing the center vector with shape :math:`(B, 2)`.
+ scale: torch.tensor containing the scale factor with shape :math:`(B, 2)`.
+ angle: torch.tensor of angles in degrees :math:`(B)`.
+ sx: torch.tensor containing the shear factor in the x-direction with shape :math:`(B)`.
+ sy: torch.tensor containing the shear factor in the y-direction with shape :math:`(B)`.
Returns:
the affine transformation matrix :math:`(B, 3, 3)`.
@@ -618,10 +624,10 @@ def get_affine_matrix2d(
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
"""
- transform: Tensor = get_rotation_matrix2d(center, -angle, scale)
+ transform: torch.Tensor = get_rotation_matrix2d(center, -angle, scale)
transform[..., 2] += translations # tx/ty
- # pad transform to get Bx3x3
+ # F.pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography(transform)
if any(s is not None for s in [sx, sy]):
@@ -631,11 +637,11 @@ def get_affine_matrix2d(
return transform_h
-def get_translation_matrix2d(translations: Tensor) -> Tensor:
+def get_translation_matrix2d(translations: torch.Tensor) -> torch.Tensor:
r"""Compose translation matrix from the components.
Args:
- translations: tensor containing the translation vector with shape :math:`(B, 2)`.
+ translations: torch.tensor containing the translation vector with shape :math:`(B, 2)`.
Returns:
the affine transformation matrix :math:`(B, 3, 3)`.
@@ -644,16 +650,18 @@ def get_translation_matrix2d(translations: Tensor) -> Tensor:
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
"""
- transform: Tensor = eye_like(3, translations)[:, :2, :]
+ transform: torch.Tensor = eye_like(3, translations)[:, :2, :]
transform[..., 2] += translations # tx/ty
- # pad transform to get Bx3x3
+ # F.pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography(transform)
return transform_h
-def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional[Tensor] = None) -> Tensor:
+def get_shear_matrix2d(
+ center: torch.Tensor, sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis.
@@ -687,17 +695,17 @@ def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
"""
- sx = tensor([0.0]).repeat(center.size(0)) if sx is None else sx
- sy = tensor([0.0]).repeat(center.size(0)) if sy is None else sy
+ sx = torch.tensor([0.0]).repeat(center.size(0)) if sx is None else sx
+ sy = torch.tensor([0.0]).repeat(center.size(0)) if sy is None else sy
x, y = torch.split(center, 1, dim=-1)
x, y = x.view(-1), y.view(-1)
- sx_tan = tan(sx)
- sy_tan = tan(sy)
- ones = ones_like(sx)
- shear_mat = stack(
- [ones, -sx_tan, sx_tan * y, -sy_tan, ones + sx_tan * sy_tan, sy_tan * (x - sx_tan * y)], dim=-1
+ sx_tan = torch.tan(sx)
+ sy_tan = torch.tan(sy)
+ ones_tensor = torch.ones_like(sx)
+ shear_mat = torch.stack(
+ [ones_tensor, -sx_tan, sx_tan * y, -sy_tan, ones_tensor + sx_tan * sy_tan, sy_tan * (x - sx_tan * y)], dim=-1
).view(-1, 2, 3)
shear_mat = convert_affinematrix_to_homography(shear_mat)
@@ -705,32 +713,32 @@ def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional
def get_affine_matrix3d(
- translations: Tensor,
- center: Tensor,
- scale: Tensor,
- angles: Tensor,
- sxy: Optional[Tensor] = None,
- sxz: Optional[Tensor] = None,
- syx: Optional[Tensor] = None,
- syz: Optional[Tensor] = None,
- szx: Optional[Tensor] = None,
- szy: Optional[Tensor] = None,
-) -> Tensor:
+ translations: torch.Tensor,
+ center: torch.Tensor,
+ scale: torch.Tensor,
+ angles: torch.Tensor,
+ sxy: Optional[torch.Tensor] = None,
+ sxz: Optional[torch.Tensor] = None,
+ syx: Optional[torch.Tensor] = None,
+ syz: Optional[torch.Tensor] = None,
+ szx: Optional[torch.Tensor] = None,
+ szy: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
r"""Compose 3d affine matrix from the components.
Args:
- translations: tensor containing the translation vector (dx,dy,dz) with shape :math:`(B, 3)`.
- center: tensor containing the center vector (x,y,z) with shape :math:`(B, 3)`.
- scale: tensor containing the scale factor with shape :math:`(B)`.
+ translations: torch.tensor containing the translation vector (dx,dy,dz) with shape :math:`(B, 3)`.
+ center: torch.tensor containing the center vector (x,y,z) with shape :math:`(B, 3)`.
+ scale: torch.tensor containing the scale factor with shape :math:`(B)`.
angles: axis angle vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape :math:`(B, 3)`. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
- sxy: tensor containing the shear factor in the xy-direction with shape :math:`(B)`.
- sxz: tensor containing the shear factor in the xz-direction with shape :math:`(B)`.
- syx: tensor containing the shear factor in the yx-direction with shape :math:`(B)`.
- syz: tensor containing the shear factor in the yz-direction with shape :math:`(B)`.
- szx: tensor containing the shear factor in the zx-direction with shape :math:`(B)`.
- szy: tensor containing the shear factor in the zy-direction with shape :math:`(B)`.
+ sxy: torch.tensor containing the shear factor in the xy-direction with shape :math:`(B)`.
+ sxz: torch.tensor containing the shear factor in the xz-direction with shape :math:`(B)`.
+ syx: torch.tensor containing the shear factor in the yx-direction with shape :math:`(B)`.
+ syz: torch.tensor containing the shear factor in the yz-direction with shape :math:`(B)`.
+ szx: torch.tensor containing the shear factor in the zx-direction with shape :math:`(B)`.
+ szy: torch.tensor containing the shear factor in the zy-direction with shape :math:`(B)`.
Returns:
the 3d affine transformation matrix :math:`(B, 3, 3)`.
@@ -739,10 +747,10 @@ def get_affine_matrix3d(
This function is often used in conjunction with :func:`warp_perspective`.
"""
- transform: Tensor = get_projective_transform(center, -angles, scale)
+ transform: torch.Tensor = get_projective_transform(center, -angles, scale)
transform[..., 3] += translations # tx/ty/tz
- # pad transform to get Bx3x3
+ # F.pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography3d(transform)
if any(s is not None for s in [sxy, sxz, syx, syz, szx, szy]):
shear_mat = get_shear_matrix3d(center, sxy, sxz, syx, syz, szx, szy)
@@ -752,14 +760,14 @@ def get_affine_matrix3d(
def get_shear_matrix3d(
- center: Tensor,
- sxy: Optional[Tensor] = None,
- sxz: Optional[Tensor] = None,
- syx: Optional[Tensor] = None,
- syz: Optional[Tensor] = None,
- szx: Optional[Tensor] = None,
- szy: Optional[Tensor] = None,
-) -> Tensor:
+ center: torch.Tensor,
+ sxy: Optional[torch.Tensor] = None,
+ sxz: Optional[torch.Tensor] = None,
+ syx: Optional[torch.Tensor] = None,
+ syz: Optional[torch.Tensor] = None,
+ szx: Optional[torch.Tensor] = None,
+ szy: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
@@ -809,22 +817,22 @@ def get_shear_matrix3d(
This function is often used in conjunction with :func:`warp_perspective3d`.
"""
- sxy = tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
- sxz = tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
- syx = tensor([0.0]).repeat(center.size(0)) if syx is None else syx
- syz = tensor([0.0]).repeat(center.size(0)) if syz is None else syz
- szx = tensor([0.0]).repeat(center.size(0)) if szx is None else szx
- szy = tensor([0.0]).repeat(center.size(0)) if szy is None else szy
+ sxy = torch.tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
+ sxz = torch.tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
+ syx = torch.tensor([0.0]).repeat(center.size(0)) if syx is None else syx
+ syz = torch.tensor([0.0]).repeat(center.size(0)) if syz is None else syz
+ szx = torch.tensor([0.0]).repeat(center.size(0)) if szx is None else szx
+ szy = torch.tensor([0.0]).repeat(center.size(0)) if szy is None else szy
x, y, z = torch.split(center, 1, dim=-1)
x, y, z = x.view(-1), y.view(-1), z.view(-1)
# Prepare parameters
- sxy_tan = tan(sxy)
- sxz_tan = tan(sxz)
- syx_tan = tan(syx)
- syz_tan = tan(syz)
- szx_tan = tan(szx)
- szy_tan = tan(szy)
+ sxy_tan = torch.tan(sxy)
+ sxz_tan = torch.tan(sxz)
+ syx_tan = torch.tan(syx)
+ syz_tan = torch.tan(syz)
+ szx_tan = torch.tan(szx)
+ szy_tan = torch.tan(szy)
# compute translation matrix
m00, m10, m20, m01, m11, m21, m02, m12, m22 = _compute_shear_matrix_3d(
@@ -841,50 +849,55 @@ def get_shear_matrix3d(
sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan
)
- shear_mat = stack([m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23], -1).view(-1, 3, 4)
+ shear_mat = torch.stack([m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23], -1).view(-1, 3, 4)
shear_mat = convert_affinematrix_to_homography3d(shear_mat)
return shear_mat
def _compute_shear_matrix_3d(
- sxy_tan: Tensor, sxz_tan: Tensor, syx_tan: Tensor, syz_tan: Tensor, szx_tan: Tensor, szy_tan: Tensor
-) -> tuple[Tensor, ...]:
- ones = ones_like(sxy_tan)
-
- m00, m10, m20 = ones, sxy_tan, sxz_tan
- m01, m11, m21 = syx_tan, sxy_tan * syx_tan + ones, sxz_tan * syx_tan + syz_tan
+ sxy_tan: torch.Tensor,
+ sxz_tan: torch.Tensor,
+ syx_tan: torch.Tensor,
+ syz_tan: torch.Tensor,
+ szx_tan: torch.Tensor,
+ szy_tan: torch.Tensor,
+) -> tuple[torch.Tensor, ...]:
+ ones_tensor = torch.ones_like(sxy_tan)
+
+ m00, m10, m20 = ones_tensor, sxy_tan, sxz_tan
+ m01, m11, m21 = syx_tan, sxy_tan * syx_tan + ones_tensor, sxz_tan * syx_tan + syz_tan
m02 = syx_tan * szy_tan + szx_tan
m12 = sxy_tan * szx_tan + szy_tan * m11
- m22 = sxz_tan * szx_tan + szy_tan * m21 + ones
+ m22 = sxz_tan * szx_tan + szy_tan * m21 + ones_tensor
return m00, m10, m20, m01, m11, m21, m02, m12, m22
def warp_affine3d(
- src: Tensor,
- M: Tensor,
+ src: torch.Tensor,
+ M: torch.Tensor,
dsize: tuple[int, int, int],
flags: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
-) -> Tensor:
- r"""Apply a projective transformation a to 3d tensor.
+) -> torch.Tensor:
+ r"""Apply a projective transformation a to 3d torch.tensor.
.. warning::
This API signature it is experimental and might suffer some changes in the future.
Args:
- src : input tensor of shape :math:`(B, C, D, H, W)`.
+ src : input torch.tensor of shape :math:`(B, C, D, H, W)`.
M: projective transformation matrix of shape :math:`(B, 3, 4)`.
dsize: size of the output image (depth, height, width).
flags: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
- ``'zeros'`` | ``'border'`` | ``'reflection'``.
+ ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
align_corners : mode for grid_generation.
Returns:
- Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.
+ torch.Tensor: the warped 3d torch.tensor with shape :math:`(B, C, D, H, W)`.
.. note::
This function is often used in conjunction with :func:`get_perspective_transform3d`.
@@ -903,11 +916,11 @@ def warp_affine3d(
M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
- # we need to normalize the transformation since grid sample needs -1/1 coordinates
- dst_norm_trans_src_norm: Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
+ # we need to F.normalize the transformation since grid sample needs -1/1 coordinates
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
- P_norm: Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
+ P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
# compute meshgrid and apply to input
dsize_out: list[int] = [B, C, *list(size_out)]
@@ -915,7 +928,7 @@ def warp_affine3d(
return F.grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
-def projection_from_Rt(rmat: Tensor, tvec: Tensor) -> Tensor:
+def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
r"""Compute the projection matrix from Rotation and translation.
.. warning::
@@ -936,10 +949,10 @@ def projection_from_Rt(rmat: Tensor, tvec: Tensor) -> Tensor:
if not (len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1)):
raise AssertionError(tvec.shape)
- return concatenate([rmat, tvec], -1) # Bx3x4
+ return torch.cat([rmat, tvec], -1) # Bx3x4
-def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) -> Tensor:
+def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
r"""Calculate the projection matrix for a 3D rotation.
.. warning::
@@ -971,9 +984,9 @@ def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) ->
raise AssertionError(center.dtype, angles.dtype)
# create rotation matrix
- axis_angle_rad: Tensor = deg2rad(angles)
- rmat: Tensor = axis_angle_to_rotation_matrix(axis_angle_rad) # Bx3x3
- scaling_matrix: Tensor = eye_like(3, rmat)
+ axis_angle_rad: torch.Tensor = torch.torch.deg2rad(angles)
+ rmat: torch.Tensor = axis_angle_to_rotation_matrix(axis_angle_rad) # Bx3x3
+ scaling_matrix: torch.Tensor = eye_like(3, rmat)
scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)
rmat = rmat @ scaling_matrix.to(rmat)
@@ -984,7 +997,7 @@ def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) ->
to_origin_mat = from_origin_mat.clone()
to_origin_mat = _torch_inverse_cast(from_origin_mat)
- # append translation with zeros
+ # append translation with torch.zeros
proj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4
# chain 4x4 transforms
@@ -994,7 +1007,7 @@ def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) ->
return proj_mat[..., :3, :] # Bx3x4
-def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
+def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
r"""Calculate a 3d perspective transform from four pairs of the corresponding points.
The function calculates the matrix of a perspective transform so that:
@@ -1016,7 +1029,7 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
1 \\
\end{bmatrix}
- where
+ torch.where
.. math::
dst(i) = (x_{i}^{'},y_{i}^{'},z_{i}^{'}), src(i) = (x_{i}, y_{i}, z_{i}), i = 0,1,2,5,7
@@ -1064,14 +1077,14 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
This function is often used in conjunction with :func:`warp_perspective3d`.
"""
- if not isinstance(src, (Tensor)):
- raise TypeError(f"Input type is not a Tensor. Got {type(src)}")
+ if not isinstance(src, (torch.Tensor)):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(src)}")
- if not isinstance(dst, (Tensor)):
- raise TypeError(f"Input type is not a Tensor. Got {type(dst)}")
+ if not isinstance(dst, (torch.Tensor)):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst)}")
if not src.shape[-2:] == (8, 3):
- raise ValueError(f"Inputs must be a Bx8x3 tensor. Got {src.shape}")
+ raise ValueError(f"Inputs must be a Bx8x3 torch.tensor. Got {src.shape}")
if not src.shape == dst.shape:
raise ValueError(f"Inputs must have the same shape. Got {dst.shape}")
@@ -1097,10 +1110,10 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
p.append(_build_perspective_param3d(src[:, i], dst[:, i], "z"))
# A is Bx15x15
- A = stack(p, 1)
+ A = torch.stack(p, 1)
# b is a Bx15x1
- b = stack(
+ b = torch.stack(
[
dst[:, 0:1, 0],
dst[:, 0:1, 1],
@@ -1125,7 +1138,7 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
)
# solve the system Ax = b
- X: Tensor = _torch_solve_cast(A, b)
+ X: torch.Tensor = _torch_solve_cast(A, b)
# create variable to return
batch_size: int = src.shape[0]
@@ -1136,25 +1149,25 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
return M.view(-1, 4, 4) # Bx4x4
-def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
- ones = torch.ones_like(p)[..., 0:1]
- zeros = torch.zeros_like(p)[..., 0:1]
+def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> torch.Tensor:
+ ones_tensor = torch.ones_like(p)[..., 0:1]
+ zeros_tensor = torch.zeros_like(p)[..., 0:1]
if axis == "x":
- return concatenate(
+ return torch.cat(
[
p[:, 0:1],
p[:, 1:2],
p[:, 2:3],
- ones,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
+ ones_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
-p[:, 0:1] * q[:, 0:1],
-p[:, 1:2] * q[:, 0:1],
-p[:, 2:3] * q[:, 0:1],
@@ -1163,20 +1176,20 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
)
if axis == "y":
- return concatenate(
+ return torch.cat(
[
- zeros,
- zeros,
- zeros,
- zeros,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
p[:, 0:1],
p[:, 1:2],
p[:, 2:3],
- ones,
- zeros,
- zeros,
- zeros,
- zeros,
+ ones_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
-p[:, 0:1] * q[:, 1:2],
-p[:, 1:2] * q[:, 1:2],
-p[:, 2:3] * q[:, 1:2],
@@ -1185,20 +1198,20 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
)
if axis == "z":
- return concatenate(
+ return torch.cat(
[
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
- zeros,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
+ zeros_tensor,
p[:, 0:1],
p[:, 1:2],
p[:, 2:3],
- ones,
+ ones_tensor,
-p[:, 0:1] * q[:, 2:3],
-p[:, 1:2] * q[:, 2:3],
-p[:, 2:3] * q[:, 2:3],
@@ -1210,13 +1223,13 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
def warp_perspective3d(
- src: Tensor,
- M: Tensor,
+ src: torch.Tensor,
+ M: torch.Tensor,
dsize: tuple[int, int, int],
flags: str = "bilinear",
border_mode: str = "zeros",
align_corners: bool = False,
-) -> Tensor:
+) -> torch.Tensor:
r"""Apply a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -1245,17 +1258,17 @@ def warp_perspective3d(
This function is often used in conjunction with :func:`get_perspective_transform3d`.
"""
- if not isinstance(src, Tensor):
- raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
+ if not isinstance(src, torch.Tensor):
+ raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
- if not isinstance(M, Tensor):
- raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
+ if not isinstance(M, torch.Tensor):
+ raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 5:
- raise ValueError(f"Input src must be a BxCxDxHxW tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxDxHxW torch.tensor. Got {src.shape}")
if not (len(M.shape) == 3 or M.shape[-2:] == (4, 4)):
- raise ValueError(f"Input M must be a Bx4x4 tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx4x4 torch.tensor. Got {M.shape}")
# launches the warper
d, h, w = src.shape[-3:]
@@ -1263,22 +1276,23 @@ def warp_perspective3d(
def homography_warp(
- patch_src: Tensor,
- src_homo_dst: Tensor,
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
dsize: tuple[int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
normalized_coordinates: bool = True,
normalized_homography: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Warp image patches or tensors by normalized 2D homographies.
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
Args:
- patch_src: The image or tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.
- src_homo_dst: The homography or stack of homographies from destination to source of shape :math:`(N, 3, 3)`.
+ patch_src: The image or torch.tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.
+ src_homo_dst: The homography or torch.stack of homographies from destination to source of shape
+ :math:`(N, 3, 3)`.
dsize:
if homography normalized: The height and width of the image to warp.
if homography not normalized: size of the output image (height, width).
@@ -1323,35 +1337,35 @@ def homography_warp(
def _transform_warp_impl3d(
- src: Tensor,
- dst_pix_trans_src_pix: Tensor,
+ src: torch.Tensor,
+ dst_pix_trans_src_pix: torch.Tensor,
dsize_src: tuple[int, int, int],
dsize_dst: tuple[int, int, int],
grid_mode: str,
padding_mode: str,
align_corners: bool,
-) -> Tensor:
+) -> torch.Tensor:
"""Compute the transform in normalized coordinates and perform the warping."""
- dst_norm_trans_src_norm: Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
src_norm_trans_dst_norm = torch.linalg.inv(dst_norm_trans_src_norm)
return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners, True)
def homography_warp3d(
- patch_src: Tensor,
- src_homo_dst: Tensor,
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
dsize: tuple[int, int, int],
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
normalized_coordinates: bool = True,
-) -> Tensor:
+) -> torch.Tensor:
r"""Warp image patches or tensors by normalized 3D homographies.
Args:
- patch_src: The image or tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
- src_homo_dst: The homography or stack of homographies from destination to source of shape
+ patch_src: The image or torch.tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
+ src_homo_dst: The homography or torch.stack of homographies from destination to source of shape
:math:`(N, 4, 4)`.
dsize: The height and width of the image to warp.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 644c0fdda..a44100edd 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -21,8 +21,8 @@ import math
import torch
import torch.nn.functional as F
+from torch import nn
-from kornia.core import Module, Tensor, ones, pad, stack, tensor, zeros
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d, gaussian_blur2d
@@ -38,10 +38,10 @@ __all__ = [
]
-def _get_pyramid_gaussian_kernel() -> Tensor:
+def _get_pyramid_gaussian_kernel() -> torch.Tensor:
"""Return a pre-computed gaussian kernel."""
return (
- tensor(
+ torch.tensor(
[
[
[1.0, 4.0, 6.0, 4.0, 1.0],
@@ -56,8 +56,8 @@ def _get_pyramid_gaussian_kernel() -> Tensor:
)
-class PyrDown(Module):
- r"""Blur a tensor and downsamples it.
+class PyrDown(nn.Module):
+ r"""Blur a torch.tensor and downsamples it.
Args:
border_type: the padding mode to be applied before convolving.
@@ -67,7 +67,7 @@ class PyrDown(Module):
factor: the downsampling factor
Return:
- the downsampled tensor.
+ the downsampled torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -85,12 +85,12 @@ class PyrDown(Module):
self.align_corners: bool = align_corners
self.factor: float = factor
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return pyrdown(input, self.border_type, self.align_corners, self.factor)
-class PyrUp(Module):
- r"""Upsample a tensor and then blurs it.
+class PyrUp(nn.Module):
+ r"""Upsample a torch.tensor and then blurs it.
Args:
borde_type: the padding mode to be applied before convolving.
@@ -99,7 +99,7 @@ class PyrUp(Module):
align_corners: interpolation flag.
Return:
- the upsampled tensor.
+ the upsampled torch.tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -116,11 +116,11 @@ class PyrUp(Module):
self.border_type: str = border_type
self.align_corners: bool = align_corners
- def forward(self, input: Tensor) -> Tensor:
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return pyrup(input, self.border_type, self.align_corners)
-class ScalePyramid(Module):
+class ScalePyramid(nn.Module):
r"""Create an scale pyramid of image, usually used for local feature detection.
Images are consequently smoothed with Gaussian blur and downscaled.
@@ -177,14 +177,14 @@ class ScalePyramid(Module):
ksize = int(2.0 * 4.0 * sigma + 1.0)
# matches OpenCV, but may cause padding problem for small images
- # PyTorch does not allow to pad more than original size.
+ # PyTorch does not allow to F.pad more than original size.
# Therefore there is a hack in forward function
if ksize % 2 == 0:
ksize += 1
return ksize
- def get_first_level(self, input: Tensor) -> tuple[Tensor, float, float]:
+ def get_first_level(self, input: torch.Tensor) -> tuple[torch.Tensor, float, float]:
pixel_distance = 1.0
cur_sigma = 0.5
# Same as in OpenCV up to interpolation difference
@@ -204,12 +204,12 @@ class ScalePyramid(Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: Tensor) -> tuple[list[Tensor], list[Tensor], list[Tensor]]:
+ def forward(self, x: torch.Tensor) -> tuple[list[torch.Tensor], list[torch.Tensor], list[torch.Tensor]]:
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
- sigmas = [cur_sigma * ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
- pixel_dists = [pixel_distance * ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
+ sigmas = [cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
+ pixel_dists = [pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
pyr = [[cur_level]]
oct_idx = 0
while True:
@@ -218,7 +218,7 @@ class ScalePyramid(Module):
sigma = cur_sigma * math.sqrt(self.sigma_step**2 - 1.0)
ksize = self.get_kernel_size(sigma)
- # Hack, because PyTorch does not allow to pad more than original size.
+ # Hack, because PyTorch does not allow to F.pad more than original size.
# But for the huge sigmas, one needs huge kernel and padding...
ksize = min(ksize, cur_level.size(2), cur_level.size(3))
@@ -242,18 +242,20 @@ class ScalePyramid(Module):
pixel_dists.append(pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))
oct_idx += 1
- output_pyr = [stack(i, 2) for i in pyr]
+ output_pyr = [torch.stack(i, 2) for i in pyr]
return output_pyr, sigmas, pixel_dists
-def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0) -> Tensor:
- r"""Blur a tensor and downsamples it.
+def pyrdown(
+ input: torch.Tensor, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0
+) -> torch.Tensor:
+ r"""Blur a torch.tensor and downsamples it.
.. image:: _static/img/pyrdown.png
Args:
- input: the tensor to be downsampled.
+ input: the torch.tensor to be downsampled.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
@@ -261,7 +263,7 @@ def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = F
factor: the downsampling factor
Return:
- the downsampled tensor.
+ the downsampled torch.tensor.
Examples:
>>> input = torch.arange(16, dtype=torch.float32).reshape(1, 1, 4, 4)
@@ -272,14 +274,14 @@ def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = F
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- kernel: Tensor = _get_pyramid_gaussian_kernel()
+ kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
_, _, height, width = input.shape
# blur image
- x_blur: Tensor = filter2d(input, kernel, border_type)
+ x_blur: torch.Tensor = filter2d(input, kernel, border_type)
# TODO: use kornia.geometry.resize/rescale
# downsample.
- out: Tensor = F.interpolate(
+ out: torch.Tensor = F.interpolate(
x_blur,
size=(int(float(height) / factor), int(float(width) // factor)),
mode="bilinear",
@@ -288,19 +290,19 @@ def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = F
return out
-def pyrup(input: Tensor, border_type: str = "reflect", align_corners: bool = False) -> Tensor:
- r"""Upsample a tensor and then blurs it.
+def pyrup(input: torch.Tensor, border_type: str = "reflect", align_corners: bool = False) -> torch.Tensor:
+ r"""Upsample a torch.tensor and then blurs it.
.. image:: _static/img/pyrup.png
Args:
- input: the tensor to be downsampled.
+ input: the torch.tensor to be downsampled.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
align_corners: interpolation flag.
Return:
- the downsampled tensor.
+ the downsampled torch.tensor.
Examples:
>>> input = torch.arange(4, dtype=torch.float32).reshape(1, 1, 2, 2)
@@ -313,21 +315,23 @@ def pyrup(input: Tensor, border_type: str = "reflect", align_corners: bool = Fal
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- kernel: Tensor = _get_pyramid_gaussian_kernel()
- # upsample tensor
+ kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
+ # upsample torch.tensor
_, _, height, width = input.shape
# TODO: use kornia.geometry.resize/rescale
- x_up: Tensor = F.interpolate(input, size=(height * 2, width * 2), mode="bilinear", align_corners=align_corners)
+ x_up: torch.Tensor = F.interpolate(
+ input, size=(height * 2, width * 2), mode="bilinear", align_corners=align_corners
+ )
- # blurs upsampled tensor
- x_blur: Tensor = filter2d(x_up, kernel, border_type)
+ # blurs upsampled torch.tensor
+ x_blur: torch.Tensor = filter2d(x_up, kernel, border_type)
return x_blur
def build_pyramid(
- input: Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
-) -> list[Tensor]:
- r"""Construct the Gaussian pyramid for a tensor image.
+ input: torch.Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
+) -> list[torch.Tensor]:
+ r"""Construct the Gaussian pyramid for a torch.tensor image.
.. image:: _static/img/build_pyramid.png
@@ -335,7 +339,7 @@ def build_pyramid(
by recursively applying pyrDown to the previously built pyramid layers.
Args:
- input : the tensor to be used to construct the pyramid.
+ input : the torch.tensor to be used to construct the pyramid.
max_level: 0-based index of the last (the smallest) pyramid layer.
It must be non-negative.
border_type: the padding mode to be applied before convolving.
@@ -355,13 +359,13 @@ def build_pyramid(
)
# create empty list and append the original image
- pyramid: list[Tensor] = []
+ pyramid: list[torch.Tensor] = []
pyramid.append(input)
# iterate and downsample
for _ in range(max_level - 1):
- img_curr: Tensor = pyramid[-1]
- img_down: Tensor = pyrdown(img_curr, border_type, align_corners)
+ img_curr: torch.Tensor = pyramid[-1]
+ img_down: torch.Tensor = pyrdown(img_curr, border_type, align_corners)
pyramid.append(img_down)
return pyramid
@@ -377,9 +381,9 @@ def find_next_powerof_two(x: int) -> int:
def build_laplacian_pyramid(
- input: Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
-) -> list[Tensor]:
- r"""Construct the Laplacian pyramid for a tensor image.
+ input: torch.Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
+) -> list[torch.Tensor]:
+ r"""Construct the Laplacian pyramid for a torch.tensor image.
The function constructs a vector of images and builds the Laplacian pyramid
by recursively computing the difference after applying
@@ -388,7 +392,7 @@ def build_laplacian_pyramid(
See :cite:`burt1987laplacian` for more details.
Args:
- input : the tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
+ input : the torch.tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
max_level: 0-based index of the last (the smallest) pyramid layer.
It must be non-negative.
border_type: the padding mode to be applied before convolving.
@@ -411,29 +415,29 @@ def build_laplacian_pyramid(
require_padding = not (is_powerof_two(w) or is_powerof_two(h))
if require_padding:
- # in case of arbitrary shape tensor image need to be padded.
+ # in case of arbitrary shape torch.tensor image need to be padded.
# Reference: https://stackoverflow.com/a/29967555
padding = (0, find_next_powerof_two(w) - w, 0, find_next_powerof_two(h) - h)
- input = pad(input, padding, "reflect")
+ input = F.pad(input, padding, "reflect")
# create gaussian pyramid
- gaussian_pyramid: list[Tensor] = build_pyramid(input, max_level, border_type, align_corners)
+ gaussian_pyramid: list[torch.Tensor] = build_pyramid(input, max_level, border_type, align_corners)
# create empty list
- laplacian_pyramid: list[Tensor] = []
+ laplacian_pyramid: list[torch.Tensor] = []
# iterate and compute difference of adjacent layers in a gaussian pyramid
for i in range(max_level - 1):
- img_expand: Tensor = pyrup(gaussian_pyramid[i + 1], border_type, align_corners)
- laplacian: Tensor = gaussian_pyramid[i] - img_expand
+ img_expand: torch.Tensor = pyrup(gaussian_pyramid[i + 1], border_type, align_corners)
+ laplacian: torch.Tensor = gaussian_pyramid[i] - img_expand
laplacian_pyramid.append(laplacian)
laplacian_pyramid.append(gaussian_pyramid[-1])
return laplacian_pyramid
-def upscale_double(x: Tensor) -> Tensor:
+def upscale_double(x: torch.Tensor) -> torch.Tensor:
r"""Upscale image by the factor of 2, even indices maps to original indices.
- Odd indices are linearly interpolated from the even ones.
+ Odd indices are linearly interpolated from the even torch.ones.
Args:
x: input image.
@@ -446,7 +450,7 @@ def upscale_double(x: Tensor) -> Tensor:
KORNIA_CHECK_IS_TENSOR(x)
KORNIA_CHECK_SHAPE(x, ["*", "H", "W"])
double_shape = x.shape[:-2] + (x.shape[-2] * 2, x.shape[-1] * 2)
- upscaled = zeros(double_shape, device=x.device, dtype=x.dtype)
+ upscaled = torch.zeros(double_shape, device=x.device, dtype=x.dtype)
upscaled[..., ::2, ::2] = x
upscaled[..., ::2, 1::2][..., :-1] = (upscaled[..., ::2, ::2][..., :-1] + upscaled[..., ::2, 2::2]) / 2
upscaled[..., ::2, -1] = upscaled[..., ::2, -2]
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 9b5383105..5d1f0f428 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -20,7 +20,6 @@ from __future__ import annotations
import torch
from torch import nn
-from kornia.core import ones, zeros
from kornia.utils import create_meshgrid
from kornia.utils.helpers import _torch_solve_cast
@@ -44,7 +43,7 @@ def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torc
def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
- r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, where `r` is the euclidean distance.
+ r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, torch.where `r` is the euclidean distance.
Since
:math: `\log(r) = 1/2 \log(r^2)`, this function takes the squared distance matrix and calculates
@@ -57,16 +56,16 @@ def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torc
def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Compute the TPS transform parameters that warp source points to target points.
- The input to this function is a tensor of :math:`(x, y)` source points :math:`(B, N, 2)` and a corresponding
- tensor of target :math:`(x, y)` points :math:`(B, N, 2)`.
+ The input to this function is a torch.tensor of :math:`(x, y)` source points :math:`(B, N, 2)` and a corresponding
+ torch.tensor of target :math:`(x, y)` points :math:`(B, N, 2)`.
Args:
points_src: batch of source points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
points_dst: batch of target points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
Returns:
- :math:`(B, N, 2)` tensor of kernel weights and :math:`(B, 3, 2)`
- tensor of affine weights. The last dimension contains the x-transform and y-transform weights
+ :math:`(B, N, 2)` torch.tensor of kernel weights and :math:`(B, 3, 2)`
+ torch.tensor of affine weights. The last dimension contains the x-transform and y-transform weights
as separate columns.
Example:
@@ -99,8 +98,8 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
pair_distance: torch.Tensor = _pair_square_euclidean(points_src, points_dst)
k_matrix: torch.Tensor = _kernel_distance(pair_distance)
- zero_mat: torch.Tensor = zeros(batch_size, 3, 3, device=device, dtype=dtype)
- one_mat: torch.Tensor = ones(batch_size, num_points, 1, device=device, dtype=dtype)
+ zero_mat: torch.Tensor = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
+ one_mat: torch.Tensor = torch.ones(batch_size, num_points, 1, device=device, dtype=dtype)
dest_with_zeros: torch.Tensor = torch.cat((points_dst, zero_mat[:, :, :2]), 1)
p_matrix: torch.Tensor = torch.cat((one_mat, points_src), -1)
p_matrix_t: torch.Tensor = torch.cat((p_matrix, zero_mat), 1).transpose(1, 2)
@@ -117,21 +116,22 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
def warp_points_tps(
points_src: torch.Tensor, kernel_centers: torch.Tensor, kernel_weights: torch.Tensor, affine_weights: torch.Tensor
) -> torch.Tensor:
- r"""Warp a tensor of coordinate points using the thin plate spline defined by arguments.
+ r"""Warp a torch.tensor of coordinate points using the thin plate spline defined by arguments.
- The source points should be a :math:`(B, N, 2)` tensor of :math:`(x, y)` coordinates. The kernel centers are
- a :math:`(B, K, 2)` tensor of :math:`(x, y)` coordinates. The kernel weights are a :math:`(B, K, 2)` tensor,
- and the affine weights are a :math:`(B, 3, 2)` tensor. For the weight tensors, tensor[..., 0] contains the
- weights for the x-transform and tensor[..., 1] the weights for the y-transform.
+ The source points should be a :math:`(B, N, 2)` torch.tensor of :math:`(x, y)` coordinates. The kernel centers are
+ a :math:`(B, K, 2)` torch.tensor of :math:`(x, y)` coordinates. The kernel weights are a :math:`(B, K, 2)`
+ torch.tensor, and the affine weights are a :math:`(B, 3, 2)` torch.tensor. For the weight tensors,
+ torch.tensor[..., 0] contains the weights for the x-transform and torch.tensor[..., 1] the weights
+ for the y-transform.
Args:
- points_src: tensor of source points :math:`(B, N, 2)`.
- kernel_centers: tensor of kernel center points :math:`(B, K, 2)`.
- kernel_weights: tensor of kernl weights :math:`(B, K, 2)`.
- affine_weights: tensor of affine weights :math:`(B, 3, 2)`.
+ points_src: torch.tensor of source points :math:`(B, N, 2)`.
+ kernel_centers: torch.tensor of kernel center points :math:`(B, K, 2)`.
+ kernel_weights: torch.tensor of kernl weights :math:`(B, K, 2)`.
+ affine_weights: torch.tensor of affine weights :math:`(B, 3, 2)`.
Returns:
- The :math:`(B, N, 2)` tensor of warped source points, from applying the TPS transform.
+ The :math:`(B, N, 2)` torch.tensor of warped source points, from applying the TPS transform.
Example:
>>> points_src = torch.rand(1, 5, 2)
@@ -189,7 +189,7 @@ def warp_image_tps(
align_corners: bool = False,
padding_mode: str = "zeros",
) -> torch.Tensor:
- r"""Warp an image tensor according to the thin plate spline transform defined by arguments.
+ r"""Warp an image torch.tensor according to the thin plate spline transform defined by arguments.
.. image:: _static/img/warp_image_tps.png
@@ -197,19 +197,19 @@ def warp_image_tps(
image for interpolation of the output pixel. So the TPS parameters should correspond to a warp from
output space to input space.
- The input `image` is a :math:`(B, C, H, W)` tensor. The kernel centers, kernel weight and affine weights
+ The input `image` is a :math:`(B, C, H, W)` torch.tensor. The kernel centers, kernel weight and affine weights
are the same as in `warp_points_tps`.
Args:
- image: input image tensor :math:`(B, C, H, W)`.
+ image: input image torch.tensor :math:`(B, C, H, W)`.
kernel_centers: kernel center points :math:`(B, K, 2)`.
- kernel_weights: tensor of kernl weights :math:`(B, K, 2)`.
- affine_weights: tensor of affine weights :math:`(B, 3, 2)`.
+ kernel_weights: torch.tensor of kernl weights :math:`(B, K, 2)`.
+ affine_weights: torch.tensor of affine weights :math:`(B, 3, 2)`.
align_corners: interpolation flag used by `grid_sample`.
padding_mode: padding flag used by `grid_sample`.
Returns:
- warped image tensor :math:`(B, C, H, W)`.
+ warped image torch.tensor :math:`(B, C, H, W)`.
Example:
>>> points_src = torch.rand(1, 5, 2)
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index cf8d31666..0cb476a42 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -17,7 +17,9 @@
from typing import Optional, Tuple, Union, cast
-from kornia.core import Device, Dtype, Tensor, as_tensor, normalize, rand, stack
+import torch
+import torch.nn.functional as F
+
from kornia.core.check import KORNIA_CHECK
from kornia.core.tensor_wrapper import TensorWrapper, wrap # type: ignore[attr-defined]
from kornia.geometry.linalg import batched_dot_product, batched_squared_norm
@@ -27,35 +29,35 @@ __all__ = ["Scalar", "Vector2", "Vector3"]
# TODO: implement more functionality to validate
class Scalar(TensorWrapper):
- def __init__(self, data: Tensor) -> None:
+ def __init__(self, data: torch.Tensor) -> None:
super().__init__(data)
class Vector3(TensorWrapper):
- def __init__(self, vector: Tensor) -> None:
+ def __init__(self, vector: torch.Tensor) -> None:
super().__init__(vector)
KORNIA_CHECK(vector.shape[-1] == 3)
def __repr__(self) -> str:
return f"x: {self.x}\ny: {self.y}\nz: {self.z}"
- def __getitem__(self, idx: Union[slice, int, Tensor]) -> "Vector3":
+ def __getitem__(self, idx: Union[slice, int, torch.Tensor]) -> "Vector3":
return Vector3(self.data[idx, ...])
@property
- def x(self) -> Tensor:
+ def x(self) -> torch.Tensor:
return self.data[..., 0]
@property
- def y(self) -> Tensor:
+ def y(self) -> torch.Tensor:
return self.data[..., 1]
@property
- def z(self) -> Tensor:
+ def z(self) -> torch.Tensor:
return self.data[..., 2]
def normalized(self) -> "Vector3":
- return Vector3(normalize(self.data, p=2, dim=-1))
+ return Vector3(F.normalize(self.data, p=2, dim=-1))
def dot(self, right: "Vector3") -> Scalar:
return Scalar(batched_dot_product(self.data, right.data))
@@ -65,11 +67,14 @@ class Vector3(TensorWrapper):
@classmethod
def random(
- cls, shape: Optional[Tuple[int, ...]] = None, device: Optional[Device] = None, dtype: Dtype = None
+ cls,
+ shape: Optional[Tuple[int, ...]] = None,
+ device: Optional[Union[str, torch.device]] = None,
+ dtype: Optional[torch.dtype] = None,
) -> "Vector3":
if shape is None:
shape = ()
- return cls(rand((*shape, 3), device=device, dtype=dtype))
+ return cls(torch.rand((*shape, 3), device=device, dtype=dtype))
# TODO: polish overload
# @overload
@@ -94,42 +99,42 @@ class Vector3(TensorWrapper):
@classmethod
def from_coords(
cls,
- x: Union[float, Tensor],
- y: Union[float, Tensor],
- z: Union[float, Tensor],
- device: Optional[Device] = None,
- dtype: Dtype = None,
+ x: Union[float, torch.Tensor],
+ y: Union[float, torch.Tensor],
+ z: Union[float, torch.Tensor],
+ device: Optional[Union[str, torch.device]] = None,
+ dtype: Optional[torch.dtype] = None,
) -> "Vector3":
KORNIA_CHECK(type(x) is type(y) is type(z))
- KORNIA_CHECK(isinstance(x, (Tensor, float)))
+ KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
if isinstance(x, float):
- return wrap(as_tensor((x, y, z), device=device, dtype=dtype), Vector3)
+ return wrap(torch.as_tensor((x, y, z), device=device, dtype=dtype), Vector3)
# TODO: this is totally insane ...
- tensors: Tuple[Tensor, ...] = (x, cast(Tensor, y), cast(Tensor, z))
- return wrap(stack(tensors, -1), Vector3)
+ tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y), cast(torch.Tensor, z))
+ return wrap(torch.stack(tensors, -1), Vector3)
class Vector2(TensorWrapper):
- def __init__(self, vector: Tensor) -> None:
+ def __init__(self, vector: torch.Tensor) -> None:
super().__init__(vector)
KORNIA_CHECK(vector.shape[-1] == 2)
def __repr__(self) -> str:
return f"x: {self.x}\ny: {self.y}"
- def __getitem__(self, idx: Union[slice, int, Tensor]) -> "Vector2":
+ def __getitem__(self, idx: Union[slice, int, torch.Tensor]) -> "Vector2":
return Vector2(self.data[idx, ...])
@property
- def x(self) -> Tensor:
+ def x(self) -> torch.Tensor:
return self.data[..., 0]
@property
- def y(self) -> Tensor:
+ def y(self) -> torch.Tensor:
return self.data[..., 1]
def normalized(self) -> "Vector2":
- return Vector2(normalize(self.data, p=2, dim=-1))
+ return Vector2(F.normalize(self.data, p=2, dim=-1))
def dot(self, right: "Vector2") -> Scalar:
return Scalar(batched_dot_product(self.data, right.data))
@@ -138,22 +143,31 @@ class Vector2(TensorWrapper):
return Scalar(batched_squared_norm(self.data))
@classmethod
- def random(cls, shape: Optional[Tuple[int, ...]] = None, device: Device = None, dtype: Dtype = None) -> "Vector2":
+ def random(
+ cls,
+ shape: Optional[Tuple[int, ...]] = None,
+ device: Optional[Union[str, torch.device]] = None,
+ dtype: Optional[torch.dtype] = None,
+ ) -> "Vector2":
if shape is None:
shape = ()
- return cls(rand((*shape, 2), device=device, dtype=dtype))
+ return cls(torch.rand((*shape, 2), device=device, dtype=dtype))
@classmethod
def from_coords(
- cls, x: Union[float, Tensor], y: Union[float, Tensor], device: Device = None, dtype: Dtype = None
+ cls,
+ x: Union[float, torch.Tensor],
+ y: Union[float, torch.Tensor],
+ device: Optional[Union[str, torch.device]] = None,
+ dtype: Optional[torch.dtype] = None,
) -> "Vector2":
KORNIA_CHECK(type(x) is type(y))
- KORNIA_CHECK(isinstance(x, (Tensor, float)))
+ KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
if isinstance(x, float):
- return wrap(as_tensor((x, y), device=device, dtype=dtype), Vector2)
+ return wrap(torch.as_tensor((x, y), device=device, dtype=dtype), Vector2)
# TODO: this is totally insane ...
- tensors: Tuple[Tensor, ...] = (x, cast(Tensor, y))
- return wrap(stack(tensors, -1), Vector2)
+ tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y))
+ return wrap(torch.stack(tensors, -1), Vector2)
Vec3 = Vector3
@@ -162,7 +176,7 @@ Vec2 = Vector2
# TODO: adapt to TensorWrapper
# class UnitVector(Module):
-# def __init__(self, vector: Tensor) -> None:
+# def __init__(self, vector: torch.Tensor) -> None:
# super().__init__()
# KORNIA_CHECK_SHAPE(vector, ["B", "N"])
# self._vector = Parameter(vector)
diff --git a/kornia/image/base.py b/kornia/image/base.py
index 2fa10f4f9..8ea91522d 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -20,7 +20,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from kornia.core import Tensor
+import torch
@dataclass(frozen=True)
@@ -40,8 +40,8 @@ class ImageSize:
"""
- height: int | Tensor
- width: int | Tensor
+ height: int | torch.Tensor
+ width: int | torch.Tensor
class ColorSpace(Enum):
diff --git a/kornia/image/image.py b/kornia/image/image.py
index 206b3b60e..469a5e709 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -18,13 +18,12 @@
from __future__ import annotations
from pathlib import Path
-from typing import Any
+from typing import Any, Union
import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
import kornia.color
-from kornia.core import Device, Dtype, Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
from kornia.io.io import ImageLoadType, load_image, write_image
@@ -36,12 +35,12 @@ DLPack = Any
class Image:
- r"""Class that holds an Image Tensor representation.
+ r"""Class that holds an Image torch.Tensor representation.
.. note::
Disclaimer: This class provides the minimum functionality for image manipulation. However, as soon
- as you start to experiment with advanced tensor manipulation, you might expect fancy
+ as you start to experiment with advanced torch.tensor manipulation, you might expect fancy
polymorphic behaviours.
.. warning::
@@ -49,7 +48,7 @@ class Image:
This API is experimental and might suffer changes in the future.
Args:
- data: a torch tensor containing the image data.
+ data: a torch torch.tensor containing the image data.
layout: a dataclass containing the image layout information.
Examples:
@@ -76,11 +75,11 @@ class Image:
"""
- def __init__(self, data: Tensor, pixel_format: PixelFormat, layout: ImageLayout) -> None:
+ def __init__(self, data: torch.Tensor, pixel_format: PixelFormat, layout: ImageLayout) -> None:
"""Image constructor.
Args:
- data: a torch tensor containing the image data.
+ data: a torch torch.tensor containing the image data.
pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
@@ -104,7 +103,7 @@ class Image:
return f"Image data: {self.data}\nPixel Format: {self.pixel_format}\n Layout: {self.layout}"
# TODO: explore use TensorWrapper
- def to(self, device: Device = None, dtype: Dtype = None) -> Image:
+ def to(self, device: Union[str, torch.device, None] = None, dtype: Union[torch.dtype, None] = None) -> Image:
"""Move the image to the given device and dtype.
Args:
@@ -127,8 +126,8 @@ class Image:
return Image(self.data.clone(), self.pixel_format, self.layout)
@property
- def data(self) -> Tensor:
- """Return the underlying tensor data."""
+ def data(self) -> torch.Tensor:
+ """Return the underlying torch.tensor data."""
return self._data
@property
@@ -279,13 +278,13 @@ class Image:
color_space: ColorSpace = ColorSpace.RGB,
channels_order: ChannelsOrder = ChannelsOrder.CHANNELS_LAST,
) -> Image:
- """Construct an image tensor from a numpy array.
+ """Construct an image torch.tensor from a numpy array.
Args:
data: a numpy array containing the image data.
color_space: the color space of the image.
pixel_format: the pixel format of the image.
- channels_order: what dimension the channels are in the image tensor.
+ channels_order: what dimension the channels are in the image torch.tensor.
Example:
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
@@ -310,16 +309,16 @@ class Image:
# create the image layout based on the input data
layout = ImageLayout(image_size=image_size, channels=channels, channels_order=channels_order)
- # create the image tensor
+ # create the image torch.tensor
return cls(torch.from_numpy(data), pixel_format, layout)
def to_numpy(self) -> np_ndarray:
- """Return a numpy array in cpu from the image tensor."""
+ """Return a numpy array in cpu from the image torch.tensor."""
return self.data.cpu().detach().numpy()
@classmethod
def from_dlpack(cls, data: DLPack) -> Image:
- """Construct an image tensor from a DLPack capsule.
+ """Construct an image torch.tensor from a DLPack capsule.
Args:
data: a DLPack capsule from numpy, tvm or jax.
@@ -329,7 +328,7 @@ class Image:
>>> img = Image.from_dlpack(x.__dlpack__())
"""
- _data: Tensor = from_dlpack(data)
+ _data: torch.Tensor = from_dlpack(data)
pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=_data.element_size() * 8)
@@ -343,19 +342,19 @@ class Image:
return cls(_data, pixel_format, layout)
def to_dlpack(self) -> DLPack:
- """Return a DLPack capsule from the image tensor."""
+ """Return a DLPack capsule from the image torch.tensor."""
return to_dlpack(self.data)
@classmethod
def from_file(cls, file_path: str | Path) -> Image:
- """Construct an image tensor from a file.
+ """Construct an image torch.tensor from a file.
Args:
file_path: the path to the file to read the image from.
"""
# TODO: allow user to specify the desired type and device
- data: Tensor = load_image(file_path, desired_type=ImageLoadType.RGB8, device="cpu")
+ data: torch.Tensor = load_image(file_path, desired_type=ImageLoadType.RGB8, device="cpu")
pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=data.element_size() * 8)
@@ -386,7 +385,7 @@ class Image:
write_image(file_path, data)
def print(self, max_width: int = 256) -> None:
- """Print the image tensor to the console.
+ """Print the image torch.tensor to the console.
Args:
max_width: the maximum width of the image to print.
diff --git a/kornia/io/io.py b/kornia/io/io.py
index bc2db64f7..cf04068ba 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -19,13 +19,12 @@ from __future__ import annotations
from enum import Enum
from pathlib import Path
-from typing import Any
+from typing import Any, Union
import kornia_rs
import torch
import kornia
-from kornia.core import Device, Tensor
from kornia.core.check import KORNIA_CHECK
from kornia.utils import image_to_tensor, tensor_to_image
@@ -41,17 +40,17 @@ class ImageLoadType(Enum):
RGB32 = 5
-def _load_image_to_tensor(path_file: Path, device: Device) -> Tensor:
+def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None]) -> torch.Tensor:
"""Read an image file and decode using the Kornia Rust backend.
The decoded image is returned as numpy array with shape HxWxC.
Args:
path_file: Path to a valid image file.
- device: the device where you want to get your image placed.
+ device: the device torch.where you want to get your image placed.
Return:
- Image tensor with shape :math:`(3,H,W)`.
+ Image torch.tensor with shape :math:`(3,H,W)`.
"""
# read image and return as `np.ndarray` with shape HxWxC
@@ -60,46 +59,48 @@ def _load_image_to_tensor(path_file: Path, device: Device) -> Tensor:
else:
img = kornia_rs.read_image_any(str(path_file))
- # convert the image to tensor with shape CxHxW
+ # convert the image to torch.tensor with shape CxHxW
img_t = image_to_tensor(img, keepdim=True)
- # move the tensor to the desired device,
+ # move the torch.tensor to the desired device,
dev = device if isinstance(device, torch.device) or device is None else torch.device(device)
return img_t.to(device=dev)
-def _to_float32(image: Tensor) -> Tensor:
- """Convert an image tensor to float32."""
+def _to_float32(image: torch.Tensor) -> torch.Tensor:
+ """Convert an image torch.tensor to float32."""
KORNIA_CHECK(image.dtype == torch.uint8)
return image.float() / 255.0
-def _to_uint8(image: Tensor) -> Tensor:
- """Convert an image tensor to uint8."""
+def _to_uint8(image: torch.Tensor) -> torch.Tensor:
+ """Convert an image torch.tensor to uint8."""
KORNIA_CHECK(image.dtype == torch.float32)
return image.mul(255.0).byte()
def load_image(
- path_file: str | Path, desired_type: ImageLoadType = ImageLoadType.RGB32, device: Device = "cpu"
-) -> Tensor:
+ path_file: str | Path,
+ desired_type: ImageLoadType = ImageLoadType.RGB32,
+ device: Union[str, torch.device, None] = "cpu",
+) -> torch.Tensor:
"""Read an image file and decode using the Kornia Rust backend.
Args:
path_file: Path to a valid image file.
desired_type: the desired image type, defined by color space and dtype.
- device: the device where you want to get your image placed.
+ device: the device torch.where you want to get your image placed.
Return:
- Image tensor with shape :math:`(3,H,W)`.
+ Image torch.tensor with shape :math:`(3,H,W)`.
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
# read the image using the kornia_rs package
- image: Tensor = _load_image_to_tensor(path_file, device) # CxHxW
+ image: torch.Tensor = _load_image_to_tensor(path_file, device) # CxHxW
if desired_type == ImageLoadType.UNCHANGED:
return image
@@ -180,12 +181,12 @@ def _write_float32_image(path_file: Path, img_np: Any) -> None:
raise NotImplementedError(f"Unsupported file extension: {path_file.suffix} for float32 image")
-def write_image(path_file: str | Path, image: Tensor, quality: int = 80) -> None:
+def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -> None:
"""Save an image file using the Kornia Rust backend.
Args:
path_file: Path to a valid image file.
- image: Image tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.
+ image: Image torch.tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.
quality: The quality of the JPEG encoding. If the file extension is .png or .tiff, the quality is ignored.
Return:
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index b69e806a0..7df3633d5 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -18,13 +18,12 @@
from __future__ import annotations
import torch
-from torch import Tensor
+from torch import nn
-from kornia.core import Module
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
-def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
+def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none") -> torch.Tensor:
r"""Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.
According to [1], we compute the Cauchy loss as follows:
@@ -42,8 +41,8 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
[2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf
Args:
- img1: the predicted tensor with shape :math:`(*)`.
- img2: the target tensor with the same shape as img1.
+ img1: the predicted torch.tensor with shape :math:`(*)`.
+ img2: the target torch.tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -88,7 +87,7 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
return loss
-class CauchyLoss(Module):
+class CauchyLoss(nn.Module):
r"""Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.
According to [1], we compute the Cauchy loss as follows:
@@ -113,8 +112,8 @@ class CauchyLoss(Module):
summed.
Shape:
- - img1: the predicted tensor with shape :math:`(*)`.
- - img2: the target tensor with the same shape as img1.
+ - img1: the predicted torch.tensor with shape :math:`(*)`.
+ - img2: the target torch.tensor with the same shape as img1.
Example:
>>> criterion = CauchyLoss(reduction="mean")
@@ -129,5 +128,5 @@ class CauchyLoss(Module):
super().__init__()
self.reduction = reduction
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return cauchy_loss(img1=img1, img2=img2, reduction=self.reduction)
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 5e519c46a..a619c79df 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -17,13 +17,14 @@
from __future__ import annotations
-from torch import Tensor
+import torch
+from torch import nn
-from kornia.core import Module
+# from torch import Tensor (use torch.Tensor instead)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
-def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
+def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none") -> torch.Tensor:
r"""Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.
According to [1], we compute the Charbonnier loss as follows:
@@ -47,8 +48,8 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
a slightly different implementation (see [4]).
Args:
- img1: the predicted tensor with shape :math:`(*)`.
- img2: the target tensor with the same shape as img1.
+ img1: the predicted torch.tensor with shape :math:`(*)`.
+ img2: the target torch.tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -93,7 +94,7 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
return loss
-class CharbonnierLoss(Module):
+class CharbonnierLoss(nn.Module):
r"""Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.
According to [1], we compute the Charbonnier loss as follows:
@@ -124,8 +125,8 @@ class CharbonnierLoss(Module):
summed.
Shape:
- - img1: the predicted tensor with shape :math:`(*)`.
- - img2: the target tensor with the same shape as img1.
+ - img1: the predicted torch.tensor with shape :math:`(*)`.
+ - img2: the target torch.tensor with the same shape as img1.
Example:
>>> criterion = CharbonnierLoss(reduction="mean")
@@ -140,5 +141,5 @@ class CharbonnierLoss(Module):
super().__init__()
self.reduction = reduction
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return charbonnier_loss(img1=img1, img2=img2, reduction=self.reduction)
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index e7ce32338..0aa350bd7 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -20,9 +20,9 @@ from __future__ import annotations
from typing import Optional
import torch
+import torch.nn.functional as F
from torch import nn
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.losses._utils import mask_ignore_pixels
from kornia.utils.one_hot import one_hot
@@ -33,13 +33,13 @@ from kornia.utils.one_hot import one_hot
def dice_loss(
- pred: Tensor,
- target: Tensor,
+ pred: torch.Tensor,
+ target: torch.Tensor,
average: str = "micro",
eps: float = 1e-8,
- weight: Optional[Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
-) -> Tensor:
+) -> torch.Tensor:
r"""Criterion that computes SΓΈrensen-Dice Coefficient loss.
According to [1], we compute the SΓΈrensen-Dice Coefficient as follows:
@@ -50,7 +50,7 @@ def dice_loss(
Where:
- :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot tensor with the class labels.
+ - :math:`Y` expects to be the one-hot torch.tensor with the class labels.
the loss, is finally computed as:
@@ -62,8 +62,8 @@ def dice_loss(
[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
Args:
- pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
- target: labels tensor with shape :math:`(N, H, W)` where each value
+ pred: logits torch.tensor with shape :math:`(N, C, H, W)` torch.where C = number of classes.
+ target: labels torch.tensor with shape :math:`(N, H, W)` torch.where each value
is :math:`0 ≀ targets[i] ≀ C-1`.
average:
Reduction applied in multi-class scenario:
@@ -74,7 +74,7 @@ def dice_loss(
ignore_index: labels with this value are ignored in the loss computation.
Return:
- One-element tensor of the computed loss.
+ One-element torch.tensor of the computed loss.
Example:
>>> N = 5 # num_classes
@@ -98,13 +98,13 @@ def dice_loss(
possible_average = {"micro", "macro"}
KORNIA_CHECK(average in possible_average, f"The `average` has to be one of {possible_average}. Got: {average}")
- # compute softmax over the classes axis
- pred_soft: Tensor = pred.softmax(dim=1)
+ # compute F.softmax over the classes axis
+ pred_soft: torch.Tensor = F.softmax(pred, dim=1)
target, target_mask = mask_ignore_pixels(target, ignore_index)
- # create the labels one hot tensor
- target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # create the labels one hot torch.tensor
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# mask ignore pixels
if target_mask is not None:
@@ -114,7 +114,7 @@ def dice_loss(
# compute the actual dice score
if weight is not None:
- KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
+ KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
@@ -162,7 +162,7 @@ class DiceLoss(nn.Module):
Where:
- :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot tensor with the class labels.
+ - :math:`Y` expects to be the one-hot torch.tensor with the class labels.
the loss, is finally computed as:
@@ -183,8 +183,8 @@ class DiceLoss(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, H, W)` where C = number of classes.
- - Target: :math:`(N, H, W)` where each value is
+ - Pred: :math:`(N, C, H, W)` torch.where C = number of classes.
+ - Target: :math:`(N, H, W)` torch.where each value is
:math:`0 ≀ targets[i] ≀ C-1`.
Example:
@@ -201,7 +201,7 @@ class DiceLoss(nn.Module):
self,
average: str = "micro",
eps: float = 1e-8,
- weight: Optional[Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
) -> None:
super().__init__()
@@ -210,5 +210,5 @@ class DiceLoss(nn.Module):
self.weight = weight
self.ignore_index = ignore_index
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return dice_loss(pred, target, self.average, self.eps, self.weight, self.ignore_index)
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 4698a9cf1..2caafcfd9 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -22,10 +22,8 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
-from kornia.core import Tensor
-
-def _kl_div_2d(p: Tensor, q: Tensor) -> Tensor:
+def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# D_KL(P || Q)
batch, chans, height, width = p.shape
unsummed_kl = F.kl_div(
@@ -35,25 +33,25 @@ def _kl_div_2d(p: Tensor, q: Tensor) -> Tensor:
return kl_values
-def _js_div_2d(p: Tensor, q: Tensor) -> Tensor:
+def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# JSD(P || Q)
m = 0.5 * (p + q)
return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)
# TODO: add this to the main module
-def _reduce_loss(losses: Tensor, reduction: str) -> Tensor:
+def _reduce_loss(losses: torch.Tensor, reduction: str) -> torch.Tensor:
if reduction == "none":
return losses
return torch.mean(losses) if reduction == "mean" else torch.sum(losses)
-def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Tensor:
+def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
r"""Calculate the Jensen-Shannon divergence loss between heatmaps.
Args:
- pred: the input tensor with shape :math:`(B, N, H, W)`.
- target: the target tensor with shape :math:`(B, N, H, W)`.
+ pred: the input torch.tensor with shape :math:`(B, N, H, W)`.
+ target: the target torch.tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
@@ -70,12 +68,12 @@ def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Ten
return _reduce_loss(_js_div_2d(target, pred), reduction)
-def kl_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Tensor:
+def kl_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
r"""Calculate the Kullback-Leibler divergence loss between heatmaps.
Args:
- pred: the input tensor with shape :math:`(B, N, H, W)`.
- target: the target tensor with shape :math:`(B, N, H, W)`.
+ pred: the input torch.tensor with shape :math:`(B, N, H, W)`.
+ target: the target torch.tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index a345f1b06..53dd978bd 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -22,7 +22,6 @@ from typing import Optional
import torch
from torch import nn
-from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.losses._utils import mask_ignore_pixels
from kornia.utils.one_hot import one_hot
@@ -32,14 +31,14 @@ from kornia.utils.one_hot import one_hot
def focal_loss(
- pred: Tensor,
- target: Tensor,
+ pred: torch.Tensor,
+ target: torch.Tensor,
alpha: Optional[float],
gamma: float = 2.0,
reduction: str = "none",
- weight: Optional[Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
-) -> Tensor:
+) -> torch.Tensor:
r"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
@@ -52,8 +51,8 @@ def focal_loss(
- :math:`p_t` is the model's estimated probability for each class.
Args:
- pred: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
- target: labels tensor with shape :math:`(N, *)` where each value is an integer
+ pred: logits torch.tensor with shape :math:`(N, C, *)` torch.where C = number of classes.
+ target: labels torch.tensor with shape :math:`(N, *)` torch.where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
gamma: Focusing parameter :math:`\gamma >= 0`.
@@ -90,29 +89,31 @@ def focal_loss(
target, target_mask = mask_ignore_pixels(target, ignore_index)
- # create the labels one hot tensor
- target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # create the labels one hot torch.tensor
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# mask ignore pixels
if target_mask is not None:
target_mask.unsqueeze_(1)
target_one_hot = target_one_hot * target_mask
- # compute softmax over the classes axis
- log_pred_soft: Tensor = pred.log_softmax(1)
+ # compute F.softmax over the classes axis
+ log_pred_soft: torch.Tensor = pred.log_softmax(1)
# compute the actual focal loss
- loss_tmp: Tensor = -torch.pow(1.0 - log_pred_soft.exp(), gamma) * log_pred_soft * target_one_hot
+ loss_tmp: torch.Tensor = -torch.pow(1.0 - log_pred_soft.exp(), gamma) * log_pred_soft * target_one_hot
num_of_classes = pred.shape[1]
broadcast_dims = [-1] + [1] * len(pred.shape[2:])
if alpha is not None:
- alpha_fac = tensor([1 - alpha] + [alpha] * (num_of_classes - 1), dtype=loss_tmp.dtype, device=loss_tmp.device)
+ alpha_fac = torch.tensor(
+ [1 - alpha] + [alpha] * (num_of_classes - 1), dtype=loss_tmp.dtype, device=loss_tmp.device
+ )
alpha_fac = alpha_fac.view(broadcast_dims)
loss_tmp = alpha_fac * loss_tmp
if weight is not None:
- KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
+ KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
@@ -160,8 +161,8 @@ class FocalLoss(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, *)` where C = number of classes.
- - Target: :math:`(N, *)` where each value is an integer
+ - Pred: :math:`(N, C, *)` torch.where C = number of classes.
+ - Target: :math:`(N, *)` torch.where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
Example:
@@ -180,30 +181,30 @@ class FocalLoss(nn.Module):
alpha: Optional[float],
gamma: float = 2.0,
reduction: str = "none",
- weight: Optional[Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
) -> None:
super().__init__()
self.alpha: Optional[float] = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.weight: Optional[Tensor] = weight
+ self.weight: Optional[torch.Tensor] = weight
self.ignore_index: Optional[int] = ignore_index
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight, self.ignore_index)
def binary_focal_loss_with_logits(
- pred: Tensor,
- target: Tensor,
+ pred: torch.Tensor,
+ target: torch.Tensor,
alpha: Optional[float] = 0.25,
gamma: float = 2.0,
reduction: str = "none",
- pos_weight: Optional[Tensor] = None,
- weight: Optional[Tensor] = None,
+ pos_weight: Optional[torch.Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
-) -> Tensor:
+) -> torch.Tensor:
r"""Criterion that computes Binary Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
@@ -212,13 +213,13 @@ def binary_focal_loss_with_logits(
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
- where:
+ torch.where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
- pred: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
- target: labels tensor with the same shape as pred :math:`(N, C, *)`
- where each value is between 0 and 1.
+ pred: logits torch.tensor with shape :math:`(N, C, *)` torch.where C = number of classes.
+ target: labels torch.tensor with the same shape as pred :math:`(N, C, *)`
+ torch.where each value is between 0 and 1.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
@@ -250,8 +251,8 @@ def binary_focal_loss_with_logits(
f"pred and target must be in the same device. Got: {pred.device} and {target.device}",
)
- log_probs_pos: Tensor = nn.functional.logsigmoid(pred)
- log_probs_neg: Tensor = nn.functional.logsigmoid(-pred)
+ log_probs_pos: torch.Tensor = nn.functional.logsigmoid(pred)
+ log_probs_neg: torch.Tensor = nn.functional.logsigmoid(-pred)
target, target_mask = mask_ignore_pixels(target, ignore_index)
@@ -260,8 +261,8 @@ def binary_focal_loss_with_logits(
log_probs_neg = log_probs_neg * target_mask
log_probs_pos = log_probs_pos * target_mask
- pos_term: Tensor = -log_probs_neg.exp().pow(gamma) * target * log_probs_pos
- neg_term: Tensor = -log_probs_pos.exp().pow(gamma) * (1.0 - target) * log_probs_neg
+ pos_term: torch.Tensor = -log_probs_neg.exp().pow(gamma) * target * log_probs_pos
+ neg_term: torch.Tensor = -log_probs_pos.exp().pow(gamma) * (1.0 - target) * log_probs_neg
if alpha is not None:
pos_term = alpha * pos_term
neg_term = (1.0 - alpha) * neg_term
@@ -269,7 +270,7 @@ def binary_focal_loss_with_logits(
num_of_classes = pred.shape[1]
broadcast_dims = [-1] + [1] * len(pred.shape[2:])
if pos_weight is not None:
- KORNIA_CHECK_IS_TENSOR(pos_weight, "pos_weight must be Tensor or None.")
+ KORNIA_CHECK_IS_TENSOR(pos_weight, "pos_weight must be torch.Tensor or None.")
KORNIA_CHECK(
(pos_weight.shape[0] == num_of_classes and pos_weight.numel() == num_of_classes),
f"pos_weight shape must be (num_of_classes,): ({num_of_classes},), got {pos_weight.shape}",
@@ -282,9 +283,9 @@ def binary_focal_loss_with_logits(
pos_weight = pos_weight.view(broadcast_dims)
pos_term = pos_weight * pos_term
- loss_tmp: Tensor = pos_term + neg_term
+ loss_tmp: torch.Tensor = pos_term + neg_term
if weight is not None:
- KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
+ KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
@@ -317,7 +318,7 @@ class BinaryFocalLossWithLogits(nn.Module):
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
- where:
+ torch.where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
@@ -334,9 +335,9 @@ class BinaryFocalLossWithLogits(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, *)` where C = number of classes.
+ - Pred: :math:`(N, C, *)` torch.where C = number of classes.
- Target: the same shape as Pred :math:`(N, C, *)`
- where each value is between 0 and 1.
+ torch.where each value is between 0 and 1.
Examples:
>>> C = 3 # num_classes
@@ -354,19 +355,19 @@ class BinaryFocalLossWithLogits(nn.Module):
alpha: Optional[float],
gamma: float = 2.0,
reduction: str = "none",
- pos_weight: Optional[Tensor] = None,
- weight: Optional[Tensor] = None,
+ pos_weight: Optional[torch.Tensor] = None,
+ weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
) -> None:
super().__init__()
self.alpha: Optional[float] = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.pos_weight: Optional[Tensor] = pos_weight
- self.weight: Optional[Tensor] = weight
+ self.pos_weight: Optional[torch.Tensor] = pos_weight
+ self.weight: Optional[torch.Tensor] = weight
self.ignore_index: Optional[int] = ignore_index
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return binary_focal_loss_with_logits(
pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight, self.ignore_index
)
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 011e76566..2c953dbd7 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -18,13 +18,12 @@
from __future__ import annotations
import torch
-from torch import Tensor
+from torch import nn
-from kornia.core import Module
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
-def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
+def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none") -> torch.Tensor:
r"""Criterion that computes the Geman-McClure loss [2].
According to [1], we compute the Geman-McClure loss as follows:
@@ -42,8 +41,8 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
[2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985
Args:
- img1: the predicted tensor with shape :math:`(*)`.
- img2: the target tensor with the same shape as img1.
+ img1: the predicted torch.tensor with shape :math:`(*)`.
+ img2: the target torch.tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -90,7 +89,7 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
return loss
-class GemanMcclureLoss(Module):
+class GemanMcclureLoss(nn.Module):
r"""Criterion that computes the Geman-McClure loss [2].
According to [1], we compute the Geman-McClure loss as follows:
@@ -115,8 +114,8 @@ class GemanMcclureLoss(Module):
summed.
Shape:
- - img1: the predicted tensor with shape :math:`(*)`.
- - img2: the target tensor with the same shape as img1.
+ - img1: the predicted torch.tensor with shape :math:`(*)`.
+ - img2: the target torch.tensor with the same shape as img1.
Example:
>>> criterion = GemanMcclureLoss(reduction="mean")
@@ -131,5 +130,5 @@ class GemanMcclureLoss(Module):
super().__init__()
self.reduction = reduction
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return geman_mcclure_loss(img1=img1, img2=img2, reduction=self.reduction)
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index 70a3c2cd6..e298ff17e 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -22,10 +22,8 @@ from typing import Callable
import torch
from torch import nn
-from kornia.core import Module, Tensor, as_tensor, stack, tensor, where, zeros_like
-
-class _HausdorffERLossBase(Module):
+class _HausdorffERLossBase(nn.Module):
"""Base class for binary Hausdorff loss based on morphological erosion.
This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided
@@ -45,8 +43,8 @@ class _HausdorffERLossBase(Module):
"""
- conv: Callable[..., Tensor]
- max_pool: Callable[..., Tensor]
+ conv: Callable[..., torch.Tensor]
+ max_pool: Callable[..., torch.Tensor]
def __init__(self, alpha: float = 2.0, k: int = 10, reduction: str = "mean") -> None:
super().__init__()
@@ -55,15 +53,15 @@ class _HausdorffERLossBase(Module):
self.reduction = reduction
self.register_buffer("kernel", self.get_kernel())
- def get_kernel(self) -> Tensor:
+ def get_kernel(self) -> torch.Tensor:
"""Get kernel for image morphology convolution."""
raise NotImplementedError
- def perform_erosion(self, pred: Tensor, target: Tensor) -> Tensor:
+ def perform_erosion(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
bound = (pred - target) ** 2
- kernel = as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)
- eroded = zeros_like(bound, device=pred.device, dtype=pred.dtype)
+ kernel = torch.as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)
+ eroded = torch.zeros_like(bound, device=pred.device, dtype=pred.dtype)
mask = torch.ones_like(bound, device=pred.device, dtype=torch.bool)
# Same padding, assuming kernel is odd and square (cube) shaped.
@@ -71,7 +69,7 @@ class _HausdorffERLossBase(Module):
for k in range(self.k):
# compute convolution with kernel
dilation = self.conv(bound, weight=kernel, padding=padding, groups=1)
- # apply soft thresholding at 0.5 and normalize
+ # apply soft thresholding at 0.5 and F.normalize
erosion = dilation - 0.5
erosion[erosion < 0] = 0
@@ -86,7 +84,7 @@ class _HausdorffERLossBase(Module):
# erosion[to_norm] = (erosion[to_norm] - erosion_min[to_norm]) / (
# erosion_max[to_norm] - erosion_min[to_norm])
_erosion_to_fill = (erosion - erosion_min) / (erosion_max - erosion_min)
- erosion = where(mask * _to_norm, _erosion_to_fill, erosion)
+ erosion = torch.where(mask * _to_norm, _erosion_to_fill, erosion)
# save erosion and add to loss
eroded = eroded + erosion * (k + 1) ** self.alpha
@@ -94,13 +92,13 @@ class _HausdorffERLossBase(Module):
return eroded
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Compute Hausdorff loss.
Args:
- pred: predicted tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
+ pred: predicted torch.tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.
+ target: target torch.tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.
Returns:
Estimated Hausdorff Loss.
@@ -115,14 +113,14 @@ class _HausdorffERLossBase(Module):
if pred.size(1) < target.max().item():
raise ValueError("Invalid target value.")
- out = stack(
+ out = torch.stack(
[
self.perform_erosion(
pred[:, i : i + 1],
- where(
+ torch.where(
target == i,
- tensor(1, device=target.device, dtype=target.dtype),
- tensor(0, device=target.device, dtype=target.dtype),
+ torch.tensor(1, device=target.device, dtype=target.dtype),
+ torch.tensor(0, device=target.device, dtype=target.dtype),
),
)
for i in range(pred.size(1))
@@ -181,19 +179,19 @@ class HausdorffERLoss(_HausdorffERLossBase):
conv = torch.conv2d
max_pool = nn.AdaptiveMaxPool2d(1)
- def get_kernel(self) -> Tensor:
+ def get_kernel(self) -> torch.Tensor:
"""Get kernel for image morphology convolution."""
- cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])
+ cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])
kernel = cross * 0.2
return kernel[None]
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Compute Hausdorff loss.
Args:
- pred: predicted tensor with a shape of :math:`(B, C, H, W)`.
+ pred: predicted torch.tensor with a shape of :math:`(B, C, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target tensor with a shape of :math:`(B, 1, H, W)`.
+ target: target torch.tensor with a shape of :math:`(B, 1, H, W)`.
Returns:
Estimated Hausdorff Loss.
@@ -249,23 +247,23 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
conv = torch.conv3d
max_pool = nn.AdaptiveMaxPool3d(1)
- def get_kernel(self) -> Tensor:
+ def get_kernel(self) -> torch.Tensor:
"""Get kernel for image morphology convolution."""
- cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])
- bound = tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])
+ cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])
+ bound = torch.tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])
# NOTE: The original repo claimed it shaped as (3, 1, 3, 3)
# which Jian suspect it is wrongly implemented.
# https://github.com/PatRyg99/HausdorffLoss/blob/9f580acd421af648e74b45d46555ccb7a876c27c/hausdorff_loss.py#L94
- kernel = stack([bound, cross, bound], 1) * (1 / 7)
+ kernel = torch.stack([bound, cross, bound], 1) * (1 / 7)
return kernel[None]
- def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Compute 3D Hausdorff loss.
Args:
- pred: predicted tensor with a shape of :math:`(B, C, D, H, W)`.
+ pred: predicted torch.tensor with a shape of :math:`(B, C, D, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target tensor with a shape of :math:`(B, 1, D, H, W)`.
+ target: target torch.tensor with a shape of :math:`(B, 1, D, H, W)`.
Returns:
Estimated Hausdorff Loss.
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index d2a45fe8a..e0bc74292 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -17,19 +17,21 @@
from __future__ import annotations
+import torch
+from torch import nn
+
from kornia import metrics
-from kornia.core import Module, Tensor
def ssim3d_loss(
- img1: Tensor,
- img2: Tensor,
+ img1: torch.Tensor,
+ img2: torch.Tensor,
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
reduction: str = "mean",
padding: str = "same",
-) -> Tensor:
+) -> torch.Tensor:
r"""Compute a loss based on the SSIM measurement.
The loss, or the Structural dissimilarity (DSSIM) is described as:
@@ -63,7 +65,7 @@ def ssim3d_loss(
"""
# compute the ssim map
- ssim_map: Tensor = metrics.ssim3d(img1, img2, window_size, max_val, eps, padding)
+ ssim_map: torch.Tensor = metrics.ssim3d(img1, img2, window_size, max_val, eps, padding)
# compute and reduce the loss
loss = 1.0 - ssim_map
@@ -80,7 +82,7 @@ def ssim3d_loss(
return loss
-class SSIM3DLoss(Module):
+class SSIM3DLoss(nn.Module):
r"""Create a criterion that computes a loss based on the SSIM measurement.
The loss, or the Structural dissimilarity (DSSIM) is described as:
@@ -123,5 +125,5 @@ class SSIM3DLoss(Module):
self.reduction: str = reduction
self.padding: str = padding
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return ssim3d_loss(img1, img2, self.window_size, self.max_val, self.eps, self.reduction, self.padding)
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 8655ccb4c..9e61784c7 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -17,11 +17,13 @@
from __future__ import annotations
-from kornia.core import Module, Tensor
+import torch
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
+def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:
r"""Compute Total Variation according to [1].
Args:
@@ -31,7 +33,7 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
in the output, ``'sum'``: the output will be summed.
Return:
- a tensor with shape :math:`(*,)`.
+ a torch.tensor with shape :math:`(*,)`.
Examples:
>>> total_variation(torch.ones(4, 4))
@@ -49,8 +51,8 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
"""
# TODO: here torchscript doesn't like KORNIA_CHECK_TYPE
- if not isinstance(img, Tensor):
- raise TypeError(f"Not a Tensor type. Got: {type(img)}")
+ if not isinstance(img, torch.Tensor):
+ raise TypeError(f"Not a torch.Tensor type. Got: {type(img)}")
KORNIA_CHECK_SHAPE(img, ["*", "H", "W"])
KORNIA_CHECK(reduction in ("mean", "sum"), f"Expected reduction to be one of 'mean'/'sum', but got '{reduction}'.")
@@ -78,7 +80,7 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
return res1 + res2
-class TotalVariation(Module):
+class TotalVariation(nn.Module):
r"""Compute the Total Variation according to [1].
Shape:
@@ -98,5 +100,5 @@ class TotalVariation(Module):
"""
- def forward(self, img: Tensor) -> Tensor:
+ def forward(self, img: torch.Tensor) -> torch.Tensor:
return total_variation(img)
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index cc84ba0d5..d24f949f1 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -17,13 +17,14 @@
from __future__ import annotations
-from torch import Tensor
+import torch
+from torch import nn
-from kornia.core import Module
+# from torch import Tensor (use torch.Tensor instead)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
-def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
+def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none") -> torch.Tensor:
r"""Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.
According to [1], we compute the Welsch loss as follows:
@@ -42,8 +43,8 @@ def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
[3] https://link.springer.com/article/10.1007/BF00054839
Args:
- img1: the predicted tensor with shape :math:`(*)`.
- img2: the target tensor with the same shape as img1.
+ img1: the predicted torch.tensor with shape :math:`(*)`.
+ img2: the target torch.tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -86,7 +87,7 @@ def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
return loss
-class WelschLoss(Module):
+class WelschLoss(nn.Module):
r"""Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.
According to [1], we compute the Welsch loss as follows:
@@ -112,8 +113,8 @@ class WelschLoss(Module):
summed.
Shape:
- - img1: the predicted tensor with shape :math:`(*)`.
- - img2: the target tensor with the same shape as img1.
+ - img1: the predicted torch.tensor with shape :math:`(*)`.
+ - img2: the target torch.tensor with the same shape as img1.
Example:
>>> criterion = WelschLoss(reduction="mean")
@@ -128,5 +129,5 @@ class WelschLoss(Module):
super().__init__()
self.reduction = reduction
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return welsch_loss(img1=img1, img2=img2, reduction=self.reduction)
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 76a13608d..89456977b 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -17,15 +17,15 @@
from typing import List, Tuple
-from kornia.core import Tensor
+import torch
-def accuracy(pred: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
+def accuracy(pred: torch.Tensor, target: torch.Tensor, topk: Tuple[int, ...] = (1,)) -> List[torch.Tensor]:
"""Compute the accuracy over the k top predictions for the specified values of k.
Args:
- pred: the input tensor with the logits to evaluate.
- target: the tensor containing the ground truth.
+ pred: the input torch.tensor with the logits to evaluate.
+ target: the torch.tensor containing the ground truth.
topk: the expected topk ranking.
Example:
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index bfb94edef..3c9791182 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -17,7 +17,7 @@
from typing import Union
-from kornia.core import Tensor
+import torch
class AverageMeter:
@@ -26,15 +26,15 @@ class AverageMeter:
Example:
>>> stats = AverageMeter()
>>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy
- >>> stats.update(acc1, n=1) # where n is batch size usually
+ >>> stats.update(acc1, n=1) # torch.where n is batch size usually
>>> round(stats.avg, 2)
0.99
"""
- val: Union[float, bool, Tensor]
- _avg: Union[float, Tensor]
- sum: Union[float, Tensor]
+ val: Union[float, bool, torch.Tensor]
+ _avg: Union[float, torch.Tensor]
+ sum: Union[float, torch.Tensor]
count: int
def __init__(self) -> None:
@@ -46,7 +46,7 @@ class AverageMeter:
self.sum = 0
self.count = 0
- def update(self, val: Union[float, bool, Tensor], n: int = 1) -> None:
+ def update(self, val: Union[float, bool, torch.Tensor], n: int = 1) -> None:
self.val = val
self.sum += val * n
self.count += n
@@ -54,6 +54,6 @@ class AverageMeter:
@property
def avg(self) -> float:
- if isinstance(self._avg, Tensor):
+ if isinstance(self._avg, torch.Tensor):
return float(self._avg.item())
return self._avg
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index 405b2452a..1ac4956a9 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -19,31 +19,29 @@ from typing import Dict, List, Tuple
import torch
-from kornia.core import Tensor, concatenate, tensor, zeros
-
from .mean_iou import mean_iou_bbox
def mean_average_precision(
- pred_boxes: List[Tensor],
- pred_labels: List[Tensor],
- pred_scores: List[Tensor],
- gt_boxes: List[Tensor],
- gt_labels: List[Tensor],
+ pred_boxes: List[torch.Tensor],
+ pred_labels: List[torch.Tensor],
+ pred_scores: List[torch.Tensor],
+ gt_boxes: List[torch.Tensor],
+ gt_labels: List[torch.Tensor],
n_classes: int,
threshold: float = 0.5,
-) -> Tuple[Tensor, Dict[int, float]]:
+) -> Tuple[torch.Tensor, Dict[int, float]]:
"""Calculate the Mean Average Precision (mAP) of detected objects.
Code altered from https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/utils.py#L271.
Background class (0 index) is excluded.
Args:
- pred_boxes: a tensor list of predicted bounding boxes.
- pred_labels: a tensor list of predicted labels.
- pred_scores: a tensor list of predicted labels' scores.
- gt_boxes: a tensor list of ground truth bounding boxes.
- gt_labels: a tensor list of ground truth labels.
+ pred_boxes: a torch.tensor list of predicted bounding boxes.
+ pred_labels: a torch.tensor list of predicted labels.
+ pred_scores: a torch.tensor list of predicted labels' scores.
+ gt_boxes: a torch.tensor list of ground truth bounding boxes.
+ gt_labels: a torch.tensor list of ground truth labels.
n_classes: the number of classes.
threshold: count as a positive if the overlap is greater than the threshold.
@@ -61,32 +59,34 @@ def mean_average_precision(
if not len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels):
raise AssertionError
- # Store all (true) objects in a single continuous tensor while keeping track of the image it is from
+ # Store all (true) objects in a single continuous torch.tensor while keeping track of the image it is from
gt_images = []
for i, labels in enumerate(gt_labels):
gt_images.extend([i] * labels.size(0))
# (n_objects), n_objects is the total no. of objects across all images
- _gt_boxes = concatenate(gt_boxes, 0) # (n_objects, 4)
- _gt_labels = concatenate(gt_labels, 0) # (n_objects)
- _gt_images = tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
+ _gt_boxes = torch.cat(gt_boxes, 0) # (n_objects, 4)
+ _gt_labels = torch.cat(gt_labels, 0) # (n_objects)
+ _gt_images = torch.tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
if not _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0):
raise AssertionError
- # Store all detections in a single continuous tensor while keeping track of the image it is from
+ # Store all detections in a single continuous torch.tensor while keeping track of the image it is from
pred_images = []
for i, labels in enumerate(pred_labels):
pred_images.extend([i] * labels.size(0))
- _pred_boxes = concatenate(pred_boxes, 0) # (n_detections, 4)
- _pred_labels = concatenate(pred_labels, 0) # (n_detections)
- _pred_scores = concatenate(pred_scores, 0) # (n_detections)
- _pred_images = tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
+ _pred_boxes = torch.cat(pred_boxes, 0) # (n_detections, 4)
+ _pred_labels = torch.cat(pred_labels, 0) # (n_detections)
+ _pred_scores = torch.cat(pred_scores, 0) # (n_detections)
+ _pred_images = torch.tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
if not _pred_images.size(0) == _pred_boxes.size(0) == _pred_labels.size(0) == _pred_scores.size(0):
raise AssertionError
# Calculate APs for each class (except background)
- average_precisions = zeros((n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype) # (n_classes - 1)
+ average_precisions = torch.zeros(
+ (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype
+ ) # (n_classes - 1)
for c in range(1, n_classes):
# Extract only objects with this class
gt_class_images = _gt_images[_gt_labels == c] # (n_class_objects)
@@ -94,7 +94,9 @@ def mean_average_precision(
# Keep track of which true objects with this class have already been 'detected'
# (n_class_objects)
- gt_class_boxes_detected = zeros((gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device)
+ gt_class_boxes_detected = torch.zeros(
+ (gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device
+ )
# Extract only detections with this class
pred_class_images = _pred_images[_pred_labels == c] # (n_class_detections)
@@ -110,10 +112,10 @@ def mean_average_precision(
pred_class_boxes = pred_class_boxes[sort_ind] # (n_class_detections, 4)
# In the order of decreasing scores, check if true or false positive
- gt_positives = zeros(
+ gt_positives = torch.zeros(
(n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
) # (n_class_detections)
- false_positives = zeros(
+ false_positives = torch.zeros(
(n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
) # (n_class_detections)
for d in range(n_class_detections):
@@ -133,7 +135,7 @@ def mean_average_precision(
# 'ind' is the index of the object in these image-level tensors 'object_boxes', 'object_difficulties'
# In the original class-level tensors 'gt_class_boxes', etc., 'ind' corresponds to object with index...
- original_ind = tensor(
+ original_ind = torch.tensor(
range(gt_class_boxes.size(0)), device=gt_class_boxes_detected.device, dtype=torch.long
)[gt_class_images == this_image][ind]
# We need 'original_ind' to update 'gt_class_boxes_detected'
@@ -161,7 +163,7 @@ def mean_average_precision(
# Find the mean of the maximum of the precisions corresponding to recalls above the threshold 't'
recall_thresholds = torch.arange(start=0, end=1.1, step=0.1).tolist() # (11)
- precisions = zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
+ precisions = torch.zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
for i, t in enumerate(recall_thresholds):
recalls_above_t = cumul_recall >= t
if recalls_above_t.any():
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index 23e98674c..df5ed9d61 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -17,15 +17,18 @@
from typing import List
-from kornia.core import Module, Tensor, pad
+import torch
+import torch.nn.functional as F
+from torch import nn
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter3d, get_gaussian_kernel3d
from kornia.filters.filter import _compute_padding
-def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:
+def _crop(img: torch.Tensor, cropping_shape: List[int]) -> torch.Tensor:
"""Crop out the part of "valid" convolution area."""
- return pad(
+ return F.pad(
img,
(
-cropping_shape[4],
@@ -39,8 +42,13 @@ def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:
def ssim3d(
- img1: Tensor, img2: Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same"
-) -> Tensor:
+ img1: torch.Tensor,
+ img2: torch.Tensor,
+ window_size: int,
+ max_val: float = 1.0,
+ eps: float = 1e-12,
+ padding: str = "same",
+) -> torch.Tensor:
r"""Compute the Structural Similarity (SSIM) index map between two images.
Measures the (SSIM) index between each element in the input `x` and target `y`.
@@ -52,7 +60,7 @@ def ssim3d(
\text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}
{(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}
- where:
+ torch.where:
- :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to
stabilize the division with weak denominator.
- :math:`L` is the dynamic range of the pixel-values (typically this is
@@ -86,15 +94,15 @@ def ssim3d(
raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")
# prepare kernel
- kernel: Tensor = get_gaussian_kernel3d((window_size, window_size, window_size), (1.5, 1.5, 1.5))
+ kernel: torch.Tensor = get_gaussian_kernel3d((window_size, window_size, window_size), (1.5, 1.5, 1.5))
# compute coefficients
C1: float = (0.01 * max_val) ** 2
C2: float = (0.03 * max_val) ** 2
# compute local mean per channel
- mu1: Tensor = filter3d(img1, kernel)
- mu2: Tensor = filter3d(img2, kernel)
+ mu1: torch.Tensor = filter3d(img1, kernel)
+ mu2: torch.Tensor = filter3d(img2, kernel)
cropping_shape: List[int] = []
if padding == "valid":
@@ -126,13 +134,13 @@ def ssim3d(
sigma12 = mu_img1_img2 - mu1_mu2
# compute the similarity index map
- num: Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)
- den: Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
+ num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)
+ den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
return num / (den + eps)
-class SSIM3D(Module):
+class SSIM3D(nn.Module):
r"""Create a module that computes the Structural Similarity (SSIM) index between two 3D images.
Measures the (SSIM) index between each element in the input `x` and target `y`.
@@ -144,7 +152,7 @@ class SSIM3D(Module):
\text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}
{(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}
- where:
+ torch.where:
- :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to
stabilize the division with weak denominator.
- :math:`L` is the dynamic range of the pixel-values (typically this is
@@ -177,5 +185,5 @@ class SSIM3D(Module):
self.eps = eps
self.padding = padding
- def forward(self, img1: Tensor, img2: Tensor) -> Tensor:
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
return ssim3d(img1, img2, self.window_size, self.max_val, self.eps, self.padding)
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 0e5a15adb..9f6d49587 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -39,7 +39,7 @@ class HFONNXComunnityModelLoader:
Args:
model_name: The name of the model to load.
model_type: The type of the model to load.
- cache_dir: The directory where models are cached locally.
+ cache_dir: The directory torch.where models are cached locally.
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
with_data: Whether to download the model weights such as `model.onnx_data`.
diff --git a/kornia/models/_hf_models/preprocessor.py b/kornia/models/_hf_models/preprocessor.py
index c0af70748..63351a30a 100644
--- a/kornia/models/_hf_models/preprocessor.py
+++ b/kornia/models/_hf_models/preprocessor.py
@@ -63,7 +63,7 @@ class DPTImageProcessor(PreprocessingLoader):
preproc_list.append(PreprocessingLoader.rescale(rescale_factor=json_data["rescale_factor"] * 255))
if json_data["do_normalize"]:
preproc_list.append(
- PreprocessingLoader.normalize(
+ PreprocessingLoader.F.normalize(
mean=torch.tensor([json_data["image_mean"]]), std=torch.tensor([json_data["image_std"]])
)
)
diff --git a/kornia/models/rt_detr/post_processor.py b/kornia/models/rt_detr/post_processor.py
index 969544432..04d397cb7 100644
--- a/kornia/models/rt_detr/post_processor.py
+++ b/kornia/models/rt_detr/post_processor.py
@@ -35,7 +35,7 @@ def mod(a: torch.Tensor, b: int) -> torch.Tensor:
implementation uses `a % b` (equivalent to `torch.remainder(a, b)`).
Args:
- a (torch.Tensor): Dividend tensor (any numeric dtype).
+ a (torch.Tensor): Dividend torch.tensor(any numeric dtype).
b (int): Divisor (must be non-zero).
Returns:
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
index 9cee3d41e..34eaad73e 100644
--- a/kornia/sensors/camera/camera_model.py
+++ b/kornia/sensors/camera/camera_model.py
@@ -21,7 +21,8 @@ from __future__ import annotations
from enum import Enum
from typing import Any, Union
-from kornia.core import Tensor, stack, zeros_like
+import torch
+
from kornia.geometry.vector import Vector2, Vector3
from kornia.image import ImageSize
from kornia.sensors.camera.distortion_model import AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform
@@ -35,7 +36,9 @@ class CameraModelType(Enum):
ORTHOGRAPHIC = 3
-def get_model_from_type(model_type: CameraModelType, image_size: ImageSize, params: Tensor) -> CameraModelVariants:
+def get_model_from_type(
+ model_type: CameraModelType, image_size: ImageSize, params: torch.Tensor
+) -> CameraModelVariants:
"""Get camera model from model type."""
if model_type == CameraModelType.PINHOLE:
return PinholeModel(image_size, params)
@@ -73,7 +76,11 @@ class CameraModelBase:
"""
def __init__(
- self, distortion: CameraDistortionType, projection: CameraProjectionType, image_size: ImageSize, params: Tensor
+ self,
+ distortion: CameraDistortionType,
+ projection: CameraProjectionType,
+ image_size: ImageSize,
+ params: torch.Tensor,
) -> None:
"""Construct CameraModelBase class.
@@ -100,45 +107,45 @@ class CameraModelBase:
return self._image_size
@property
- def height(self) -> int | Tensor:
+ def height(self) -> int | torch.Tensor:
"""Returns the height of the image."""
return self._height
@property
- def width(self) -> int | Tensor:
+ def width(self) -> int | torch.Tensor:
"""Returns the width of the image."""
return self._width
@property
- def params(self) -> Tensor:
+ def params(self) -> torch.Tensor:
"""Returns the camera parameters."""
return self._params
@property
- def fx(self) -> Tensor:
+ def fx(self) -> torch.Tensor:
"""Returns the focal length in x direction."""
return self._params[..., 0]
@property
- def fy(self) -> Tensor:
+ def fy(self) -> torch.Tensor:
"""Returns the focal length in y direction."""
return self._params[..., 1]
@property
- def cx(self) -> Tensor:
+ def cx(self) -> torch.Tensor:
"""Returns the principal point in x direction."""
return self._params[..., 2]
@property
- def cy(self) -> Tensor:
+ def cy(self) -> torch.Tensor:
"""Returns the principal point in y direction."""
return self._params[..., 3]
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
"""Return the camera matrix."""
raise NotImplementedError
- def K(self) -> Tensor:
+ def K(self) -> torch.Tensor:
"""Return the camera matrix."""
return self.matrix()
@@ -161,7 +168,7 @@ class CameraModelBase:
"""
return self.distortion.distort(self.params, self.projection.project(points))
- def unproject(self, points: Vector2, depth: Tensor) -> Vector3:
+ def unproject(self, points: Vector2, depth: torch.Tensor) -> Vector3:
"""Unprojects 2D points from camera plane to 3D.
Args:
@@ -199,7 +206,7 @@ class PinholeModel(CameraModelBase):
"""
- def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:
"""Construct PinholeModel class.
Args:
@@ -211,7 +218,7 @@ class PinholeModel(CameraModelBase):
raise ValueError("params must be of shape (B, 4) for PINHOLE Camera")
super().__init__(AffineTransform(), Z1Projection(), image_size, params)
- def matrix(self) -> Tensor:
+ def matrix(self) -> torch.Tensor:
r"""Return the camera matrix.
The matrix is of the form:
@@ -229,15 +236,15 @@ class PinholeModel(CameraModelBase):
[0., 0., 1.]])
"""
- z = zeros_like(self.fx)
- row1 = stack((self.fx, z, self.cx), -1)
- row2 = stack((z, self.fy, self.cy), -1)
- row3 = stack((z, z, z), -1)
- K = stack((row1, row2, row3), -2)
+ z = torch.zeros_like(self.fx)
+ row1 = torch.stack((self.fx, z, self.cx), -1)
+ row2 = torch.stack((z, self.fy, self.cy), -1)
+ row3 = torch.stack((z, z, z), -1)
+ K = torch.stack((row1, row2, row3), -2)
K[..., -1, -1] = 1.0
return K
- def scale(self, scale_factor: Tensor) -> PinholeModel:
+ def scale(self, scale_factor: torch.Tensor) -> PinholeModel:
"""Scales the camera model by a scale factor.
Args:
@@ -257,7 +264,7 @@ class PinholeModel(CameraModelBase):
fy = self.fy * scale_factor
cx = self.cx * scale_factor
cy = self.cy * scale_factor
- params = stack((fx, fy, cx, cy), -1)
+ params = torch.stack((fx, fy, cx, cy), -1)
image_size = ImageSize(self.image_size.height * scale_factor, self.image_size.width * scale_factor)
return PinholeModel(image_size, params)
@@ -265,7 +272,7 @@ class PinholeModel(CameraModelBase):
class BrownConradyModel(CameraModelBase):
"""Brown Conrady Camera Model."""
- def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:
"""Construct BrownConradyModel class.
Args:
@@ -282,7 +289,7 @@ class BrownConradyModel(CameraModelBase):
class KannalaBrandtK3(CameraModelBase):
"""Kannala Brandt K3 Camera Model."""
- def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:
"""Construct KannalaBrandtK3 class.
Args:
@@ -298,7 +305,7 @@ class KannalaBrandtK3(CameraModelBase):
class Orthographic(CameraModelBase):
"""Orthographic Camera Model."""
- def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:
"""Construct Orthographic class.
Args:
@@ -333,7 +340,7 @@ class CameraModel:
"""
- def __init__(self, image_size: ImageSize, model_type: CameraModelType, params: Tensor) -> None:
+ def __init__(self, image_size: ImageSize, model_type: CameraModelType, params: torch.Tensor) -> None:
"""Construct CameraModel class.
Args:
diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.py
index 71cfec081..ef9622e1f 100644
--- a/kornia/sensors/camera/distortion_model.py
+++ b/kornia/sensors/camera/distortion_model.py
@@ -15,23 +15,25 @@
# limitations under the License.
#
-from kornia.core import Tensor
+
+import torch
+
from kornia.geometry.vector import Vector2
class AffineTransform:
- def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
"""Distort one or more Vector2 points using the affine transform.
Args:
- params: Tensor representing the affine transform parameters.
+ params: torch.Tensor representing the affine transform parameters.
points: Vector2 representing the points to distort.
Returns:
Vector2 representing the distorted points.
Example:
- >>> params = Tensor([1., 2., 3., 4.])
+ >>> params = torch.Tensor([1., 2., 3., 4.])
>>> points = Vector2.from_coords(1., 2.)
>>> AffineTransform().distort(params, points)
x: 4.0
@@ -43,18 +45,18 @@ class AffineTransform:
v = points.y * fy + cy
return Vector2.from_coords(u, v)
- def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:
"""Undistort one or more Vector2 points using the affine transform.
Args:
- params: Tensor representing the affine transform parameters.
+ params: torch.Tensor representing the affine transform parameters.
points: Vector2 representing the points to undistort.
Returns:
Vector2 representing the undistorted points.
Example:
- >>> params = Tensor([1., 2., 3., 4.])
+ >>> params = torch.Tensor([1., 2., 3., 4.])
>>> points = Vector2.from_coords(1., 2.)
>>> AffineTransform().undistort(params, points)
x: -2.0
@@ -68,16 +70,16 @@ class AffineTransform:
class BrownConradyTransform:
- def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
- def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
class KannalaBrandtK3Transform:
- def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
- def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
index 44fd2eeec..94eae1f97 100644
--- a/kornia/sensors/camera/projection_model.py
+++ b/kornia/sensors/camera/projection_model.py
@@ -17,7 +17,8 @@
from __future__ import annotations
-from kornia.core import Tensor
+import torch
+
from kornia.geometry.vector import Vector2, Vector3
@@ -41,18 +42,18 @@ class Z1Projection:
xy = points.data[..., :2]
z = points.z
if len(z.shape):
- uv = (xy.mT @ z.diag().inverse()).mT
+ uv = (xy.mT @ torch.diag(z).inverse()).mT
else:
# For scalar z, xy is 1-D, so no transpose needed
uv = xy * 1 / z
return Vector2(uv)
- def unproject(self, points: Vector2, depth: Tensor | float) -> Vector3:
+ def unproject(self, points: Vector2, depth: torch.Tensor | float) -> Vector3:
"""Unproject one or more Vector2 from the canonical z=1 plane into the camera frame.
Args:
points: Vector2 representing the points to unproject.
- depth: Tensor representing the depth of the points to unproject.
+ depth: torch.Tensor representing the depth of the points to unproject.
Returns:
Vector3 representing the unprojected points.
@@ -66,7 +67,7 @@ class Z1Projection:
"""
if isinstance(depth, (float, int)):
- depth = Tensor([depth])
+ depth = torch.Tensor([depth])
return Vector3.from_coords(points.x * depth, points.y * depth, depth)
@@ -74,5 +75,5 @@ class OrthographicProjection:
def project(self, points: Vector3) -> Vector2:
raise NotImplementedError
- def unproject(self, points: Vector2, depth: Tensor) -> Vector3:
+ def unproject(self, points: Vector2, depth: torch.Tensor) -> Vector3:
raise NotImplementedError
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 894f5fd7c..84a4e5f48 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -18,8 +18,8 @@
from typing import Dict, Optional, Tuple
import torch
+from torch import nn
-from kornia.core import Module, Tensor
from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR
from kornia.feature.integrated import LocalFeature
from kornia.geometry.linalg import transform_points
@@ -27,7 +27,7 @@ from kornia.geometry.ransac import RANSAC
from kornia.geometry.transform import warp_perspective
-class HomographyTracker(Module):
+class HomographyTracker(nn.Module):
r"""Perform local-feature-based tracking of the target planar object in the sequence of the frames.
Args:
@@ -43,8 +43,8 @@ class HomographyTracker(Module):
def __init__(
self,
initial_matcher: Optional[LocalFeature] = None,
- fast_matcher: Optional[Module] = None,
- ransac: Optional[Module] = None,
+ fast_matcher: Optional[nn.Module] = None,
+ ransac: Optional[nn.Module] = None,
minimum_inliers_num: int = 30,
) -> None:
super().__init__()
@@ -56,10 +56,10 @@ class HomographyTracker(Module):
self.minimum_inliers_num = minimum_inliers_num
# placeholders
- self.target: Tensor
- self.target_initial_representation: Dict[str, Tensor] = {}
- self.target_fast_representation: Dict[str, Tensor] = {}
- self.previous_homography: Optional[Tensor] = None
+ self.target: torch.Tensor
+ self.target_initial_representation: Dict[str, torch.Tensor] = {}
+ self.target_fast_representation: Dict[str, torch.Tensor] = {}
+ self.previous_homography: Optional[torch.Tensor] = None
self.inliers_num: int = 0
self.keypoints0_num: int = 0
@@ -76,34 +76,34 @@ class HomographyTracker(Module):
return self.target.dtype
@torch.no_grad()
- def set_target(self, target: Tensor) -> None:
+ def set_target(self, target: torch.Tensor) -> None:
self.target = target
self.target_initial_representation = {}
self.target_fast_representation = {}
if hasattr(self.initial_matcher, "extract_features") and isinstance(
- self.initial_matcher.extract_features, Module
+ self.initial_matcher.extract_features, nn.Module
):
self.target_initial_representation = self.initial_matcher.extract_features(target)
- if hasattr(self.fast_matcher, "extract_features") and isinstance(self.fast_matcher.extract_features, Module):
+ if hasattr(self.fast_matcher, "extract_features") and isinstance(self.fast_matcher.extract_features, nn.Module):
self.target_fast_representation = self.fast_matcher.extract_features(target)
def reset_tracking(self) -> None:
self.previous_homography = None
- def no_match(self) -> Tuple[Tensor, bool]:
+ def no_match(self) -> Tuple[torch.Tensor, bool]:
self.inliers_num = 0
self.keypoints0_num = 0
self.keypoints1_num = 0
return torch.empty(3, 3, device=self.device, dtype=self.dtype), False
- def match_initial(self, x: Tensor) -> Tuple[Tensor, bool]:
+ def match_initial(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
"""Match the frame `x` with initial_matcher and verified with ransac."""
- input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": x}
+ input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": x}
for k, v in self.target_initial_representation.items():
input_dict[f"{k}0"] = v
- match_dict: Dict[str, Tensor] = self.initial_matcher(input_dict)
+ match_dict: Dict[str, torch.Tensor] = self.initial_matcher(input_dict)
keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]
keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]
@@ -122,7 +122,7 @@ class HomographyTracker(Module):
return H, True
- def track_next_frame(self, x: Tensor) -> Tuple[Tensor, bool]:
+ def track_next_frame(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
"""Prewarp the frame `x` according to the previous frame homography.
Matched with fast_matcher verified with ransac.
@@ -135,7 +135,7 @@ class HomographyTracker(Module):
Hinv = torch.inverse(Hwarp)
h, w = self.target.shape[2:]
frame_warped = warp_perspective(x, Hinv, (h, w))
- input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": frame_warped}
+ input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": frame_warped}
for k, v in self.target_fast_representation.items():
input_dict[f"{k}0"] = v
@@ -161,7 +161,7 @@ class HomographyTracker(Module):
self.previous_homography = H.clone()
return H, True
- def forward(self, x: Tensor) -> Tuple[Tensor, bool]:
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
if self.previous_homography is not None:
return self.track_next_frame(x)
return self.match_initial(x)
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index 81ee557ea..bb1d91217 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -19,7 +19,6 @@ from typing import Optional
import torch
-from kornia.core import Tensor, stack
from kornia.utils._compat import torch_meshgrid
@@ -29,7 +28,7 @@ def create_meshgrid(
normalized_coordinates: bool = True,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
"""Generate a coordinate grid for an image.
When the flag ``normalized_coordinates`` is set to True, the grid is
@@ -64,8 +63,8 @@ def create_meshgrid(
[1., 1.]]]])
"""
- xs: Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys: Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
+ xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
+ ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
# Fix TracerWarning
# Note: normalize_pixel_coordinates still gots TracerWarning since new width and height
# tensors will be generated.
@@ -81,9 +80,9 @@ def create_meshgrid(
# TODO: torchscript doesn't like `torch_version_ge`
# if torch_version_ge(1, 13, 0):
# x, y = torch_meshgrid([xs, ys], indexing="xy")
- # return stack([x, y], -1).unsqueeze(0) # 1xHxWx2
+ # return torch.stack([x, y], -1).unsqueeze(0) # 1xHxWx2
# TODO: remove after we drop support of old versions
- base_grid: Tensor = stack(torch_meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2
+ base_grid: torch.Tensor = torch.stack(torch_meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2
return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2
@@ -94,7 +93,7 @@ def create_meshgrid3d(
normalized_coordinates: bool = True,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> Tensor:
+) -> torch.Tensor:
"""Generate a coordinate grid for an image.
When the flag ``normalized_coordinates`` is set to True, the grid is
@@ -115,14 +114,14 @@ def create_meshgrid3d(
grid tensor with shape :math:`(1, D, H, W, 3)`.
"""
- xs: Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys: Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
- zs: Tensor = torch.linspace(0, depth - 1, depth, device=device, dtype=dtype)
+ xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
+ ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
+ zs: torch.Tensor = torch.linspace(0, depth - 1, depth, device=device, dtype=dtype)
# Fix TracerWarning
if normalized_coordinates:
xs = (xs / (width - 1) - 0.5) * 2
ys = (ys / (height - 1) - 0.5) * 2
zs = (zs / (depth - 1) - 0.5) * 2
# generate grid by stacking coordinates
- base_grid = stack(torch_meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3
+ base_grid = torch.stack(torch_meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3
return base_grid.permute(0, 2, 1, 3).unsqueeze(0) # 1xDxHxWx3
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 78f49fb0a..1efed98c2 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -27,7 +27,6 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Ty
import torch
from torch.linalg import inv_ex
-from kornia.core import Tensor
from kornia.utils._compat import torch_version_ge
@@ -38,7 +37,7 @@ def xla_is_available() -> bool:
return False
-def is_mps_tensor_safe(x: Tensor) -> bool:
+def is_mps_tensor_safe(x: torch.Tensor) -> bool:
"""Return whether tensor is on MPS device."""
return "mps" in str(x.device)
@@ -87,14 +86,14 @@ def get_cuda_or_mps_device_if_available() -> torch.device:
@overload
-def map_location_to_cpu(storage: Tensor, location: str) -> Tensor: ...
+def map_location_to_cpu(storage: torch.Tensor, location: str) -> torch.Tensor: ...
@overload
def map_location_to_cpu(storage: str) -> str: ...
-def map_location_to_cpu(storage: Union[str, Tensor], *args: Any, **kwargs: Any) -> Union[str, Tensor]:
+def map_location_to_cpu(storage: Union[str, torch.Tensor], *args: Any, **kwargs: Any) -> Union[str, torch.Tensor]:
"""Map location of device to CPU, util for loading things from HUB."""
return storage
@@ -136,7 +135,7 @@ def deprecated(
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
- """Check if all the input are in the same device (only if when they are Tensor).
+ """Check if all the input are in the same device (only if when they are torch.Tensor).
If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
@@ -147,7 +146,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
- if not isinstance(tensor, (Tensor,)):
+ if not isinstance(tensor, (torch.Tensor,)):
continue
_device = tensor.device
_dtype = tensor.dtype
@@ -167,35 +166,35 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
return (device, dtype)
-def _torch_inverse_cast(input: Tensor) -> Tensor:
+def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
"""Make torch.inverse work with other than fp32/64.
The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, Tensor):
- raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
return torch.linalg.inv(input.to(dtype)).to(input.dtype)
-def _torch_histc_cast(input: Tensor, bins: int, min: Union[float, bool], max: Union[float, bool]) -> Tensor:
+def _torch_histc_cast(input: torch.Tensor, bins: int, min: Union[float, bool], max: Union[float, bool]) -> torch.Tensor:
"""Make torch.histc work with other than fp32/64.
The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, Tensor):
- raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)
-def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
+def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Make torch.svd work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
@@ -218,7 +217,7 @@ def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))
-def _torch_linalg_svdvals(input: Tensor) -> Tensor:
+def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
"""Make torch.linalg.svdvals work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
@@ -227,15 +226,15 @@ def _torch_linalg_svdvals(input: Tensor) -> Tensor:
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- if not isinstance(input, Tensor):
- raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
if TYPE_CHECKING:
# TODO: remove this branch when kornia relies on torch >= 1.10
- out: Tensor
+ out: torch.Tensor
elif torch_version_ge(1, 10):
out = torch.linalg.svdvals(input.to(dtype))
else:
@@ -244,8 +243,8 @@ def _torch_linalg_svdvals(input: Tensor) -> Tensor:
return out.to(input.dtype)
-# TODO: return only `Tensor` and review all the calls to adjust
-def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
+# TODO: return only `torch.Tensor` and review all the calls to adjust
+def _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
"""Make torch.solve work with other than fp32/64.
For stable operation, the input matrices should be cast to fp64, and the output will
@@ -262,7 +261,7 @@ def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
return out.to(A.dtype)
-def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
+def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Solves the system of equations.
Avoids crashing because of singular matrix input and outputs the mask of valid solution.
@@ -272,24 +271,24 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning, stacklevel=1)
return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
- if not isinstance(B, Tensor):
- raise AssertionError(f"B must be Tensor. Got: {type(B)}.")
+ if not isinstance(B, torch.Tensor):
+ raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")
dtype: torch.dtype = B.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
if TYPE_CHECKING:
# TODO: remove this branch when kornia relies on torch >= 1.13
- A_LU: Tensor
- pivots: Tensor
- info: Tensor
+ A_LU: torch.Tensor
+ pivots: torch.Tensor
+ info: torch.Tensor
elif torch_version_ge(1, 13):
A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
else:
# TODO: remove this branch when kornia relies on torch >= 1.13
A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)
- valid_mask: Tensor = info == 0
+ valid_mask: torch.Tensor = info == 0
n_dim_B = len(B.shape)
n_dim_A = len(A.shape)
if n_dim_A - n_dim_B == 1:
@@ -297,7 +296,7 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
if TYPE_CHECKING:
# TODO: remove this branch when kornia relies on torch >= 1.13
- X: Tensor
+ X: torch.Tensor
elif torch_version_ge(1, 13):
X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
else:
@@ -307,13 +306,13 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
-def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:
+def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Perform inverse.
Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.
"""
- if not isinstance(A, Tensor):
- raise AssertionError(f"A must be Tensor. Got: {type(A)}.")
+ if not isinstance(A, torch.Tensor):
+ raise AssertionError(f"A must be torch.Tensor. Got: {type(A)}.")
dtype_original = A.dtype
if dtype_original not in (torch.float32, torch.float64):
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 49c22860e..f58863c38 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -22,10 +22,8 @@ import torch
from torch import nn
from torch.nn import functional as F
-from kornia.core import Tensor
-
-def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor:
+def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
"""Convert a numpy image to a PyTorch 4d tensor image.
Args:
@@ -56,7 +54,7 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor:
raise ValueError("Input size must be a two, three or four dimensional array")
input_shape = image.shape
- tensor: Tensor = torch.from_numpy(image)
+ tensor: torch.Tensor = torch.from_numpy(image)
if len(input_shape) == 2:
# (H, W) -> (1, H, W)
@@ -74,7 +72,7 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor:
return tensor.unsqueeze(0) if not keepdim else tensor
-def image_list_to_tensor(images: List[Any]) -> Tensor:
+def image_list_to_tensor(images: List[Any]) -> torch.Tensor:
"""Convert a list of numpy images to a PyTorch 4d tensor image.
Args:
@@ -109,7 +107,7 @@ def image_list_to_tensor(images: List[Any]) -> Tensor:
return torch.stack(images_t, dim=0).permute(0, 3, 1, 2)
-def _to_bchw(tensor: Tensor) -> Tensor:
+def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:
"""Convert a PyTorch tensor image to BCHW format.
Args:
@@ -119,8 +117,8 @@ def _to_bchw(tensor: Tensor) -> Tensor:
input tensor of the form :math:`(B, C, H, W)`.
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) < 2:
raise ValueError(f"Input size must be a two, three or four dimensional tensor. Got {tensor.shape}")
@@ -137,7 +135,7 @@ def _to_bchw(tensor: Tensor) -> Tensor:
return tensor
-def _to_bcdhw(tensor: Tensor) -> Tensor:
+def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
"""Convert a PyTorch tensor image to BCDHW format.
Args:
@@ -147,8 +145,8 @@ def _to_bcdhw(tensor: Tensor) -> Tensor:
input tensor of the form :math:`(B, C, D, H, W)`.
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) < 3:
raise ValueError(f"Input size must be a three, four or five dimensional tensor. Got {tensor.shape}")
@@ -165,7 +163,7 @@ def _to_bcdhw(tensor: Tensor) -> Tensor:
return tensor
-def tensor_to_image(tensor: Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
+def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
"""Convert a PyTorch tensor image to a numpy image.
In case the tensor is in the GPU, it will be copied back to CPU.
@@ -190,8 +188,8 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False, force_contiguous: boo
(4, 4, 3)
"""
- if not isinstance(tensor, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) > 4 or len(tensor.shape) < 2:
raise ValueError("Input size must be a two, three or four dimensional tensor")
@@ -238,11 +236,11 @@ class ImageToTensor(nn.Module):
super().__init__()
self.keepdim = keepdim
- def forward(self, x: Any) -> Tensor:
+ def forward(self, x: Any) -> torch.Tensor:
return image_to_tensor(x, keepdim=self.keepdim)
-def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) -> Tensor:
+def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int = 2) -> torch.Tensor:
"""Convert a batched tensor to one image with padding in between.
Args:
@@ -251,7 +249,7 @@ def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) ->
padding: The amount of padding to add between images.
Returns:
- Tensor: The combined image grid.
+ torch.Tensor: The combined image grid.
"""
if not isinstance(tensor, torch.Tensor):
@@ -259,7 +257,7 @@ def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) ->
B, C, H, W = tensor.shape
if n_row is None:
- n_row = int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil().item())
+ n_row = int(torch.sqrt(tensor(B, dtype=torch.float32)).ceil().item())
n_col = (B + n_row - 1) // n_row
padded_H = H + padding
@@ -291,7 +289,7 @@ def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) ->
return combined
-def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
+def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
"""Apply `f` to an image of arbitrary leading dimensions `(*, C, H, W)`.
It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the image as original
@@ -299,9 +297,9 @@ def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""
@wraps(f)
- def _wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Tensor:
- if not isinstance(input, Tensor):
- raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
+ def _wrapper(input: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
if input.shape.numel() == 0:
raise ValueError("Invalid input tensor, it is empty.")
@@ -323,7 +321,7 @@ def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
return _wrapper
-def perform_keep_shape_video(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
+def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
"""Apply `f` to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the image as original
@@ -331,9 +329,9 @@ def perform_keep_shape_video(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""
@wraps(f)
- def _wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Tensor:
- if not isinstance(input, Tensor):
- raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
+ def _wrapper(input: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
if input.numel() == 0:
raise ValueError("Invalid input tensor, it is empty.")
diff --git a/kornia/utils/image_print.py b/kornia/utils/image_print.py
index 5fa58fcae..299e60ea4 100644
--- a/kornia/utils/image_print.py
+++ b/kornia/utils/image_print.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-"""Convert an image tensor to an ANSI text string (xterm-256color).
+"""Convert an image torch.tensor to an ANSI text string (xterm-256color).
Nice long listing of all 256 colors and their codes.
@@ -29,7 +29,6 @@ import torch
from torch import float16, float32, float64
import kornia
-from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK_IS_IMAGE, KORNIA_CHECK_SHAPE
from kornia.io import ImageLoadType
@@ -357,9 +356,9 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
- """Obtain the closest xterm-256 approximation string from an image tensor.
+ """Obtain the closest xterm-256 approximation string from an image torch.tensor.
- The tensor shall be either 0~1 float type or 0~255 long type.
+ The torch.tensor shall be either 0~1 float type or 0~255 long type.
Args:
image: an RGB image with shape :math:`3HW`.
@@ -397,13 +396,13 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
return "".join(lines)
-def print_image(image: Union[str, Tensor], max_width: int = 96) -> None:
+def print_image(image: Union[str, torch.Tensor], max_width: int = 96) -> None:
"""Print an image to the terminal.
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
Args:
- image: path to a valid image file or a tensor.
+ image: path to a valid image file or a torch.tensor.
max_width: maximum width to print to terminal.
Note:
@@ -412,8 +411,8 @@ def print_image(image: Union[str, Tensor], max_width: int = 96) -> None:
"""
if isinstance(image, str):
img = kornia.io.load_image(image, ImageLoadType.RGB8)
- elif isinstance(image, Tensor):
+ elif isinstance(image, torch.Tensor):
img = image
else:
- raise RuntimeError(f"Expect image type to be either Tensor or str. Got {type(image)}.")
+ raise RuntimeError(f"Expect image type to be either torch.Tensor or str. Got {type(image)}.")
print(image_to_string(img, max_width))
diff --git a/kornia/utils/memory.py b/kornia/utils/memory.py
index 19aeba4ae..c555f63ea 100644
--- a/kornia/utils/memory.py
+++ b/kornia/utils/memory.py
@@ -15,14 +15,19 @@
# limitations under the License.
#
-from typing import Any, Dict
+from typing import Any, Dict, Union
-from kornia.core import Device, Module, Tensor, concatenate
+import torch
+from torch import nn
def batched_forward(
- model: Module, data: Tensor, device: Device, batch_size: int = 128, **kwargs: Dict[str, Any]
-) -> Tensor:
+ model: nn.Module,
+ data: torch.Tensor,
+ device: Union[str, torch.device, None],
+ batch_size: int = 128,
+ **kwargs: Dict[str, Any],
+) -> torch.Tensor:
r"""Run the forward in micro-batches.
When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.
@@ -65,6 +70,6 @@ def batched_forward(
if st >= end:
continue
out_list.append(model_dev(data[st:end].to(device), **kwargs))
- out = concatenate(out_list, 0)
+ out = torch.cat(out_list, 0)
return out.to(data.device)
return model(data, **kwargs)
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index df253ec4e..7af3c35d2 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -19,10 +19,8 @@ from typing import Optional
import torch
-from kornia.core import Tensor, eye, zeros
-
-def eye_like(n: int, input: Tensor, shared_memory: bool = False) -> Tensor:
+def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.
Args:
@@ -45,12 +43,12 @@ def eye_like(n: int, input: Tensor, shared_memory: bool = False) -> Tensor:
if len(input.shape) < 1:
raise AssertionError(input.shape)
- identity = eye(n, device=input.device).type(input.dtype)
+ identity = torch.eye(n, device=input.device).type(input.dtype)
return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)
-def vec_like(n: int, tensor: Tensor, shared_memory: bool = False) -> Tensor:
+def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.
Args:
@@ -73,62 +71,62 @@ def vec_like(n: int, tensor: Tensor, shared_memory: bool = False) -> Tensor:
if len(tensor.shape) < 1:
raise AssertionError(tensor.shape)
- vec = zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
+ vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)
-def differentiable_polynomial_rounding(input: Tensor) -> Tensor:
+def differentiable_polynomial_rounding(input: torch.Tensor) -> torch.Tensor:
"""Differentiable rounding.
Args:
- input (Tensor): Input tensor of any shape to be rounded.
+ input (torch.Tensor): Input tensor of any shape to be rounded.
Returns:
- output (Tensor): Pseudo rounded tensor of the same shape as input tensor.
+ output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.
"""
# Perform differentiable rounding
input_round = input.round()
- output: Tensor = input_round + (input - input_round) ** 3
+ output: torch.Tensor = input_round + (input - input_round) ** 3
return output
-def differentiable_polynomial_floor(input: Tensor) -> Tensor:
+def differentiable_polynomial_floor(input: torch.Tensor) -> torch.Tensor:
"""Perform floor via a differentiable operation.
Args:
- input (Tensor): Input tensor of any shape to be floored.
+ input (torch.Tensor): Input tensor of any shape to be floored.
Returns:
- output (Tensor): Pseudo rounded tensor of the same shape as input tensor.
+ output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.
"""
# Perform differentiable rounding
input_floor = input.floor()
- output: Tensor = input_floor + (input - 0.5 - input_floor) ** 3
+ output: torch.Tensor = input_floor + (input - 0.5 - input_floor) ** 3
return output
def differentiable_clipping(
- input: Tensor,
+ input: torch.Tensor,
min_val: Optional[float] = None,
max_val: Optional[float] = None,
scale: float = 0.02,
-) -> Tensor:
+) -> torch.Tensor:
"""Clip via a differentiable and soft approximation of the clipping operation.
Args:
- input (Tensor): Input tensor of any shape.
+ input (torch.Tensor): Input tensor of any shape.
min_val (Optional[float]): Minimum value.
max_val (Optional[float]): Maximum value.
scale (float): Scale value. Default 0.02.
Returns:
- output (Tensor): Clipped output tensor of the same shape as the input tensor.
+ output (torch.Tensor): Clipped output tensor of the same shape as the input tensor.
"""
# Make a copy of the input tensor
- output: Tensor = input.clone()
+ output: torch.Tensor = input.clone()
# Perform differentiable soft clipping
if max_val is not None:
output[output > max_val] = -scale * (torch.exp(-output[output > max_val] + max_val) - 1.0) + max_val
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index 2e8068af6..4497085fc 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -17,22 +17,22 @@
import torch
-from kornia.core import Tensor
-
-def one_hot(labels: Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 1e-6) -> Tensor:
- r"""Convert an integer label x-D tensor to a one-hot (x+1)-D tensor.
+def one_hot(
+ labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 1e-6
+) -> torch.Tensor:
+ r"""Convert an integer label x-D torch.tensor to a one-hot (x+1)-D torch.tensor.
Args:
- labels: tensor with labels of shape :math:`(N, *)`, where N is batch size.
+ labels: torch.tensor with labels of shape :math:`(N, *)`, torch.where N is batch size.
Each value is an integer representing correct classification.
num_classes: number of classes in labels.
- device: the desired device of returned tensor.
- dtype: the desired data type of returned tensor.
+ device: the desired device of returned torch.tensor.
+ dtype: the desired data type of returned torch.tensor.
eps: epsilon for numerical stability.
Returns:
- the labels in one hot tensor of shape :math:`(N, C, *)`,
+ the labels in one hot torch.tensor of shape :math:`(N, C, *)`,
Examples:
>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
@@ -47,8 +47,8 @@ def one_hot(labels: Tensor, num_classes: int, device: torch.device, dtype: torch
[1.0000e+00, 1.0000e-06]]]])
"""
- if not isinstance(labels, Tensor):
- raise TypeError(f"Input labels type is not a Tensor. Got {type(labels)}")
+ if not isinstance(labels, torch.Tensor):
+ raise TypeError(f"Input labels type is not a torch.Tensor. Got {type(labels)}")
if not labels.dtype == torch.int64:
raise ValueError(f"labels must be of the same dtype torch.int64. Got: {labels.dtype}")
diff --git a/kornia/utils/sample.py b/kornia/utils/sample.py
index eadca40c7..b0b855a1d 100644
--- a/kornia/utils/sample.py
+++ b/kornia/utils/sample.py
@@ -20,8 +20,9 @@ import logging
import os
from typing import Any, List, Optional, Tuple, Union
+import torch
+
import kornia
-from kornia.core import Tensor, stack
from kornia.core.external import PILImage as Image
from kornia.core.external import requests
from kornia.io import load_image
@@ -60,7 +61,7 @@ def get_sample_images(
as_list: Optional[bool] = None,
divisible_factor: Optional[int] = None,
**kwargs: Any,
-) -> Union[Tensor, List[Tensor]]:
+) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Load multiple images from the given URLs.
Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.
@@ -110,6 +111,6 @@ def get_sample_images(
tensors.append(img_tensor)
if not as_list and resize is not None:
- return stack(tensors)
+ return torch.stack(tensors)
return tensors
diff --git a/pyproject.toml b/pyproject.toml
index b0c0380db..b28fd0328 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -241,6 +241,9 @@ markers = [
"nn: mark a test as module test",
"slow: mark test as slow to run",
]
+filterwarnings = [
+ "ignore::DeprecationWarning:onnxscript.converter",
+]
# Test configuration via environment variables:
# KORNIA_TEST_DEVICE: cpu, cuda, mps (default: cpu)
# KORNIA_TEST_DTYPE: float32, float64, float16, bfloat16 (default: float32)
diff --git a/testing/base.py b/testing/base.py
index b757b46b5..8f4bbc327 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -24,7 +24,8 @@ import torch
from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
-from kornia.core import Dtype, Tensor
+Dtype = Union[torch.dtype, None]
+Tensor = torch.Tensor
# {dtype: (rtol, atol)}
_DTYPE_PRECISIONS = {
diff --git a/testing/casts.py b/testing/casts.py
index c65636c59..0aa4495e0 100644
--- a/testing/casts.py
+++ b/testing/casts.py
@@ -19,13 +19,13 @@ from __future__ import annotations
from typing import Any, TypeVar
-from kornia.core import Device, Dtype, Tensor
+import torch
T = TypeVar("T")
-def dict_to(data: dict[T, Any], device: Device, dtype: Dtype) -> dict[T, Any]:
+def dict_to(data: dict[T, Any], device: torch.device, dtype: torch.dtype) -> dict[T, Any]:
out: dict[T, Any] = {}
for key, val in data.items():
- out[key] = val.to(device, dtype) if isinstance(val, Tensor) else val
+ out[key] = val.to(device, dtype) if isinstance(val, torch.Tensor) else val
return out
diff --git a/testing/error.py b/testing/error.py
index 006c47c9d..0f27949ff 100644
--- a/testing/error.py
+++ b/testing/error.py
@@ -19,9 +19,7 @@ from __future__ import annotations
import torch
-from kornia.core import Tensor
-
-def compute_patch_abs_error(x: Tensor, y: Tensor, h: int, w: int) -> Tensor:
+def compute_patch_abs_error(x: torch.Tensor, y: torch.Tensor, h: int, w: int) -> torch.Tensor:
"""Compute the absolute error between patches."""
return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()
diff --git a/testing/geometry/create.py b/testing/geometry/create.py
index 4a9b861c8..46d3bd9fb 100644
--- a/testing/geometry/create.py
+++ b/testing/geometry/create.py
@@ -17,32 +17,38 @@
from __future__ import annotations
-from typing import Optional
+from typing import Optional, Union
import torch
import kornia.geometry.epipolar as epi
-from kornia.core import Device, Dtype, Tensor, tensor, zeros
from kornia.utils.misc import eye_like
-def create_random_homography(data: Tensor, eye_size: int, std_val: float = 1e-3) -> Tensor:
+def create_random_homography(data: torch.Tensor, eye_size: int, std_val: float = 1e-3) -> torch.Tensor:
"""Create a batch of random homographies of shape Bx3x3."""
- std = zeros(data.shape[0], eye_size, eye_size, device=data.device, dtype=data.dtype)
+ std = torch.zeros(data.shape[0], eye_size, eye_size, device=data.device, dtype=data.dtype)
eye = eye_like(eye_size, data)
return eye + std.uniform_(-std_val, std_val)
-def create_rectified_fundamental_matrix(batch_size: int, dtype: Dtype = None, device: Device = None) -> Tensor:
+def create_rectified_fundamental_matrix(
+ batch_size: int, dtype: Optional[torch.dtype] = None, device: Optional[Union[str, torch.device]] = None
+) -> torch.Tensor:
"""Create a batch of rectified fundamental matrices of shape Bx3x3."""
- F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 3, 3)
+ F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(
+ 1, 3, 3
+ )
F_repeat = F_rect.expand(batch_size, 3, 3)
return F_repeat
def create_random_fundamental_matrix(
- batch_size: int, std_val: float = 1e-3, dtype: Dtype = None, device: Device = None
-) -> Tensor:
+ batch_size: int,
+ std_val: float = 1e-3,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[Union[str, torch.device]] = None,
+) -> torch.Tensor:
"""Create a batch of random fundamental matrices of shape Bx3x3."""
F_rect = create_rectified_fundamental_matrix(batch_size, dtype, device)
H_left = create_random_homography(F_rect, 3, std_val)
diff --git a/testing/parametrized_tester.py b/testing/parametrized_tester.py
index f5d705b49..67b656408 100644
--- a/testing/parametrized_tester.py
+++ b/testing/parametrized_tester.py
@@ -36,11 +36,12 @@ Example:
from __future__ import annotations
import warnings
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Optional, Union
import torch
-from kornia.core import Dtype, Tensor
+Dtype = Union[torch.dtype, None]
+Tensor = torch.Tensor
def parametrized_test(
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index bfb64c99f..967536535 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -125,13 +125,13 @@ class TestRandomMixUpV2(BaseTester):
class TestRandomCutMixV2(BaseTester):
def test_smoke(self):
- f = RandomCutMixV2(data_keys=["input", "class"])
- repr = "RandomCutMixV2(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
- assert str(f) == repr
+ f = RandomCutMixV2(data_keys=["input", "class"], use_correct_lambda=True)
+ expected_repr = "RandomCutMixV2(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
+ assert str(f) == expected_repr
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMixV2(p=1.0, data_keys=["input", "class"])
+ f = RandomCutMixV2(p=1.0, data_keys=["input", "class"], use_correct_lambda=True)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -156,7 +156,7 @@ class TestRandomCutMixV2(BaseTester):
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMixV2(p=0.0, data_keys=["input", "class"])
+ f = RandomCutMixV2(p=0.0, data_keys=["input", "class"], use_correct_lambda=True)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -175,7 +175,7 @@ class TestRandomCutMixV2(BaseTester):
torch.manual_seed(76)
# beta 0 => resample 0.5 area
# beta cannot be 0 after torch 1.8.0
- f = RandomCutMixV2(beta=1e-7, p=1.0, data_keys=["input", "class"])
+ f = RandomCutMixV2(beta=1e-7, p=1.0, data_keys=["input", "class"], use_correct_lambda=True)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -196,12 +196,17 @@ class TestRandomCutMixV2(BaseTester):
self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
self.assert_close(out_label[0, :, 0], label)
self.assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- # cut area = 4 / 12
- self.assert_close(out_label[0, :, 2], torch.tensor([0.33333, 0.33333], device=device, dtype=dtype))
+ # cut area = 4 / 12, but with use_correct_lambda=True the lambda calculation is different
+ self.assert_close(
+ out_label[0, :, 2],
+ torch.tensor([0.66667, 0.66667], device=device, dtype=dtype),
+ rtol=1e-4,
+ atol=1e-4,
+ )
def test_random_mixup_num2(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMixV2(num_mix=5, p=1.0, data_keys=["input", "class"])
+ f = RandomCutMixV2(num_mix=5, p=1.0, data_keys=["input", "class"], use_correct_lambda=True)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -224,10 +229,11 @@ class TestRandomCutMixV2(BaseTester):
self.assert_close(
out_label[:, :, 1], torch.tensor([[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]], device=device, dtype=dtype)
)
+ # Updated expected values for use_correct_lambda=True
self.assert_close(
out_label[:, :, 2],
torch.tensor(
- [[0.0833, 0.3333], [0.0, 0.1667], [0.5, 0.0833], [0.0833, 0.0], [0.5, 0.3333]],
+ [[0.9167, 0.6667], [1.0, 0.8333], [0.5, 0.9167], [0.9167, 1.0], [0.5, 0.6667]],
device=device,
dtype=dtype,
),
@@ -237,7 +243,7 @@ class TestRandomCutMixV2(BaseTester):
def test_random_mixup_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- f = RandomCutMixV2(same_on_batch=True, p=1.0, data_keys=["input", "class"])
+ f = RandomCutMixV2(same_on_batch=True, p=1.0, data_keys=["input", "class"], use_correct_lambda=True)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -623,7 +629,7 @@ class TestRandomTransplantation(BaseTester):
f = RandomTransplantation(p=1.0)
f(image, mask, data_keys=["input", "mask", "mask"])
- with pytest.raises(Exception, match="selected_labels must be a 1-dimensional tensor"):
+ with pytest.raises(Exception, match=r"selected_labels must be a 1-dimensional torch\.tensor"):
params_copy = copy.deepcopy(params)
params_copy["selected_labels"] = torch.tensor([[0, 1]], device=device, dtype=dtype)
del params_copy["selection"]
diff --git a/tests/augmentation/test_param_validation.py b/tests/augmentation/test_param_validation.py
index 1379a1cbc..0d42839fd 100644
--- a/tests/augmentation/test_param_validation.py
+++ b/tests/augmentation/test_param_validation.py
@@ -106,8 +106,8 @@ class TestParamValidation:
((-10, 2), {}, ValueError, None),
(("invalid", 2), {}, TypeError, None),
((torch.rand(2, 3), 2), {}, ValueError, "Degrees must be a"),
- (([1, 2, 3], 2), {}, TypeError, "If not pass a tensor"),
- ((["a", 1.0], 2), {}, TypeError, "If not pass a tensor"),
+ (([1, 2, 3], 2), {}, TypeError, "If not pass a torch.tensor"),
+ ((["a", 1.0], 2), {}, TypeError, "If not pass a torch.tensor"),
],
)
def test_tuple_range_reader_errors(self, args, kwargs, expected_exception, match_msg):
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 17749af26..e25f774a2 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -980,8 +980,8 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
expected = {
"src": torch.tensor(
[
- [[3.0, 12.0], [298.0, 12.0], [298.0, 294.0], [3.0, 294.0]],
- [[8.0, 20.0], [284.0, 20.0], [284.0, 298.0], [8.0, 298.0]],
+ [[11.0, 3.0], [293.0, 3.0], [293.0, 298.0], [11.0, 298.0]],
+ [[8.0, 22.0], [286.0, 22.0], [286.0, 298.0], [8.0, 298.0]],
],
device=device,
dtype=dtype,
@@ -1012,8 +1012,8 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
expected = {
"src": torch.tensor(
[
- [[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
- [[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
+ [[0.0, 9.0], [298.0, 9.0], [298.0, 287.0], [0.0, 287.0]],
+ [[0.0, 9.0], [298.0, 9.0], [298.0, 287.0], [0.0, 287.0]],
],
device=device,
dtype=dtype,
diff --git a/tests/color/test_colormap.py b/tests/color/test_colormap.py
index 2d472ce2f..a4a01a280 100644
--- a/tests/color/test_colormap.py
+++ b/tests/color/test_colormap.py
@@ -18,33 +18,32 @@
import pytest
import torch
-from kornia.color import AUTUMN, ApplyColorMap, ColorMap, ColorMapType, apply_colormap
-from kornia.core import tensor
+from kornia.color import ApplyColorMap, ColorMap, ColorMapType, apply_colormap
from testing.base import BaseTester, assert_close
def test_autumn(device, dtype):
- cm = AUTUMN(num_colors=64, device=device, dtype=dtype)
+ cm = ColorMap(base="autumn", num_colors=64, device=device, dtype=dtype)
colors = cm.colors
actual = colors[..., 0]
- expected = tensor([1, 0, 0], device=device, dtype=dtype)
+ expected = torch.tensor([1, 0, 0], device=device, dtype=dtype)
assert_close(actual, expected)
actual = colors[..., 32]
- expected = tensor([1.0, 0.5079365079365079, 0.0], device=device, dtype=dtype)
+ expected = torch.tensor([1.0, 0.5079365079365079, 0.0], device=device, dtype=dtype)
assert_close(actual, expected)
actual = colors[..., -1]
- expected = tensor([1, 1, 0], device=device, dtype=dtype)
+ expected = torch.tensor([1, 1, 0], device=device, dtype=dtype)
assert_close(actual, expected)
class TestApplyColorMap(BaseTester):
def test_smoke(self, device, dtype):
- input_tensor = tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]], device=device, dtype=dtype)
- expected_tensor = tensor(
+ input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]], device=device, dtype=dtype)
+ expected_tensor = torch.tensor(
[
[
[
diff --git a/tests/contrib/test_connected_component.py b/tests/contrib/test_connected_component.py
index f447f042a..d0587a5e0 100644
--- a/tests/contrib/test_connected_component.py
+++ b/tests/contrib/test_connected_component.py
@@ -44,7 +44,7 @@ class TestConnectedComponents(BaseTester):
with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components("not a tensor", 0)
- assert "Input imagetype is not a Tensor. Got:" in str(errinf)
+ assert "Input imagetype is not a torch.Tensor" in str(errinf)
with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components(img, 0)
diff --git a/tests/contrib/test_face_detection.py b/tests/contrib/test_face_detection.py
index 87a69015e..cea9c5fe0 100644
--- a/tests/contrib/test_face_detection.py
+++ b/tests/contrib/test_face_detection.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
@@ -89,13 +91,16 @@ class TestFaceDetection(BaseTester):
model_path = tmp_path / "facedetector_model.onnx"
dynamic_axes = {"images": {0: "B"}}
- torch.onnx.export(
- model,
- img,
- model_path,
- input_names=["images"],
- output_names=["loc", "conf", "iou"],
- dynamic_axes=dynamic_axes,
- )
+ # Suppress onnxscript deprecation warnings (Python 3.15 compatibility)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module="onnxscript.converter")
+ torch.onnx.export(
+ model,
+ img,
+ model_path,
+ input_names=["images"],
+ output_names=["loc", "conf", "iou"],
+ dynamic_axes=dynamic_axes,
+ )
assert model_path.is_file()
diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.py
index ba324d0cc..5fa14a390 100644
--- a/tests/core/test_tensor_wrapper.py
+++ b/tests/core/test_tensor_wrapper.py
@@ -18,7 +18,6 @@
import pytest
import torch
-from kornia.core import Tensor
from kornia.core.tensor_wrapper import TensorWrapper, unwrap, wrap
from testing.base import BaseTester
@@ -29,7 +28,7 @@ class TestTensorWrapper(BaseTester):
data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
tensor = wrap(data, TensorWrapper)
assert isinstance(tensor, TensorWrapper)
- assert isinstance(tensor.data, Tensor)
+ assert isinstance(tensor.data, torch.Tensor)
assert tensor.shape == (1, 2, 3, 4)
assert tensor.device == device
assert tensor.dtype == dtype
diff --git a/tests/enhance/test_core.py b/tests/enhance/test_core.py
index b0f39ee77..117da3d57 100644
--- a/tests/enhance/test_core.py
+++ b/tests/enhance/test_core.py
@@ -21,7 +21,6 @@ import pytest
import torch
import kornia
-from kornia.core import Tensor
from testing.base import BaseTester
@@ -61,11 +60,11 @@ class TestAddWeighted(BaseTester):
def test_shape(self, device, dtype, size1, size2, alpha, beta, gamma):
src1 = torch.randn(size1, device=device, dtype=dtype)
src2 = torch.randn(size2, device=device, dtype=dtype)
- if isinstance(alpha, Tensor):
+ if isinstance(alpha, torch.Tensor):
alpha = alpha.to(src1)
- if isinstance(beta, Tensor):
+ if isinstance(beta, torch.Tensor):
beta = beta.to(src2)
- if isinstance(gamma, Tensor):
+ if isinstance(gamma, torch.Tensor):
gamma = gamma.to(src1)
self.assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.py
index 6f3cd364d..3f2f3ee15 100644
--- a/tests/enhance/test_histogram.py
+++ b/tests/enhance/test_histogram.py
@@ -60,7 +60,7 @@ class TestImageHistogram2d(BaseTester):
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
def test_jit(self, device, dtype, kernel):
sample = torch.linspace(0, 255, 10, device=device, dtype=dtype)
- sample_x, _ = torch.meshgrid(sample, sample)
+ sample_x, _ = torch.meshgrid(sample, sample, indexing="ij")
samples = (sample_x, 0.0, 255.0, 10, None, None, False, kernel)
op = TestImageHistogram2d.fcn
@@ -74,7 +74,7 @@ class TestImageHistogram2d(BaseTester):
@pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
def test_uniform_hist(self, device, dtype, kernel, size):
sample = torch.linspace(0, 255, 10, device=device, dtype=dtype)
- sample_x, _ = torch.meshgrid(sample, sample)
+ sample_x, _ = torch.meshgrid(sample, sample, indexing="ij")
sample_x = sample_x.repeat(*size)
if kernel == "gaussian":
bandwidth = 2 * 0.4**2
@@ -88,7 +88,7 @@ class TestImageHistogram2d(BaseTester):
@pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
def test_uniform_dist(self, device, dtype, kernel, size):
sample = torch.linspace(0, 255, 10, device=device, dtype=dtype)
- sample_x, _ = torch.meshgrid(sample, sample)
+ sample_x, _ = torch.meshgrid(sample, sample, indexing="ij")
sample_x = sample_x.repeat(*size)
if kernel == "gaussian":
bandwidth = 2 * 0.4**2
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index fb5beeb55..d0b9be8e9 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -92,7 +92,7 @@ class TestDiffJPEG(BaseTester):
B = 2
jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)
kornia.enhance.jpeg_codec_differentiable(1904.0, jpeg_quality)
- assert "Input input type is not a Tensor" in str(errinfo.value)
+ assert "Input input type is not a torch.Tensor" in str(errinfo.value)
from kornia.core.exceptions import TypeCheckError
diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.py
index c99f81d29..1519dfc68 100644
--- a/tests/feature/test_dedode.py
+++ b/tests/feature/test_dedode.py
@@ -21,6 +21,7 @@ import torch
from kornia.feature.dedode import DeDoDe
[email protected](reason="DeDoDe is ummaintained")
class TestDeDoDe:
@pytest.mark.slow
@pytest.mark.parametrize("descriptor_model", ["B", "G"])
diff --git a/tests/filters/test_dissolving.py b/tests/filters/test_dissolving.py
index 03cc470c5..6a3e325ed 100644
--- a/tests/filters/test_dissolving.py
+++ b/tests/filters/test_dissolving.py
@@ -18,7 +18,6 @@
import pytest
import torch
-from kornia.core import Tensor
from kornia.filters.dissolving import StableDiffusionDissolving
from kornia.utils._compat import torch_version_le
@@ -45,19 +44,19 @@ class TestStableDiffusionDissolving:
def test_encode_tensor_to_latent(self, sdm_2_1, dummy_image):
latents = sdm_2_1.model.encode_tensor_to_latent(dummy_image)
- assert isinstance(latents, Tensor), "Latent encoding failed"
+ assert isinstance(latents, torch.Tensor), "Latent encoding failed"
assert latents.shape == (1, 4, 8, 8), "Latent shape mismatch"
def test_decode_tensor_to_latent(self, sdm_2_1, dummy_image):
latents = sdm_2_1.model.encode_tensor_to_latent(dummy_image)
reconstructed_image = sdm_2_1.model.decode_tensor_to_latent(latents)
- assert isinstance(reconstructed_image, Tensor), "Latent decoding failed"
+ assert isinstance(reconstructed_image, torch.Tensor), "Latent decoding failed"
assert reconstructed_image.shape == dummy_image.shape, "Reconstructed image shape mismatch"
def test_dissolve(self, sdm_2_1, dummy_image):
step_number = 500 # Test with a middle step
dissolved_image = sdm_2_1(dummy_image, step_number)
- assert isinstance(dissolved_image, Tensor), "Dissolve failed"
+ assert isinstance(dissolved_image, torch.Tensor), "Dissolve failed"
assert dissolved_image.shape == dummy_image.shape, "Dissolved image shape mismatch"
def test_invalid_version(self):
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 2d0318ef4..998ef351f 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
@@ -40,24 +42,24 @@ from testing.base import BaseTester, assert_close
11,
5.0,
None,
- [[0.0663, 0.0794, 0.0914, 0.1010, 0.1072, 0.1094, 0.1072, 0.1010, 0.0914, 0.0794, 0.0663]],
+ torch.tensor([[0.0663, 0.0794, 0.0914, 0.1010, 0.1072, 0.1094, 0.1072, 0.1010, 0.0914, 0.0794, 0.0663]]),
),
(
11,
5.0,
8.0,
- [[0.0343, 0.0463, 0.0600, 0.0747, 0.0895, 0.1029, 0.1138, 0.1208, 0.1232, 0.1208, 0.1138]],
+ torch.tensor([[0.0343, 0.0463, 0.0600, 0.0747, 0.0895, 0.1029, 0.1138, 0.1208, 0.1232, 0.1208, 0.1138]]),
),
(
11,
11.0,
3.0,
- [[0.0926, 0.0946, 0.0957, 0.0961, 0.0957, 0.0946, 0.0926, 0.0900, 0.0867, 0.0828, 0.0785]],
+ torch.tensor([[0.0926, 0.0946, 0.0957, 0.0961, 0.0957, 0.0946, 0.0926, 0.0900, 0.0867, 0.0828, 0.0785]]),
),
],
)
def test_gaussian(window_size, sigma, mean, expected, device, dtype):
- expected = torch.tensor(expected, device=device, dtype=dtype)
+ expected = expected.to(device=device, dtype=dtype)
result = gaussian(window_size, sigma, mean=mean, device=device, dtype=dtype)
assert_close(result, expected, atol=1e-4, rtol=1e-4)
@@ -333,18 +335,21 @@ class TestGaussianBlur2d(BaseTester):
import os
import tempfile
- with tempfile.TemporaryDirectory() as tmpdir:
- onnx_path = os.path.join(tmpdir, "gaussian_blur2d.onnx")
- torch.onnx.export(
- model,
- sample_input,
- onnx_path,
- input_names=["input"],
- output_names=["output"],
- opset_version=17,
- )
- # Verify the file was created
- assert os.path.exists(onnx_path)
+ # Suppress onnxscript deprecation warnings (Python 3.15 compatibility)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module="onnxscript.converter")
+ with tempfile.TemporaryDirectory() as tmpdir:
+ onnx_path = os.path.join(tmpdir, "gaussian_blur2d.onnx")
+ torch.onnx.export(
+ model,
+ sample_input,
+ onnx_path,
+ input_names=["input"],
+ output_names=["output"],
+ opset_version=17,
+ )
+ # Verify the file was created
+ assert os.path.exists(onnx_path)
except Exception as e:
pytest.skip(f"ONNX export not supported: {e}")
diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.py
index e38675bfc..fc4bc90a5 100644
--- a/tests/filters/test_in_range.py
+++ b/tests/filters/test_in_range.py
@@ -78,13 +78,13 @@ class TestInRange(BaseTester):
def test_exception(self, device, dtype):
input_tensor = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
- with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or Tensor."):
+ with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or torch\.Tensor\."):
InRange(lower=3, upper=3)(input_tensor)
- with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or Tensor."):
+ with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or torch\.Tensor\."):
InRange(lower=[0.2, 0.2], upper=[0.2, 0.2])(input_tensor)
- with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or Tensor."):
+ with pytest.raises(Exception, match=r"Invalid `lower` and `upper` format. Should be tuple or torch\.Tensor\."):
InRange(lower=(0.2), upper=(0.2))(input_tensor)
with pytest.raises(
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index ef631050d..007dbbefa 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -24,7 +24,6 @@ import pytest
import requests
import torch
-from kornia.core import Tensor
from kornia.io import ImageLoadType, load_image, write_image
from kornia.utils._compat import torch_version_ge
@@ -42,7 +41,7 @@ def create_random_img8(height: int, width: int, channels: int) -> np.ndarray:
return (np.random.rand(height, width, channels) * 255).astype(np.uint8) # noqa: NPY002
-def create_random_img8_torch(height: int, width: int, channels: int, device=None) -> Tensor:
+def create_random_img8_torch(height: int, width: int, channels: int, device=None) -> torch.Tensor:
return (torch.rand(channels, height, width, device=device) * 255).to(torch.uint8)
@@ -84,14 +83,14 @@ def images_fn(png_image, jpg_image):
class TestIoImage:
def test_smoke(self, tmp_path: Path) -> None:
height, width = 4, 5
- img_th: Tensor = create_random_img8_torch(height, width, 3)
+ img_th: torch.Tensor = create_random_img8_torch(height, width, 3)
file_path = tmp_path / "image.jpg"
write_image(str(file_path), img_th)
assert file_path.is_file()
- img_load: Tensor = load_image(str(file_path), ImageLoadType.UNCHANGED)
+ img_load: torch.Tensor = load_image(str(file_path), ImageLoadType.UNCHANGED)
assert img_th.shape == img_load.shape
assert img_th.shape[1:] == (height, width)
@@ -102,7 +101,7 @@ class TestIoImage:
assert file_path.is_file()
- img_th: Tensor = load_image(file_path, ImageLoadType.UNCHANGED, str(device))
+ img_th: torch.Tensor = load_image(file_path, ImageLoadType.UNCHANGED, str(device))
assert str(img_th.device) == str(device)
@pytest.mark.parametrize("ext", ["png", "jpg"])
@@ -136,7 +135,7 @@ class TestIoImage:
@pytest.mark.parametrize("channels", [3])
def test_write_image(self, device, tmp_path, ext, channels):
height, width = 4, 5
- img_th: Tensor = create_random_img8_torch(height, width, channels, device)
+ img_th: torch.Tensor = create_random_img8_torch(height, width, channels, device)
file_path = tmp_path / f"image.{ext}"
write_image(file_path, img_th)
diff --git a/tests/models/test_box_filtering.py b/tests/models/test_box_filtering.py
index 55018f6e0..809a2894b 100644
--- a/tests/models/test_box_filtering.py
+++ b/tests/models/test_box_filtering.py
@@ -20,14 +20,13 @@ import torch
from numpy.testing import assert_almost_equal
from kornia.contrib.object_detection import BoxFiltering
-from kornia.core import tensor
class TestBoxFiltering:
@pytest.fixture
def sample_boxes(self):
# Setup some sample boxes with the format [class_id, confidence_score, x, y, w, h]
- return tensor(
+ return torch.tensor(
[
[
[1, 0.9, 10, 10, 20, 20], # High confidence, class 1
@@ -66,7 +65,7 @@ class TestBoxFiltering:
def test_class_filtering(self, sample_boxes):
"""Test filtering based on class IDs."""
# Set classes_to_keep to [1, 2]
- filter = BoxFiltering(classes_to_keep=tensor([1, 2]))
+ filter = BoxFiltering(classes_to_keep=torch.tensor([1, 2]))
filtered_boxes = filter(sample_boxes)
# Expected output: only boxes with class_id 1 and 2 should be kept
@@ -83,7 +82,7 @@ class TestBoxFiltering:
def test_combined_confidence_and_class_filtering(self, sample_boxes):
"""Test filtering based on both confidence and class IDs."""
# Set confidence threshold to 0.6 and classes_to_keep to [1, 3]
- filter = BoxFiltering(confidence_threshold=0.6, classes_to_keep=tensor([1, 3]))
+ filter = BoxFiltering(confidence_threshold=0.6, classes_to_keep=torch.tensor([1, 3]))
filtered_boxes = filter(sample_boxes)
# Expected output: only boxes with confidence > 0.6 and class_id in [1, 3] should be kept
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index 5ea57281b..4c0caf9ed 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import warnings
from pathlib import Path
import pytest
@@ -65,15 +66,18 @@ class TestObjectDetector(BaseTester):
model_path = tmp_path / "rtdetr.onnx"
dynamic_axes = {"images": {0: "N"}}
- torch.onnx.export(
- detector,
- data,
- model_path,
- input_names=["images"],
- output_names=["detections"],
- dynamic_axes=dynamic_axes,
- opset_version=17,
- )
+ # Suppress onnxscript deprecation warnings (Python 3.15 compatibility)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module="onnxscript.converter")
+ torch.onnx.export(
+ detector,
+ data,
+ model_path,
+ input_names=["images"],
+ output_names=["detections"],
+ dynamic_axes=dynamic_axes,
+ opset_version=17,
+ )
assert model_path.is_file()
diff --git a/tests/models/test_sam.py b/tests/models/test_sam.py
index a18dfa8b2..653fcb6c3 100644
--- a/tests/models/test_sam.py
+++ b/tests/models/test_sam.py
@@ -17,8 +17,8 @@
import pytest
import torch
+import torch.nn.functional as F
-from kornia.core import pad
from kornia.models.sam import Sam, SamConfig
from testing.base import BaseTester
@@ -28,7 +28,7 @@ def _pad_rb(x, size):
"""Pads right bottom."""
pad_h = size - x.shape[-2]
pad_w = size - x.shape[-1]
- return pad(x, (0, pad_w, 0, pad_h))
+ return F.pad(x, (0, pad_w, 0, pad_h))
class TestSam(BaseTester):
diff --git a/tests/models/test_tiny_vit.py b/tests/models/test_tiny_vit.py
index 5b251621c..479461400 100644
--- a/tests/models/test_tiny_vit.py
+++ b/tests/models/test_tiny_vit.py
@@ -20,7 +20,6 @@ import sys
import pytest
import torch
-from kornia.core import Tensor
from kornia.models.tiny_vit import TinyViT
from testing.base import BaseTester
@@ -33,7 +32,7 @@ class TestTinyViT(BaseTester):
data = torch.randn(1, 3, img_size, img_size, device=device, dtype=dtype)
out = model(data)
- assert isinstance(out, Tensor)
+ assert isinstance(out, torch.Tensor)
@pytest.mark.slow
@pytest.mark.parametrize("num_classes", [10, 100])
diff --git a/tests/utils/test_misc.py b/tests/utils/test_misc.py
index 5e2d7d10a..0ee09a1dc 100644
--- a/tests/utils/test_misc.py
+++ b/tests/utils/test_misc.py
@@ -17,7 +17,6 @@
import torch
-from kornia.core import tensor
from kornia.utils.misc import (
differentiable_clipping,
differentiable_polynomial_floor,
@@ -29,38 +28,38 @@ from testing.base import BaseTester
class TestDifferentiableClipping(BaseTester):
def test_differentiable_clipping(self, device):
- x = tensor([1.0, 6.0, 10.0, 12.0], device=device)
+ x = torch.tensor([1.0, 6.0, 10.0, 12.0], device=device)
y = differentiable_clipping(x, min_val=5.0, max_val=10.0)
- y_expected = tensor([4.9804, 6.0, 10.0, 10.0173], device=device)
+ y_expected = torch.tensor([4.9804, 6.0, 10.0, 10.0173], device=device)
self.assert_close(y, y_expected)
def test_gradcheck(self, device):
- x = tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64)
+ x = torch.tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64)
self.gradcheck(differentiable_clipping, (x, 5.0, 10.0))
class TestDifferentiablePolynomialRounding(BaseTester):
def test_differentiable_polynomial_rounding(self, device):
- x = tensor([1.5], device=device)
+ x = torch.tensor([1.5], device=device)
y = differentiable_polynomial_rounding(x)
- y_expected = tensor([1.875], device=device)
+ y_expected = torch.tensor([1.875], device=device)
self.assert_close(y, y_expected)
def test_gradcheck(self, device):
- x = tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=torch.float64)
+ x = torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=torch.float64)
self.gradcheck(differentiable_polynomial_rounding, (x))
class TestDifferentiablePolynomialFloor(BaseTester):
def test_differentiable_polynomial_floor(self, device):
- x = tensor([1.5], device=device)
+ x = torch.tensor([1.5], device=device)
y = differentiable_polynomial_floor(x)
- y_expected = tensor([1.0], device=device)
+ y_expected = torch.tensor([1.0], device=device)
self.assert_close(y, y_expected)
def test_gradcheck(self, device):
- x = tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64)
+ x = torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64)
self.gradcheck(differentiable_polynomial_floor, (x))
diff --git a/tests/utils/test_parametrized_tester_poc.py b/tests/utils/test_parametrized_tester_poc.py
index 1d6681d3a..e67ce6cd9 100644
--- a/tests/utils/test_parametrized_tester_poc.py
+++ b/tests/utils/test_parametrized_tester_poc.py
@@ -24,7 +24,6 @@ test_gradcheck methods parametrized across devices and dtypes.
import torch
-from kornia.core import tensor
from kornia.utils.misc import differentiable_clipping, differentiable_polynomial_floor
from testing.base import BaseTester
@@ -32,14 +31,14 @@ from testing.parametrized_tester import parametrized_test
@parametrized_test(
- smoke_inputs=lambda device, dtype: (tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
+ smoke_inputs=lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
cardinality_tests=[
{
- "inputs": lambda device, dtype: (tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
+ "inputs": lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
"expected_shape": torch.Size([4]),
}
],
- gradcheck_inputs=lambda device: (tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64),),
+ gradcheck_inputs=lambda device: (torch.tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64),),
)
class TestDifferentiableClippingAutomated(BaseTester):
"""Demonstration of automated tests for differentiable_clipping function.
@@ -58,14 +57,14 @@ class TestDifferentiableClippingAutomated(BaseTester):
@parametrized_test(
- smoke_inputs=lambda device, dtype: (tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
+ smoke_inputs=lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
cardinality_tests=[
{
- "inputs": lambda device, dtype: (tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
+ "inputs": lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
"expected_shape": torch.Size([4]),
}
],
- gradcheck_inputs=lambda device: (tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64),),
+ gradcheck_inputs=lambda device: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64),),
)
class TestDifferentiablePolynomialFloorAutomated(BaseTester):
"""Demonstration of automated tests for differentiable_polynomial_floor function.