Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Apply `kornia.core` ops into geometry module (#2676)

Luca Minciullo2428d781cc88
diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/contrib/models/sam/architecture/prompt_encoder.py
index 5398ec169..a386927c3 100644
--- a/kornia/contrib/models/sam/architecture/prompt_encoder.py
+++ b/kornia/contrib/models/sam/architecture/prompt_encoder.py
@@ -12,7 +12,7 @@ import torch
from torch import nn
from kornia.contrib.models.common import LayerNorm2d
-from kornia.core import Device, Module, Tensor, concatenate, stack, zeros
+from kornia.core import Device, Module, Tensor, concatenate, cos, sin, stack, zeros
class PromptEncoder(Module):
@@ -161,7 +161,7 @@ class PositionEmbeddingRandom(Module):
coords = coords @ self.positional_encoding_gaussian_matrix
coords = 2 * pi * coords
# outputs d_1 x ... x d_n x C shape
- return concatenate([torch.sin(coords), torch.cos(coords)], dim=-1)
+ return concatenate([sin(coords), cos(coords)], dim=-1)
def forward(self, size: tuple[int, int]) -> Tensor:
"""Generate positional encoding for a grid of the specified size."""
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index d0f733489..928623e19 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -9,6 +9,7 @@ from ._backend import (
as_tensor,
complex,
concatenate,
+ cos,
diag,
einsum,
eye,
@@ -19,8 +20,10 @@ from ._backend import (
ones_like,
pad,
rand,
+ sin,
softmax,
stack,
+ tan,
tensor,
where,
zeros,
@@ -44,6 +47,9 @@ __all__ = [
"softmax",
"as_tensor",
"rand",
+ "cos",
+ "sin",
+ "tan",
"where",
"eye",
"ones",
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index 422a0fe6a..e7712b7d2 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -30,7 +30,9 @@ 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
# constructors
as_tensor = torch.as_tensor
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 504e52c34..ef9d345d9 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -4,7 +4,7 @@ from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, stack, tensor, zeros
+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.linalg import transform_points
@@ -243,8 +243,8 @@ def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
B, N, _, _ = LAF.size()
pts = concatenate(
[
- 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),
+ 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.ones(n_pts - 1, 1),
],
dim=1,
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index d2023cc80..546a17c98 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -8,7 +8,21 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, ModuleList, Tensor, arange, concatenate, einsum, ones_like, softmax, stack, where, zeros
+from kornia.core import (
+ Module,
+ ModuleList,
+ Tensor,
+ arange,
+ concatenate,
+ cos,
+ einsum,
+ ones_like,
+ sin,
+ softmax,
+ stack,
+ where,
+ zeros,
+)
from kornia.core.check import KORNIA_CHECK
from kornia.utils._compat import torch_meshgrid
@@ -58,7 +72,7 @@ class LearnableFourierPositionalEncoding(Module):
def forward(self, x: Tensor) -> Tensor:
"""Encode position vector."""
projected = self.Wr(x)
- cosines, sines = torch.cos(projected), torch.sin(projected)
+ cosines, sines = cos(projected), sin(projected)
emb = stack([cosines, sines], 0).unsqueeze(-3)
return emb.repeat_interleave(2, dim=-1)
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index 066d310c8..389a3e03d 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -3,7 +3,7 @@ from typing import Tuple
import torch
-from kornia.core import Module, Tensor, zeros
+from kornia.core import Module, Tensor, cos, sin, zeros
class PositionEncodingSine(Module):
@@ -45,10 +45,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, :, :] = 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)
+ 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)
return pe.unsqueeze(0)
def update_position_encoding_size(self, max_shape: Tuple[int, int]) -> None:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 85839af32..3c1871faa 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -5,7 +5,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.constants import pi
-from kornia.core import Tensor, tensor, zeros
+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
@@ -148,8 +148,8 @@ class VonMisesKernel(nn.Module):
emb0 = self.emb0.to(x).repeat(x.size(0), 1, 1, 1)
frange = self.frange.to(x) * x
- emb1 = torch.cos(frange)
- emb2 = torch.sin(frange)
+ emb1 = cos(frange)
+ emb2 = sin(frange)
embedding = torch.cat([emb0, emb1, emb2], dim=1)
embedding = self.weights * embedding
return embedding
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 33b14cfc5..60e97822e 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -3,7 +3,7 @@ from typing import Any, Dict, Optional, Tuple
import torch
-from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros
+from kornia.core import Module, Tensor, concatenate, sin, stack, tensor, where, zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.bbox import nms
from kornia.utils import map_location_to_cpu, torch_meshgrid
@@ -372,7 +372,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] * torch.sin(cand_angles)
+ cand_dists = cand_vecs_norm[..., None] * sin(cand_angles)
junc_dist_mask = cand_dists <= dist_tolerance
junc_mask = junc_dist_mask * proj_mask
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 8aeec36b0..aa97103a3 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -6,7 +6,7 @@ from typing import Any, Optional
import torch
-from kornia.core import Device, Dtype, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+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
@@ -929,7 +929,7 @@ 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 * torch.cos(2.0 * math.pi * x / float(kernel_size - 1))
+ x = 0.5 - 0.5 * cos(2.0 * math.pi * x / float(kernel_size - 1))
return x
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index e309d1501..7c7c5681f 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -5,6 +5,8 @@ from typing import Optional
import torch
+from kornia.core import arange, ones_like, stack, where, zeros
+
from .linalg import transform_points
__all__ = [
@@ -197,7 +199,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
"""
validate_bbox(boxes)
# zero padding the surroundings
- mask = torch.zeros((len(boxes), height + 2, width + 2), dtype=boxes.dtype, device=boxes.device)
+ mask = zeros((len(boxes), height + 2, width + 2), dtype=boxes.dtype, device=boxes.device)
# push all points one pixel off
# in order to zero-out the fully filled rows or columns
box_i = (boxes + 1).long()
@@ -257,34 +259,34 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
[0., 0., 0., 0., 0.]]]]])
"""
validate_bbox3d(boxes)
- mask = torch.zeros((len(boxes), *size))
+ mask = zeros((len(boxes), *size))
mask_out = []
# TODO: Looking for a vectorized way
for m, box in zip(mask, boxes):
m = m.index_fill(
0,
- torch.arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),
+ arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),
torch.tensor(1, device=box.device, dtype=box.dtype),
)
m = m.index_fill(
1,
- torch.arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),
+ arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),
torch.tensor(1, device=box.device, dtype=box.dtype),
)
m = m.index_fill(
2,
- torch.arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),
+ arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),
torch.tensor(1, device=box.device, dtype=box.dtype),
)
m = m.unsqueeze(dim=0)
- m_out = torch.ones_like(m)
+ m_out = ones_like(m)
m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)
m_out = m_out * (m == 1).all(dim=3, keepdim=True).all(dim=1, keepdim=True)
m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=3, keepdim=True)
mask_out.append(m_out)
- return torch.stack(mask_out, dim=0).float()
+ return stack(mask_out, dim=0).float()
def bbox_generator(
@@ -548,9 +550,9 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
- inds = torch.where(ovr <= iou_threshold)[0]
+ inds = where(ovr <= iou_threshold)[0]
order = order[inds + 1]
if len(keep) > 0:
- return torch.stack(keep)
+ return stack(keep)
return torch.tensor(keep)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 39c01f8fd..8da512f29 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -5,7 +5,7 @@ from typing import Optional, cast
import torch
from torch import Size
-from kornia.core import Tensor
+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
@@ -67,7 +67,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 = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 2), device=xmin.device, dtype=xmin.dtype)
+ polygons = 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
@@ -149,7 +149,7 @@ def _boxes3d_to_polygons3d(
# Front
# Create (B,N,4,3) with all points in front top left position of boxes
- front_vertices = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 3), device=xmin.device, dtype=xmin.dtype)
+ front_vertices = 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)
@@ -442,7 +442,7 @@ class Boxes:
[5., 3.]]])
"""
quadrilaterals: torch.Tensor | list[torch.Tensor]
- if isinstance(boxes, (torch.Tensor)):
+ if isinstance(boxes, torch.Tensor):
quadrilaterals = _boxes_to_quadrilaterals(boxes, mode=mode, validate_boxes=validate_boxes)
else:
quadrilaterals = [_boxes_to_quadrilaterals(box, mode, validate_boxes) for box in boxes]
@@ -557,7 +557,7 @@ class Boxes:
(self._data.shape[0], self._data.shape[1], height, width), dtype=self.dtype, device=self.device
)
else: # (N, 4, 2)
- mask = torch.zeros((self._data.shape[0], height, width), dtype=self.dtype, device=self.device)
+ mask = zeros((self._data.shape[0], height, width), dtype=self.dtype, device=self.device)
# Boxes coordinates can be outside the image size after transforms. Clamp values to the image size
clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))
@@ -889,7 +889,7 @@ class Boxes3D:
batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
# Create boxes in xyzxyz_plus format.
- boxes = torch.stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
+ boxes = stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
batched_boxes.shape[0], batched_boxes.shape[1], 6
)
@@ -976,15 +976,13 @@ class Boxes3D:
)
if self._is_batched: # (B, N, 8, 3)
- mask = torch.zeros(
+ mask = 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 = torch.zeros(
- (self._data.shape[0], depth, height, width), dtype=self._data.dtype, device=self._data.device
- )
+ mask = 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 b27e2c44b..142936c0b 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -2,6 +2,8 @@ from typing import Optional
import torch
+from kornia.core import cos, ones_like, sin, stack, zeros_like
+
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75
def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool = False) -> torch.Tensor:
@@ -22,20 +24,20 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
taux = taux.reshape(-1)
tauy = tauy.reshape(-1)
- 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)
+ cTx = cos(taux)
+ sTx = sin(taux)
+ cTy = cos(tauy)
+ sTy = sin(tauy)
+ zero = zeros_like(cTx)
+ one = ones_like(cTx)
- 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)
+ 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)
R = Ry @ Rx
if return_inverse:
invR22 = 1 / R[..., 2, 2]
- invPz = torch.stack(
+ invPz = stack(
[invR22, zero, R[..., 0, 2] * invR22, zero, invR22, R[..., 1, 2] * invR22, zero, zero, one], -1
).reshape(-1, 3, 3)
@@ -45,9 +47,9 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
return inv_tilt
- 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)
+ Pz = 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:
@@ -137,7 +139,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 = torch.stack([xd, yd, torch.ones_like(xd)], -1) @ tilt.transpose(-2, -1)
+ points_untilt = stack([xd, yd, ones_like(xd)], -1) @ tilt.transpose(-2, -1)
xd = points_untilt[..., 0] / points_untilt[..., 2]
yd = points_untilt[..., 1] / points_untilt[..., 2]
@@ -150,4 +152,4 @@ def distort_points(
x = fx * xd + cx
y = fy * yd + cy
- return torch.stack([x, y], -1)
+ return stack([x, y], -1)
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index ba0fd3c92..61a8d7272 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -3,6 +3,7 @@ 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.geometry.conversions import convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
from kornia.utils import eye_like
@@ -34,7 +35,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 = torch.arange(D_int, dtype=torch.int64, device=points.device)
+ idxs = 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])
@@ -213,7 +214,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 = torch.zeros((B, 2 * N, 12), dtype=world_points.dtype, device=world_points.device)
+ system = 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]
@@ -241,11 +242,11 @@ def solve_pnp_dlt(
# rotation matrices. We do this in two parts:
# First, we fix the sign by making sure that the determinant of
- # the all the rotation matrices are non negative (since determinant
+ # the all the rotation matrices are non-negative (since determinant
# of a rotation matrix should be 1).
det = torch.det(solution[:, :3, :3])
- ones = torch.ones_like(det)
- sign_fix = torch.where(det < 0, ones * -1, ones)
+ ones = ones_like(det)
+ sign_fix = where(det < 0, ones * -1, ones)
solution = solution * sign_fix[:, None, None]
# Then, we make sure that norm of the 0th columns of the rotation
@@ -263,7 +264,7 @@ def solve_pnp_dlt(
# We may need to fix the signs of the columns of the ortho matrix.
# If right[i, j, j] is negative, then we need to flip the signs of
# the column ortho[i, :, j]. The below code performs the necessary
- # operations in an better way.
+ # operations in a better way.
mask = eye_like(3, ortho)
col_sign_fix = torch.sign(mask * right)
rot_mat = torch.bmm(ortho, col_sign_fix)
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 28738d5b7..4a809b4fc 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -4,6 +4,7 @@ from typing import Optional
import torch
+from kornia.core import stack
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
from kornia.utils import create_meshgrid
@@ -77,7 +78,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, torch.stack([x, y], dim=-1)).unbind(-1)
+ x, y = transform_points(inv_tilt, stack([x, y], dim=-1)).unbind(-1)
# Iteratively undistort points
x0, y0 = x, y
@@ -110,7 +111,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 torch.stack([x, y], -1)
+ return 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/pinhole.py b/kornia/geometry/camera/pinhole.py
index 9ea492fcf..b810dbd1c 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -2,7 +2,7 @@ from typing import Iterable, List, Union
import torch
-from kornia.core import Device, Tensor
+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
@@ -355,7 +355,7 @@ class PinholeCamera:
dtype: torch.dtype,
) -> "PinholeCamera":
# create the camera matrix
- intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
+ intrinsics = zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
intrinsics[..., 1, 1] += fy
intrinsics[..., 0, 2] += cx
@@ -363,14 +363,14 @@ class PinholeCamera:
intrinsics[..., 2, 2] += 1.0
intrinsics[..., 3, 3] += 1.0
# create the pose matrix
- extrinsics = torch.eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1)
+ extrinsics = 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 = torch.zeros(batch_size, device=device, dtype=dtype)
+ height_tmp = zeros(batch_size, device=device, dtype=dtype)
height_tmp[..., 0] += height
- width_tmp = torch.zeros(batch_size, device=device, dtype=dtype)
+ width_tmp = zeros(batch_size, device=device, dtype=dtype)
width_tmp[..., 0] += width
return self(intrinsics, extrinsics, height_tmp, width_tmp)
@@ -408,10 +408,10 @@ class PinholeCamerasList(PinholeCamera):
intrinsics.append(pinhole.intrinsics)
extrinsics.append(pinhole.extrinsics)
# concatenate and set members. We will assume BxNx4x4
- self.height: Tensor = torch.stack(height, dim=1)
- self.width: Tensor = torch.stack(width, dim=1)
- self._intrinsics: Tensor = torch.stack(intrinsics, dim=1)
- self._extrinsics: Tensor = torch.stack(extrinsics, dim=1)
+ 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)
return self
@property
@@ -465,7 +465,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 = torch.eye(4, device=pinholes.device, dtype=pinholes.dtype) + eps
+ k = 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
@@ -509,7 +509,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 = torch.eye(4, device=pinhole.device, dtype=pinhole.dtype)
+ k = 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)
@@ -681,7 +681,7 @@ def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12)
v_coord: Tensor = y_coord / (z_coord + eps)
# stack and return the coordinates, that's the actual flow
- pixel_coords_dst: Tensor = torch.stack([u_coord, v_coord], dim=-1)
+ pixel_coords_dst: Tensor = stack([u_coord, v_coord], dim=-1)
return pixel_coords_dst # BxHxWx2
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 6dc1337cd..52a5aaa1d 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -6,7 +6,7 @@ import torch
import torch.nn.functional as F
from kornia.constants import pi
-from kornia.core import Tensor, concatenate, pad, stack, tensor, where, zeros_like
+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
@@ -119,8 +119,8 @@ def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
if not (isinstance(rho, Tensor) & isinstance(phi, Tensor)):
raise TypeError(f"Input type is not a Tensor. Got {type(rho)}, {type(phi)}")
- x = rho * torch.cos(phi)
- y = rho * torch.sin(phi)
+ x = rho * cos(phi)
+ y = rho * sin(phi)
return x, y
@@ -300,8 +300,8 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
theta = torch.sqrt(theta2)
wxyz = axis_angle / (theta + eps)
wx, wy, wz = torch.chunk(wxyz, 3, dim=1)
- cos_theta = torch.cos(theta)
- sin_theta = torch.sin(theta)
+ cos_theta = cos(theta)
+ sin_theta = sin(theta)
r00 = cos_theta + wx * wx * (k_one - cos_theta)
r10 = wz * sin_theta + wx * wy * (k_one - cos_theta)
@@ -649,8 +649,8 @@ def quaternion_log_to_exp(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
norm_q: Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
# compute scalar and vector
- quaternion_vector: Tensor = quaternion * torch.sin(norm_q) / norm_q
- quaternion_scalar: Tensor = torch.cos(norm_q)
+ quaternion_vector: Tensor = quaternion * sin(norm_q) / norm_q
+ quaternion_scalar: Tensor = cos(norm_q)
# compose quaternion and return
quaternion_exp: Tensor = tensor([])
@@ -744,9 +744,9 @@ def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
ones: Tensor = torch.ones_like(half_theta)
k_neg: Tensor = 0.5 * ones
- k_pos: Tensor = torch.sin(half_theta) / theta
+ k_pos: Tensor = sin(half_theta) / theta
k: Tensor = where(mask, k_pos, k_neg)
- w: Tensor = where(mask, torch.cos(half_theta), ones)
+ w: Tensor = where(mask, cos(half_theta), ones)
quaternion: Tensor = torch.zeros(size=(*axis_angle.shape[:-1], 4), dtype=axis_angle.dtype, device=axis_angle.device)
quaternion[..., 1:2] = a0 * k
@@ -974,8 +974,8 @@ def angle_to_rotation_matrix(angle: Tensor) -> Tensor:
>>> output = angle_to_rotation_matrix(input) # Nx3x2x2
"""
ang_rad = deg2rad(angle)
- cos_a: Tensor = torch.cos(ang_rad)
- sin_a: Tensor = torch.sin(ang_rad)
+ 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)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 70be73e8b..26879c20e 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -45,7 +45,7 @@ def unproject_meshgrid(
Args:
camera_matrix: tensor containing the camera intrinsics with shape :math:`(3, 3)`.
- normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
+ normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth is
represented as the Euclidean ray length from the camera position.
Return:
@@ -176,7 +176,7 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: boo
Args:
depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.
camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.
- normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
+ normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth is
represented as the Euclidean ray length from the camera position.
Return:
@@ -226,7 +226,7 @@ def warp_frame_depth(
depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.
src_trans_dst: transformation matrix from destination to source with shape :math:`(B,4,4)`.
camera_matrix: tensor containing the camera intrinsics with shape :math:`(B,3,3)`.
- normalize_points: whether to normalise the pointcloud. This must be set to ``True`` when the depth
+ normalize_points: whether to normalize the pointcloud. This must be set to ``True`` when the depth
is represented as the Euclidean ray length from the camera position.
Return:
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 782c08eba..916ff78a0 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -4,6 +4,7 @@ from typing import Optional, Tuple
import torch
import kornia.geometry.epipolar as epi
+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
@@ -47,7 +48,7 @@ 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 = torch.ones_like(x1)
+ ones = ones_like(x1)
# build equations system and find null space.
# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
@@ -61,15 +62,15 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
else:
w_diag = torch.diag_embed(weights)
X = X.transpose(-2, -1) @ w_diag @ X
- # compute eigevectors and retrieve the one with the smallest eigenvalue, using SVD
+ # compute eigenvectors and retrieve the one with the smallest eigenvalue, using SVD
# turn off the grad check due to the unstable gradients from SVD.
# several close to zero values of eigenvalues.
_, _, V = _torch_svd_cast(X) # torch.svd
null_ = V[:, :, -4:] # the last four rows
nullSpace = V.transpose(-1, -2)[:, -4:, :]
- 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)
+ coeffs = zeros(batch_size, 10, 20, device=null_.device, dtype=null_.dtype)
+ d = zeros(batch_size, 60, device=null_.device, dtype=null_.dtype)
def fun(i: int, j: int) -> torch.Tensor:
return null_[:, 3 * j + i]
@@ -120,14 +121,14 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
b = coeffs[:, :, 10:]
singular_filter = torch.linalg.matrix_rank(coeffs[:, :, :10]) >= torch.max(
- torch.linalg.matrix_rank(coeffs), torch.ones_like(torch.linalg.matrix_rank(coeffs[:, :, :10])) * 10
+ torch.linalg.matrix_rank(coeffs), ones_like(torch.linalg.matrix_rank(coeffs[:, :, :10])) * 10
)
eliminated_mat = torch.linalg.solve(coeffs[singular_filter, :, :10], b[singular_filter])
coeffs_ = torch.cat((coeffs[singular_filter, :, :10], eliminated_mat), dim=-1)
- A = torch.zeros(coeffs_.shape[0], 3, 13, device=coeffs_.device, dtype=coeffs_.dtype)
+ A = zeros(coeffs_.shape[0], 3, 13, device=coeffs_.device, dtype=coeffs_.dtype)
for i in range(3):
A[:, i, 0] = 0.0
@@ -149,8 +150,8 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
null_i = nullSpace[bi]
# companion matrix solver for polynomial
- C = torch.zeros((10, 10), device=cs.device, dtype=cs.dtype)
- C[0:-1, 1:] = torch.eye(C[0:-1, 0:-1].shape[0], device=cs.device, dtype=cs.dtype)
+ C = zeros((10, 10), device=cs.device, dtype=cs.dtype)
+ C[0:-1, 1:] = eye(C[0:-1, 0:-1].shape[0], device=cs.device, dtype=cs.dtype)
C[-1, :] = -cs[bi][:-1] / cs[bi][-1]
roots = torch.real(torch.linalg.eigvals(C))
@@ -160,10 +161,10 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
n_sols = roots.size()
if n_sols == 0:
continue
- Bs = torch.stack(
+ Bs = stack(
(
- A_i[:3, :1] * (roots**3) + A_i[:3, 1:2] * roots.square() + A_i[0:3, 2:3] * (roots) + A_i[0:3, 3:4],
- A_i[0:3, 4:5] * (roots**3) + A_i[0:3, 5:6] * roots.square() + A_i[0:3, 6:7] * (roots) + A_i[0:3, 7:8],
+ A_i[:3, :1] * (roots**3) + A_i[:3, 1:2] * roots.square() + A_i[0:3, 2:3] * roots + A_i[0:3, 3:4],
+ A_i[0:3, 4:5] * (roots**3) + A_i[0:3, 5:6] * roots.square() + A_i[0:3, 6:7] * roots + A_i[0:3, 7:8],
),
dim=0,
).transpose(0, -1)
@@ -192,7 +193,7 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
Es *= inv
if Es.shape[0] < 10:
Es = torch.cat(
- (Es.clone(), torch.eye(3, device=Es.device, dtype=Es.dtype).repeat(10 - Es.shape[0], 1).reshape(-1, 9))
+ (Es.clone(), eye(3, device=Es.device, dtype=Es.dtype).repeat(10 - Es.shape[0], 1).reshape(-1, 9))
)
E_models.append(Es)
@@ -247,14 +248,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 = torch.ones_like(E_mat)
+ mask = ones_like(E_mat)
mask[..., -1:] *= -1.0 # fill last column with negative values
maskt = mask.transpose(-2, -1)
# avoid singularities
- 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)
+ U = where((torch.det(U) < 0.0)[..., None, None], U * mask, U)
+ Vt = 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
@@ -322,10 +323,10 @@ 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 = torch.stack([R1, R1, R2, R2], dim=-3)
- Ts = torch.stack([t, -t, t, -t], dim=-3)
+ Rs = stack([R1, R1, R2, R2], dim=-3)
+ Ts = stack([t, -t, t, -t], dim=-3)
- return (Rs, Ts)
+ return Rs, Ts
def motion_from_essential_choose_solution(
@@ -473,7 +474,7 @@ def relative_camera_motion(
# compute the relative translation vector
t = t2 - R @ t1
- return (R, t)
+ return R, t
def find_essential(
@@ -496,7 +497,7 @@ def find_essential(
solution_num = 10
batch_size = points1.shape[0]
- error = torch.zeros((batch_size, solution_num))
+ error = zeros((batch_size, solution_num))
for b in range(batch_size):
error[b] = epi.sampson_epipolar_distance(points1[b], points2[b], E.view(batch_size, solution_num, 3, 3)[b]).sum(
@@ -506,6 +507,6 @@ def find_essential(
KORNIA_CHECK_SHAPE(error, ["f{batch_size}", "10"])
chosen_indices = torch.argmin(error, dim=-1)
- result = torch.stack([(E.view(-1, solution_num, 3, 3))[i, chosen_indices[i], :] for i in range(batch_size)])
+ result = stack([(E.view(-1, solution_num, 3, 3))[i, chosen_indices[i], :] for i in range(batch_size)])
return result
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 912a10a77..f72074b55 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -4,7 +4,7 @@ from typing import Literal, Optional, Tuple
import torch
-from kornia.core import Tensor, concatenate
+from kornia.core import Tensor, concatenate, ones_like, stack, where, zeros
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
@@ -40,16 +40,16 @@ 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 = torch.ones_like(scale), torch.zeros_like(scale)
+ ones, zeros = ones_like(scale), torch.zeros_like(scale)
- transform = torch.stack(
+ transform = stack(
[scale, zeros, -scale * x_mean[..., 0, 0], zeros, scale, -scale * x_mean[..., 0, 1], zeros, zeros, ones], dim=-1
) # Bx9
transform = transform.view(-1, 3, 3) # Bx3x3
points_norm = transform_points(transform, points) # BxNx2
- return (points_norm, transform)
+ return points_norm, transform
def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
@@ -68,7 +68,7 @@ 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 torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
+ return where(norm_val.abs() > eps, M / (norm_val + eps), M)
# Reference: Adapted from the 'run_7point' function in opencv
@@ -94,7 +94,7 @@ 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 = torch.ones_like(x1)
+ ones = 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
@@ -115,7 +115,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
# form a cubic equation
# finding the coefficients of cubic polynomial (coeffs)
- coeffs = torch.zeros((batch_size, 4), device=v.device, dtype=v.dtype)
+ coeffs = zeros((batch_size, 4), device=v.device, dtype=v.dtype)
f1_det = torch.linalg.det(f1)
f2_det = torch.linalg.det(f2)
@@ -128,7 +128,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
# roots = torch.tensor(np.roots(coeffs.numpy()))
roots = solve_cubic(coeffs)
- fmatrix = torch.zeros((batch_size, 3, 3, 3), device=v.device, dtype=v.dtype)
+ fmatrix = 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
@@ -151,7 +151,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
+ f2_expanded[valid_root_mask] * _mu[valid_root_mask, :, None, None]
)
- mat_ind = torch.zeros(3, 3, dtype=torch.bool)
+ mat_ind = 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
@@ -193,7 +193,7 @@ 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 = torch.ones_like(x1)
+ ones = ones_like(x1)
# build equations system and solve DLT
# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
@@ -274,7 +274,7 @@ def compute_correspond_epilines(points: Tensor, F_mat: Tensor) -> Tensor:
# compute normal and compose equation line
nu: Tensor = a * a + b * b
- nu = torch.where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
+ nu = 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
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index b881a8b2a..fd1dee0d0 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -2,6 +2,8 @@
import torch
+from kornia.core import stack, zeros_like
+
def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
r"""Return the cross_product_matrix symmetric matrix of a vector.
@@ -20,7 +22,7 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
x2 = x[..., 2]
# construct the matrix, reshape to 3x3 and return
- zeros = torch.zeros_like(x0)
- cross_product_matrix_flat = torch.stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)
+ zeros = zeros_like(x0)
+ cross_product_matrix_flat = 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 040c66b51..90572916f 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -4,7 +4,7 @@ from typing import Tuple, Union
import torch
from torch.linalg import qr as linalg_qr
-from kornia.core import Tensor, concatenate, pad
+from kornia.core import Tensor, concatenate, ones_like, pad, stack, zeros_like
from kornia.utils import eye_like, vec_like
from kornia.utils.helpers import _torch_svd_cast
@@ -51,7 +51,7 @@ def random_intrinsics(low: Union[float, Tensor], high: Union[float, Tensor]) ->
"""
sampler = torch.distributions.Uniform(low, high)
fx, fy, cx, cy = (sampler.sample(torch.Size((1,))) for _ in range(4))
- zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)
+ zeros, ones = zeros_like(fx), ones_like(fx)
camera_matrix = concatenate([fx, zeros, cx, zeros, fy, cy, zeros, zeros, ones])
return camera_matrix.view(1, 3, 3)
@@ -202,4 +202,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 torch.stack([P1, P2], dim=-1)
+ return stack([P1, P2], dim=-1)
diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.py
index 2bd498d81..2ecd138a9 100644
--- a/kornia/geometry/epipolar/scene.py
+++ b/kornia/geometry/epipolar/scene.py
@@ -4,6 +4,7 @@ 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
@@ -12,7 +13,7 @@ from .projection import projection_from_KRt, random_intrinsics
def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
# Generate the 3d points
- points3d = torch.rand(1, num_points, 3) # NxMx3
+ points3d = rand(1, num_points, 3) # NxMx3
# Create random camera matrix
K = random_intrinsics(0.0, 100.0) # 1x3x3
@@ -29,12 +30,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 = torch.stack([tx, ty, tz], dim=1)[..., None]
+ tvec = 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] = torch.where(min_dist < 0, tz - min_dist + 1.0, tz)
+ tvec[:, 2, 0] = 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 956a11f71..5ae0eec0e 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -2,6 +2,7 @@
import torch
+from kornia.core import zeros
from kornia.geometry.conversions import convert_points_from_homogeneous
from kornia.utils.helpers import _torch_svd_cast
@@ -47,7 +48,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 = torch.zeros(points_shape[:-1] + (4, 4)).type_as(points1)
+ X = 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/linalg.py b/kornia/geometry/linalg.py
index f12500d25..04e3aac73 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import torch
-from kornia.core import Tensor
+from kornia.core import Tensor, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
@@ -65,7 +65,7 @@ def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
tvec_02: Tensor = torch.matmul(rmat_01, tvec_12) + tvec_01
# pack output tensor
- trans_02: Tensor = torch.zeros_like(trans_01)
+ trans_02: Tensor = zeros_like(trans_01)
trans_02[..., :3, 0:3] += rmat_02
trans_02[..., :3, -1:] += tvec_02
trans_02[..., -1, -1:] += 1.0
@@ -107,7 +107,7 @@ def inverse_transformation(trans_12: Tensor) -> Tensor:
tvec_21 = torch.matmul(-rmat_21, tvec_12)
# pack to output tensor
- trans_21 = torch.zeros_like(trans_12)
+ trans_21 = zeros_like(trans_12)
trans_21[..., :3, 0:3] += rmat_21
trans_21[..., :3, -1:] += tvec_21
trans_21[..., -1, -1:] += 1.0
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index a1a720d60..1c03c027f 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -3,7 +3,7 @@ import math
import torch
-from kornia.core import Tensor
+from kornia.core import Tensor, cos, ones_like, stack, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_SHAPE
@@ -49,7 +49,7 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
inv_2a = 0.5 / a
# Initialize solutions tensor
- solutions = torch.zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
+ solutions = zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
# Handle cases with zero discriminant
if torch.any(mask_zero):
@@ -102,7 +102,7 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
c = coeffs[:, 2] # coefficient of x
d = coeffs[:, 3] # constant term
- solutions = torch.zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
+ solutions = zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
mask_a_zero = a == 0
mask_b_zero = b == 0
@@ -135,9 +135,9 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
D = Q3 + R * R
b_a_3 = (1.0 / 3.0) * b_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 = ones_like(a)
+ a_R_zero = ones_like(a)
+ a_D_zero = ones_like(a)
a_Q_zero[~mask_a_zero] = Q
a_R_zero[~mask_a_zero] = R
@@ -155,7 +155,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] = torch.stack(
+ solutions[mask_QR_zero_solutions] = stack(
[-b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero]], dim=1
)
@@ -166,19 +166,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 * 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)
+ 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)
- a_D_positive = torch.zeros_like(a)
+ a_D_positive = 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 = torch.zeros_like(R)
- BD = torch.zeros_like(R)
+ AD = zeros_like(R)
+ BD = zeros_like(R)
R_abs = torch.abs(R)
mask_R_positive = R_abs > 1e-16
if torch.any(mask_R_positive):
@@ -216,7 +216,7 @@ def multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
degree 2 poly with the order :math:`(x^2, x*y, x*z, x, y^2, y*z, y, z^2, z, 1)`.
"""
- return torch.stack(
+ return stack(
[
a[:, 0] * b[:, 0],
a[:, 0] * b[:, 1] + a[:, 1] * b[:, 0],
@@ -251,7 +251,7 @@ def multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
x*y*z, x*y, x*z^2, x*z, x, y*z^2, y*z, y, z^3, z^2, z, 1)`.
"""
- return torch.stack(
+ return stack(
[
a[:, 0] * b[:, 0],
a[:, 4] * b[:, 1],
@@ -291,7 +291,7 @@ def determinant_to_polynomial(A: Tensor) -> Tensor:
a degree 10 poly, representing determinant (Eqn. 14 in the paper).
"""
- cs = torch.zeros(A.shape[0], 11, device=A.device, dtype=A.dtype)
+ cs = zeros(A.shape[0], 11, device=A.device, dtype=A.dtype)
cs[:, 0] = (
A[:, 0, 12] * A[:, 1, 3] * A[:, 2, 7]
- A[:, 0, 12] * A[:, 1, 7] * A[:, 2, 3]
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index aca16dd73..7f9fcec5f 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -5,9 +5,8 @@ r"""Implementation of "differentiable spatial to numerical" (soft-argmax) operat
from __future__ import annotations
import torch
-import torch.nn.functional as F
-from kornia.core import Tensor, concatenate
+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
@@ -46,7 +45,7 @@ def spatial_softmax2d(input: Tensor, temperature: Tensor = torch.tensor(1.0)) ->
temperature = temperature.to(device=input.device, dtype=input.dtype)
x = input.view(batch_size, channels, -1)
- x_soft = F.softmax(x * temperature, dim=-1)
+ x_soft = softmax(x * temperature, dim=-1)
return x_soft.view(batch_size, channels, height, width)
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 52c251ce0..d14f6f9bd 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -50,7 +50,7 @@ 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(ky), pad(kx), pad(kx)
def forward(self, x: Tensor, mask_only: bool = False) -> Tensor:
if len(x.shape) != 4:
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index fe6eacfec..2a459e497 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
-from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros
+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
@@ -576,10 +576,10 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
Hes = 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 += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
+ Hes += rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
nms_mask: Tensor = nms3d(input, (3, 3, 3), True)
- x_solved: Tensor = torch.zeros_like(b)
+ x_solved: Tensor = 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
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 9aeea8a39..ee6b0e91e 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -3,6 +3,7 @@ from typing import Optional, Tuple, Union
import torch
from torch import nn
+from kornia.core import 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
@@ -57,7 +58,7 @@ def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
def _compute_rotation_matrix(angle: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Compute a pure affine rotation matrix."""
- scale: torch.Tensor = torch.ones_like(center)
+ scale: torch.Tensor = ones_like(center)
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
@@ -80,7 +81,7 @@ def _compute_rotation_matrix3d(
raise AssertionError(f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}.")
angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)
- scales: torch.Tensor = torch.ones_like(yaw)
+ scales: torch.Tensor = ones_like(yaw)
matrix: torch.Tensor = get_projective_transform(center, angles, scales)
return matrix
@@ -97,7 +98,7 @@ def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for scaling."""
- angle: torch.Tensor = torch.zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)
+ angle: torch.Tensor = zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
@@ -762,15 +763,15 @@ class Affine(nn.Module):
device, dtype = _extract_device_dtype([angle, translation, scale_factor])
if angle is None:
- angle = torch.zeros(batch_size, device=device, dtype=dtype)
+ angle = zeros(batch_size, device=device, dtype=dtype)
self.angle = angle
if translation is None:
- translation = torch.zeros(batch_size, 2, device=device, dtype=dtype)
+ translation = zeros(batch_size, 2, device=device, dtype=dtype)
self.translation = translation
if scale_factor is None:
- scale_factor = torch.ones(batch_size, 2, device=device, dtype=dtype)
+ scale_factor = ones(batch_size, 2, device=device, dtype=dtype)
self.scale_factor = scale_factor
self.shear = shear
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 3511c329f..301c723b2 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -154,7 +154,7 @@ def center_crop3d(
[[37.0000, 38.0000],
[41.0000, 42.0000]]]]])
"""
- if not isinstance(tensor, (torch.Tensor)):
+ if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) != 5:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index c5030fa58..f664cac79 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -5,7 +5,7 @@ from typing import Optional
import torch
import torch.nn.functional as F
-from kornia.core import Tensor, concatenate, stack, tensor, zeros
+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,
@@ -216,7 +216,7 @@ def _fill_and_warp(src: Tensor, grid: Tensor, mode: str, align_corners: bool, fi
Returns:
the warped and filled tensor with shape :math:`(B, 3, H, W)`.
"""
- ones_mask = torch.ones_like(src)
+ ones_mask = ones_like(src)
fill_value = fill_value.to(ones_mask)[None, :, None, None] # cast and add dimensions for broadcasting
inv_ones_mask = 1 - F.grid_sample(ones_mask, grid, align_corners=align_corners, mode=mode, padding_mode="zeros")
inv_color_mask = inv_ones_mask * fill_value
@@ -339,7 +339,7 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
# we need to perform in batch
_zeros = zeros(B, device=points_src.device, dtype=points_src.dtype)
- _ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)
+ _ones = 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
@@ -657,9 +657,9 @@ def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional
x, y = torch.split(center, 1, dim=-1)
x, y = x.view(-1), y.view(-1)
- sx_tan = torch.tan(sx)
- sy_tan = torch.tan(sy)
- ones = torch.ones_like(sx)
+ 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
).view(-1, 2, 3)
@@ -780,12 +780,12 @@ def get_shear_matrix3d(
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 = 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)
+ sxy_tan = tan(sxy)
+ sxz_tan = tan(sxz)
+ syx_tan = tan(syx)
+ syz_tan = tan(syz)
+ szx_tan = tan(szx)
+ szy_tan = tan(szy)
# compute translation matrix
m00, m10, m20, m01, m11, m21, m02, m12, m22 = _compute_shear_matrix_3d(
@@ -811,7 +811,7 @@ def get_shear_matrix3d(
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 = torch.ones_like(sxy_tan)
+ 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
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 1c1001d38..29d007909 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -5,7 +5,7 @@ import math
import torch
import torch.nn.functional as F
-from kornia.core import Module, Tensor, pad, stack, tensor
+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
@@ -188,8 +188,8 @@ class ScalePyramid(Module):
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
- 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)]
+ 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)]
pyr = [[cur_level]]
oct_idx = 0
while True:
@@ -362,7 +362,7 @@ def build_laplacian_pyramid(
The function constructs a vector of images and builds the Laplacian pyramid
by recursively computing the difference after applying
- pyrUp to the adjacent layer in it's Gaussian pyramid.
+ pyrUp to the adjacent layer in its Gaussian pyramid.
See :cite:`burt1987laplacian` for more details.
@@ -424,7 +424,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 = torch.zeros(double_shape, device=x.device, dtype=x.dtype)
+ upscaled = 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 b644ebefe..b105db48b 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -3,6 +3,7 @@ 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
@@ -78,8 +79,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 = 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)
+ 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)
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)
@@ -90,7 +91,7 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
kernel_weights: torch.Tensor = weights[:, :-3]
affine_weights: torch.Tensor = weights[:, -3:]
- return (kernel_weights, affine_weights)
+ return kernel_weights, affine_weights
def warp_points_tps(
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
index ea71ee2f0..55d641c14 100755
--- a/kornia/nerf/camera_utils.py
+++ b/kornia/nerf/camera_utils.py
@@ -3,7 +3,7 @@ from typing import List, Tuple, Union
import torch
-from kornia.core import Device, Tensor
+from kornia.core import Device, Tensor, cos, sin, stack
from kornia.geometry.camera import PinholeCamera
from kornia.geometry.conversions import quaternion_to_rotation_matrix
@@ -142,10 +142,10 @@ def create_spiral_path(cameras: PinholeCamera, rad: float, num_views: int, num_c
mean_center = cameras.translation_vector.mean(0, False).squeeze(-1)
device = cameras.intrinsics.device
t = torch.linspace(0, 2 * math.pi * num_circles, num_views, device=device)
- cos_t = torch.cos(t) * rad
- sin_t = -torch.sin(t) * rad
- sin_05t = -torch.sin(0.5 * t) * rad
- translation_vector = torch.unsqueeze(mean_center, dim=0) + torch.stack((cos_t, sin_t, sin_05t)).permute((1, 0))
+ cos_t = cos(t) * rad
+ sin_t = -sin(t) * rad
+ sin_05t = -sin(0.5 * t) * rad
+ translation_vector = torch.unsqueeze(mean_center, dim=0) + stack((cos_t, sin_t, sin_05t)).permute((1, 0))
mean_intrinsics = cameras.intrinsics.mean(0, True).repeat(num_views, 1, 1)
mean_extrinsics = cameras.extrinsics.mean(0, True).repeat(num_views, 1, 1)
extrinsics = mean_extrinsics