Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Affine scale with non-isotropic values (#646)

shijianjian4be4445e4086
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 7466b6db7..fe7d822bb 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -403,8 +403,10 @@ class RandomAffine(AugmentationBase):
and vertical translations. For example translate=(a, b), then horizontal shift
is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
- scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ scale (tuple, optional): scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If (a, b, c, d), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d.
+ Will keep original scale by default.
shear (sequence or float, optional): Range of degrees to select from.
If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)
will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the
@@ -433,7 +435,7 @@ class RandomAffine(AugmentationBase):
def __init__(
self, 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]]] = 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,
return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False,
@@ -447,7 +449,16 @@ class RandomAffine(AugmentationBase):
self.translate = _range_bound(translate, 'translate', bounds=(0, 1), check='singular')
self.scale: Optional[torch.Tensor] = None
if scale is not None:
- self.scale = _range_bound(scale, 'scale', bounds=(0, float('inf')), check='singular')
+ scale = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)
+ if len(scale) == 2:
+ self.scale = _range_bound(scale, 'scale', bounds=(0, float('inf')), check='singular')
+ elif len(scale) == 4:
+ self.scale = torch.stack([
+ _range_bound(scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
+ _range_bound(scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular')
+ ])
+ else:
+ raise ValueError("'scale' expected to be either 2 or 4 elements. Got {scale}")
self.shear: Optional[torch.Tensor] = None
if shear is not None:
shear = shear if isinstance(shear, torch.Tensor) else torch.tensor(shear)
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 7c5b8ebee..b71b9b1db 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -209,8 +209,10 @@ class RandomAffine3D(AugmentationBase3D):
horizontal shift will be randomly sampled in the range -img_width * b < dy < img_width * b.
vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
Will not translate by default.
- scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ scale (tuple, optional): scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
+ c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
shear (sequence or float, optional): Range of degrees to select from.
If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be apllied.
If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
@@ -249,7 +251,8 @@ class RandomAffine3D(AugmentationBase3D):
self, degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
- scale: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]] = None,
shears: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float],
Tuple[float, float], Tuple[float, float]]] = None,
@@ -272,7 +275,13 @@ class RandomAffine3D(AugmentationBase3D):
self.scale: Optional[torch.Tensor] = None
if scale is not None:
self.scale = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)
- _singular_range_check(self.scale, 'scale', bounds=(0, float('inf')), mode='2d')
+ if self.scale.shape == torch.Size([2]):
+ self.scale = self.scale.unsqueeze(0).repeat(3, 1)
+ elif self.scale.shape != torch.Size([3, 2]):
+ raise ValueError("'scale' shall be either shape (2) or (3, 2). Got {self.scale}")
+ _singular_range_check(self.scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self.scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self.scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
self.resample: Resample = Resample.get(resample)
self.same_on_batch = same_on_batch
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index 89609d765..da387025e 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -186,10 +186,13 @@ def random_affine_generator(
# compute tensor ranges
if scale is not None:
- _joint_range_check(cast(torch.Tensor, scale), "scale")
- scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch)
+ _joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
+ scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).repeat(1, 2)
+ if len(scale) == 4:
+ _joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
+ scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
else:
- scale = torch.ones(batch_size)
+ scale = torch.ones((batch_size, 2))
if translate is not None:
_joint_range_check(cast(torch.Tensor, translate), "translate")
diff --git a/kornia/augmentation/random_generator3d.py b/kornia/augmentation/random_generator3d.py
index 7c0db1f65..ed003ab77 100644
--- a/kornia/augmentation/random_generator3d.py
+++ b/kornia/augmentation/random_generator3d.py
@@ -90,10 +90,14 @@ def random_affine_generator3d(
# compute tensor ranges
if scale is not None:
- assert scale.shape == torch.Size([2]), f"'scale' must be the shape of (2). Got {scale.shape}." # type: ignore
- scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch)
+ assert scale.shape == torch.Size([3, 2]), f"'scale' must be the shape of (3, 2). Got {scale.shape}."
+ scale = torch.cat([
+ _adapted_uniform((batch_size,), scale[0, 0], scale[0, 1], same_on_batch),
+ _adapted_uniform((batch_size,), scale[1, 0], scale[1, 1], same_on_batch),
+ _adapted_uniform((batch_size,), scale[2, 0], scale[2, 1], same_on_batch),
+ ], dim=1)
else:
- scale = torch.ones(batch_size)
+ scale = torch.ones(batch_size).repeat(1, 3)
if translate is not None:
assert translate.shape == torch.Size([3]), f"'translate' must be the shape of (2). Got {translate.shape}."
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 68b33211c..4768de47b 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -59,7 +59,7 @@ def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
def _compute_rotation_matrix(angle: torch.Tensor,
center: torch.Tensor) -> torch.Tensor:
"""Computes a pure affine rotation matrix."""
- scale: torch.Tensor = torch.ones_like(angle)
+ scale: torch.Tensor = torch.ones_like(center)
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
@@ -101,7 +101,7 @@ def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
def _compute_scaling_matrix(scale: torch.Tensor,
center: torch.Tensor) -> torch.Tensor:
"""Computes affine matrix for scaling."""
- angle: torch.Tensor = torch.zeros_like(scale)
+ angle: torch.Tensor = torch.zeros(scale.shape[:1])
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
@@ -305,6 +305,10 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
raise TypeError("Input scale_factor type is not a torch.Tensor. Got {}"
.format(type(scale_factor)))
+ if len(scale_factor.shape) == 1:
+ # convert isotropic scaling to x-y direction
+ scale_factor = scale_factor.repeat(1, 2)
+
# compute the tensor center
if center is None:
center = _compute_tensor_center(tensor)
@@ -312,7 +316,7 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
# compute the rotation matrix
# TODO: add broadcasting to get_rotation_matrix2d for center
center = center.expand(tensor.shape[0], -1)
- scale_factor = scale_factor.expand(tensor.shape[0])
+ scale_factor = scale_factor.expand(tensor.shape[0], 2)
scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)
# warp using the affine transform
@@ -590,7 +594,9 @@ class Scale(nn.Module):
Args:
scale_factor (torch.Tensor): The scale factor apply. The tensor
- must have a shape of (B), where B is batch size.
+ must have a shape of (B) or (B, 2), where B is batch size.
+ If (B), isotropic scaling will perform.
+ If (B, 2), x-y-direction specific scaling will perform.
center (torch.Tensor): The center through which to scale. The tensor
must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 87a58b2cc..e65dc5633 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -307,20 +307,20 @@ def get_rotation_matrix2d(
angle (Tensor): rotation angle in degrees. Positive values mean
counter-clockwise rotation (the coordinate origin is assumed to
be the top-left corner).
- scale (Tensor): isotropic scale factor.
+ scale (Tensor): scale factor for x, y scaling with shape :math:`(B, 2)`
Returns:
Tensor: the affine matrix of 2D rotation.
Shape:
- - Input: :math:`(B, 2)`, :math:`(B)` and :math:`(B)`
+ - Input: :math:`(B, 2)`, :math:`(B)` and :math:`(B, 2)`
- Output: :math:`(B, 2, 3)`
Example:
>>> center = torch.zeros(1, 2)
- >>> scale = torch.ones(1)
+ >>> scale = torch.ones((1, 2))
>>> angle = 45. * torch.ones(1)
- >>> M = kornia.get_rotation_matrix2d(center, angle, scale)
+ >>> get_rotation_matrix2d(center, angle, scale)
tensor([[[ 0.7071, 0.7071, 0.0000],
[-0.7071, 0.7071, 0.0000]]])
"""
@@ -339,14 +339,17 @@ def get_rotation_matrix2d(
if not len(angle.shape) == 1:
raise ValueError("Input angle must be a B tensor. Got {}"
.format(angle.shape))
- if not len(scale.shape) == 1:
- raise ValueError("Input scale must be a B tensor. Got {}"
+ if not (len(scale.shape) == 2 and scale.shape[1] == 2):
+ raise ValueError("Input scale must be a Bx2 tensor. Got {}"
.format(scale.shape))
if not (center.shape[0] == angle.shape[0] == scale.shape[0]):
raise ValueError("Inputs must have same batch size dimension. Got center {}, angle {} and scale {}"
.format(center.shape, angle.shape, scale.shape))
# convert angle and apply scale
- scaled_rotation: torch.Tensor = angle_to_rotation_matrix(angle) * scale.view(-1, 1, 1)
+ rotation_matrix: torch.Tensor = angle_to_rotation_matrix(angle)
+ scaling_matrix: torch.Tensor = torch.zeros((2, 2)).fill_diagonal_(1).repeat(rotation_matrix.size(0), 1, 1)
+ scaling_matrix = scaling_matrix * scale.unsqueeze(dim=2).repeat(1, 1, 2)
+ scaled_rotation: torch.Tensor = rotation_matrix @ scaling_matrix.to(rotation_matrix)
alpha: torch.Tensor = scaled_rotation[:, 0, 0]
beta: torch.Tensor = scaled_rotation[:, 0, 1]
@@ -463,7 +466,7 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:
Args:
translations (torch.Tensor): tensor containing the translation vector with shape :math:`(B, 2)`.
center (torch.Tensor): tensor containing the center vector with shape :math:`(B, 2)`.
- scale (torch.Tensor): tensor containing the scale factor with shape :math:`(B)`.
+ scale (torch.Tensor): tensor containing the scale factor with shape :math:`(B, 2)`.
sx (torch.Tensor, optional): tensor containing the shear factor in the x-direction with shape :math:`(B)`.
sy (torch.Tensor, optional): tensor containing the shear factor in the y-direction with shape :math:`(B)`.
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index c58cda2cc..6aa9e50db 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -97,7 +97,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
angles (torch.Tensor): angle axis 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.
- scales (torch.Tensor): isotropic scale factor.
+ scales (torch.Tensor): scale factor for x-y-z-directions with shape :math:`(B, 3)`.
Returns:
torch.Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.
@@ -110,7 +110,10 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
# create rotation matrix
angle_axis_rad: torch.Tensor = K.deg2rad(angles)
- rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) * scales.view(-1, 1, 1) # Bx3x3
+ rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3
+ scaling_matrix: torch.Tensor = K.eye_like(3, rmat)
+ scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)
+ rmat = rmat @ scaling_matrix.to(rmat)
# define matrix to move forth and back to origin
from_origin_mat = torch.eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index ee77be868..6e05a56b9 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.utils import one_hot
+from kornia.utils.one_hot import one_hot
# based on:
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 61464ae36..84e95495e 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.utils import one_hot
+from kornia.utils.one_hot import one_hot
# based on:
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 089a7faa2..9991a73ca 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.utils import one_hot
+from kornia.utils.one_hot import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index 9b3a1598e..193880d66 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -1,6 +1,7 @@
-from typing import Optional
+from typing import Optional, Union
import torch
+import kornia as K
def create_meshgrid(
@@ -25,15 +26,19 @@ def create_meshgrid(
Return:
torch.Tensor: returns a grid tensor with shape :math:`(1, H, W, 2)`.
"""
- # generate coordinates
- xs: Optional[torch.Tensor] = None
- ys: Optional[torch.Tensor] = None
+ xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=torch.float)
+ ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=torch.float)
+ # Fix TracerWarning
+ # Note: normalize_pixel_coordinates still gots TracerWarning since new width and height
+ # tensors will be generated.
+ # Below is the code using normalize_pixel_coordinates:
+ # base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys]), dim=2)
+ # if normalized_coordinates:
+ # base_grid = K.geometry.normalize_pixel_coordinates(base_grid, height, width)
+ # return torch.unsqueeze(base_grid.transpose(0, 1), dim=0)
if normalized_coordinates:
- xs = torch.linspace(-1, 1, width, device=device, dtype=torch.float)
- ys = torch.linspace(-1, 1, height, device=device, dtype=torch.float)
- else:
- xs = torch.linspace(0, width - 1, width, device=device, dtype=torch.float)
- ys = torch.linspace(0, height - 1, height, device=device, dtype=torch.float)
+ xs = (xs / (width - 1) - 0.5) * 2
+ ys = (ys / (height - 1) - 0.5) * 2
# generate grid by stacking coordinates
base_grid: torch.Tensor = torch.stack(
torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
@@ -64,17 +69,14 @@ def create_meshgrid3d(
Return:
torch.Tensor: returns a grid tensor with shape :math:`(1, D, H, W, 3)`.
"""
- xs: Optional[torch.Tensor] = None
- ys: Optional[torch.Tensor] = None
- zs: Optional[torch.Tensor] = None
+ xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=torch.float)
+ ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=torch.float)
+ zs: torch.Tensor = torch.linspace(0, depth - 1, depth, device=device, dtype=torch.float)
+ # Fix TracerWarning
if normalized_coordinates:
- xs = torch.linspace(-1, 1, width, device=device, dtype=torch.float)
- ys = torch.linspace(-1, 1, height, device=device, dtype=torch.float)
- zs = torch.linspace(-1, 1, depth, device=device, dtype=torch.float)
- else:
- xs = torch.linspace(0, width - 1, width, device=device, dtype=torch.float)
- ys = torch.linspace(0, height - 1, height, device=device, dtype=torch.float)
- zs = torch.linspace(0, depth - 1, depth, device=device, dtype=torch.float)
+ xs = (xs / (width - 1) - 0.5) * 2
+ ys = (ys / (height - 1) - 0.5) * 2
+ zs = (ys / (height - 1) - 0.5) * 2
# generate grid by stacking coordinates
base_grid: torch.Tensor = torch.stack(
torch.meshgrid([zs, xs, ys])).transpose(1, 2) # 3xHxW
diff --git a/test/geometry/test_projwarp.py b/test/geometry/test_projwarp.py
index 663260f0a..68b1e2131 100644
--- a/test/geometry/test_projwarp.py
+++ b/test/geometry/test_projwarp.py
@@ -80,7 +80,7 @@ class TestWarpProjective:
angles = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angles[:, 0])
+ scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_projective(input, P, (3, 3, 3))
assert_allclose(output, expected)
@@ -120,7 +120,7 @@ class TestWarpProjective:
angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angles[:, 0])
+ scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_projective(input, P, (3, 3, 3))
assert_allclose(output, expected)
@@ -160,7 +160,7 @@ class TestWarpProjective:
angles = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angles[:, 0])
+ scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_projective(input, P, (3, 3, 3))
assert_allclose(output, expected)
@@ -225,7 +225,7 @@ class TestWarpProjective:
angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angles[:, 0])
+ scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_projective(input, P, (3, 3, 3))
assert_allclose(output, expected)
@@ -235,7 +235,7 @@ class TestGetRotationMatrix3d:
def test_smoke(self, device, dtype):
center = torch.rand(1, 3, device=device, dtype=dtype)
angle = torch.rand(1, 3, device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
assert P.shape == (1, 3, 4)
@@ -244,14 +244,14 @@ class TestGetRotationMatrix3d:
B: int = batch_size
center = torch.rand(B, 3, device=device, dtype=dtype)
angle = torch.rand(B, 3, device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
assert P.shape == (B, 3, 4)
def test_identity(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
angle = torch.zeros(1, 3, device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
P_expected = torch.tensor([
[1., 0., 0., 0.],
@@ -263,7 +263,7 @@ class TestGetRotationMatrix3d:
def test_rot90x(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
angle = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
P_expected = torch.tensor([
[1., 0., 0., 0.],
@@ -275,7 +275,7 @@ class TestGetRotationMatrix3d:
def test_rot90y(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
angle = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
P_expected = torch.tensor([
[0., 0., 1., 0.],
@@ -287,7 +287,7 @@ class TestGetRotationMatrix3d:
def test_rot90z(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
angle = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
P = proj.get_projective_transform(center, angle, scales)
P_expected = torch.tensor([
[0., -1., 0., 0.],
@@ -300,5 +300,5 @@ class TestGetRotationMatrix3d:
# generate input data
center = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=True)
angle = torch.rand(1, 3, device=device, dtype=torch.float64)
- scales: torch.Tensor = torch.ones_like(angle[:, 0])
+ scales: torch.Tensor = torch.ones_like(angle)
assert gradcheck(proj.get_projective_transform, (center, angle, scales), raise_exception=True)
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index 54b9228bb..a82fa3566 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -269,7 +269,7 @@ class TestScale:
[0., 0., 0., 0.]
]]).to(device)
# prepare transformation
- scale_factor = torch.tensor([2.]).to(device)
+ scale_factor = torch.tensor([[2., 2.]]).to(device)
transform = kornia.Scale(scale_factor)
assert_allclose(transform(inp).sum().item(), 12.25)
@@ -288,7 +288,7 @@ class TestScale:
[0., 0., 0., 0.]
]]).to(device)
# prepare transformation
- scale_factor = torch.tensor([0.5]).to(device)
+ scale_factor = torch.tensor([[0.5, 0.5]]).to(device)
transform = kornia.Scale(scale_factor)
assert_allclose(transform(inp), expected)
@@ -307,7 +307,7 @@ class TestScale:
[0., 0., 0., 0.]
]]).to(device)
# prepare transformation
- scale_factor = torch.tensor([0.5, 0.5]).to(device)
+ scale_factor = torch.tensor([[0.5, 0.5]]).to(device)
transform = kornia.Scale(scale_factor)
assert_allclose(transform(inp), expected)
@@ -326,13 +326,13 @@ class TestScale:
[0., 0., 0., 0.]
]]).to(device)
# prepare transformation
- scale_factor = torch.tensor([0.5]).to(device)
+ scale_factor = torch.tensor([[0.5, 0.5]]).to(device)
transform = kornia.Scale(scale_factor)
assert_allclose(transform(inp), expected)
def test_gradcheck(self, device):
# test parameters
- scale_factor = torch.tensor([0.5]).to(device)
+ scale_factor = torch.tensor([[0.5, 0.5]]).to(device)
scale_factor = utils.tensor_to_gradcheck_var(
scale_factor, requires_grad=False) # to var
@@ -345,7 +345,7 @@ class TestScale:
@pytest.mark.skip('Need deep look into it since crashes everywhere.')
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
- scale_factor = torch.tensor([0.5]).to(device)
+ scale_factor = torch.tensor([[0.5, 0.5]]).to(device)
batch_size, channels, height, width = 2, 3, 64, 64
img = torch.ones(batch_size, channels, height, width).to(device)
trans = kornia.Scale(scale_factor)
@@ -564,7 +564,7 @@ class TestAffine2d:
import math
batch_size, ch, height, width = 1, 1, 96, 96
angle, translations = 6.971339922894188, (0.0, -4.0)
- scale, shear = 0.7785685905190581, [11.8235607082617, 7.06797949691645]
+ scale, shear = [0.7785685905190581, 0.7785685905190581], [11.8235607082617, 7.06797949691645]
matrix_expected = T([[1.27536969, 4.26828945e-01, -3.2876e+01],
[2.18297196e-03, 1.29424165e+00, -1.1717e+01]])
center = T([float(width), float(height)]).view(1, 2) / 2. + 0.5
@@ -572,7 +572,7 @@ class TestAffine2d:
matrix_kornia = kornia.get_affine_matrix2d(
T(translations).view(-1, 2),
center,
- T([scale]).view(-1),
+ T([scale]).view(-1, 2),
T([angle]).view(-1),
T([math.radians(shear[0])]).view(-1, 1),
T([math.radians(shear[1])]).view(-1, 1))
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index ae338909b..46dade6ca 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -88,7 +88,7 @@ def test_rotation_matrix2d(batch_size, device):
# generate input data
center_base = torch.zeros(batch_size, 2).to(device)
angle_base = torch.ones(batch_size).to(device)
- scale_base = torch.ones(batch_size).to(device)
+ scale_base = torch.ones(batch_size, 2).to(device)
# 90 deg rotation
center = center_base
@@ -417,7 +417,7 @@ class TestInvertAffineTransform:
def test_rot90(self, device):
angle = torch.tensor([90.]).to(device)
- scale = torch.tensor([1.]).to(device)
+ scale = torch.tensor([[1., 1.]]).to(device)
center = torch.tensor([[0., 0.]]).to(device)
expected = torch.tensor([[
[0., -1., 0.],
@@ -429,7 +429,7 @@ class TestInvertAffineTransform:
def test_rot90_batch(self, device):
angle = torch.tensor([90.]).to(device)
- scale = torch.tensor([1.]).to(device)
+ scale = torch.tensor([[1., 1.]]).to(device)
center = torch.tensor([[0., 0.]]).to(device)
expected = torch.tensor([[
[0., -1., 0.],