Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Expose align_corners everywhere, where interpolation occurs (#546)

Dmytro Mishkine5a3ad7661df
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 412e8b8fd..a950eae78 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -95,10 +95,12 @@ class RandomHorizontalFlip(AugmentationBase):
"""
- def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:
+ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False) -> None:
super(RandomHorizontalFlip, self).__init__(return_transform)
self.p: float = p
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(p={self.p}, return_transform={self.return_transform}, same_on_batch={self.same_on_batch})"
@@ -303,13 +305,15 @@ class RandomPerspective(AugmentationBase):
def __init__(
self, distortion_scale: float = 0.5, p: float = 0.5,
interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False
) -> None:
super(RandomPerspective, self).__init__(return_transform)
self.p: float = p
self.distortion_scale: float = distortion_scale
self.interpolation: Resample = Resample.get(interpolation)
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(distortion_scale={self.distortion_scale}, p={self.p}, interpolation={self.interpolation.name}, "
@@ -319,7 +323,7 @@ class RandomPerspective(AugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_perspective_generator(
batch_shape[0], batch_shape[-2], batch_shape[-1], self.p, self.distortion_scale,
- self.interpolation, self.same_on_batch)
+ self.interpolation, self.same_on_batch, self.align_corners)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_perspective_transformation(input, params)
@@ -361,7 +365,8 @@ class RandomAffine(AugmentationBase):
def __init__(
self, degrees: UnionFloat, translate: Optional[TupleFloat] = None, scale: Optional[TupleFloat] = None,
shear: Optional[UnionFloat] = None, resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False
) -> None:
super(RandomAffine, self).__init__(return_transform)
self.degrees = degrees
@@ -370,6 +375,7 @@ class RandomAffine(AugmentationBase):
self.shear = shear
self.resample: Resample = Resample.get(resample)
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "
@@ -379,7 +385,7 @@ class RandomAffine(AugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_affine_generator(
batch_shape[0], batch_shape[-2], batch_shape[-1], self.degrees, self.translate, self.scale, self.shear,
- self.resample, self.same_on_batch)
+ self.resample, self.same_on_batch, self.align_corners)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_affine_transformation(input, params)
@@ -458,12 +464,13 @@ class RandomRotation(AugmentationBase):
# Note: Extra params, center=None, fill=0 in TorchVision
def __init__(
self, degrees: FloatUnionType, interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False
) -> None:
super(RandomRotation, self).__init__(return_transform)
self.degrees = degrees
self.interpolation: Resample = Resample.get(interpolation)
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(degrees={self.degrees}, interpolation={self.interpolation.name}, "
@@ -471,7 +478,8 @@ class RandomRotation(AugmentationBase):
return self.__class__.__name__ + repr
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_rotation_generator(batch_shape[0], self.degrees, self.interpolation, self.same_on_batch)
+ return rg.random_rotation_generator(batch_shape[0], self.degrees, self.interpolation,
+ self.same_on_batch, self.align_corners)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_rotate_tranformation(input, params)
@@ -504,7 +512,8 @@ class RandomCrop(AugmentationBase):
def __init__(
self, size: Tuple[int, int], padding: Optional[BoarderUnionType] = None, pad_if_needed: Optional[bool] = False,
- fill: int = 0, padding_mode: str = 'constant', return_transform: bool = False, same_on_batch: bool = False
+ fill: int = 0, padding_mode: str = 'constant', return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False
) -> None:
super(RandomCrop, self).__init__(return_transform)
self.size = size
@@ -513,6 +522,7 @@ class RandomCrop(AugmentationBase):
self.fill = fill
self.padding_mode = padding_mode
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(crop_size={self.size}, padding={self.padding}, fill={self.fill}, "
@@ -522,7 +532,7 @@ class RandomCrop(AugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), self.size,
- same_on_batch=self.same_on_batch)
+ same_on_batch=self.same_on_batch, align_corners=self.align_corners)
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
if self.padding is not None:
@@ -576,7 +586,8 @@ class RandomResizedCrop(AugmentationBase):
self, size: Tuple[int, int], scale: Tuple[float, float] = (0.08, 1.0),
ratio: Tuple[float, float] = (1.75, 4. / 3.),
interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False
) -> None:
super(RandomResizedCrop, self).__init__(return_transform)
self.size = size
@@ -584,6 +595,7 @@ class RandomResizedCrop(AugmentationBase):
self.ratio = ratio
self.interpolation: Resample = Resample.get(interpolation)
self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
def __repr__(self) -> str:
repr = f"(size={self.size}, resize_to={self.scale}, resize_to={self.ratio}, "
@@ -595,7 +607,8 @@ class RandomResizedCrop(AugmentationBase):
target_size = rg.random_crop_size_generator(self.size, self.scale, self.ratio)
_target_size = (int(target_size[0].data.item()), int(target_size[1].data.item()))
return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), _target_size,
- resize_to=self.size, same_on_batch=self.same_on_batch)
+ resize_to=self.size, same_on_batch=self.same_on_batch,
+ align_corners=self.align_corners)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_crop_transformation(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 4e05c05a7..e88d47f6d 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -413,8 +413,10 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> t
# apply the computed transform
height, width = x_data.shape[-2:]
resample_name = Resample(params['interpolation'].item()).name.lower()
- out_data[mask] = warp_perspective(x_data[mask], transform[mask], (height, width), flags=resample_name)
-
+ out_data[mask] = warp_perspective(x_data[mask], transform[mask], # type: ignore
+ (height, width),
+ flags=resample_name,
+ align_corners=params['align_corners'])
return out_data.view_as(input)
@@ -469,8 +471,9 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.
resample_name = Resample(params['resample'].item()).name.lower()
- out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :], (height, width), resample_name)
-
+ out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :], # type: ignore
+ (height, width), resample_name,
+ align_corners=params['align_corners'])
return out_data.view_as(input)
@@ -499,8 +502,9 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
angles: torch.Tensor = params["degrees"].type_as(input)
- transformed: torch.Tensor = rotate(
- input, angles, mode=Resample(params['interpolation'].item()).name.lower())
+ transformed: torch.Tensor = rotate( # type: ignore
+ input, angles, mode=Resample(params['interpolation'].item()).name.lower(),
+ align_corners=params['align_corners'])
return transformed
@@ -537,12 +541,12 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Te
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
- return crop_by_boxes(
+ return crop_by_boxes( # type: ignore
input,
params['src'],
params['dst'],
Resample.get(params['interpolation'].item()).name.lower(), # type: ignore
- )
+ align_corners=params['align_corners'])
def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]):
@@ -592,7 +596,6 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])
mask[i_elem, :, int(y):int(y + w), int(x):int(x + h)] = 1.
values[i_elem, :, int(y):int(y + w), int(x):int(x + h)] = v
transformed = torch.where(mask == 1., values, input)
-
return transformed
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index 81a2cba8d..e36bf4489 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -114,7 +114,8 @@ def _get_perspective_params(batch_size: int, width: int, height: int, distortion
def random_perspective_generator(
batch_size: int, height: int, width: int, p: float, distortion_scale: float,
- interpolation: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False
+ interpolation: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False,
+ align_corners: bool = False,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
@@ -126,6 +127,9 @@ def random_perspective_generator(
distortion_scale (float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
+ align_corners(bool): interpolation flag. Default: False.See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+
Returns:
List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
@@ -139,6 +143,7 @@ def random_perspective_generator(
params['start_points'] = start_points
params['end_points'] = end_points
params['interpolation'] = torch.tensor(Resample.get(interpolation).value)
+ params['align_corners'] = align_corners # type: ignore
return params
@@ -151,7 +156,8 @@ def random_affine_generator(
scale: Optional[TupleFloat] = None,
shear: Optional[UnionFloat] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ same_on_batch: bool = False,
+ align_corners: bool = False) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``affine`` for a random affine transform.
Args:
@@ -175,6 +181,9 @@ def random_affine_generator(
Will not apply shear by default
resample (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
+ align_corners(bool): interpolation flag. Default: False.See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+
"""
# check angle ranges
degrees_tmp: TupleFloat
@@ -218,12 +227,13 @@ def random_affine_generator(
shear_tmp = shear
return _get_random_affine_params(
- batch_size, height, width, degrees_tmp, translate, scale, shear_tmp, resample, same_on_batch)
+ batch_size, height, width, degrees_tmp, translate, scale, shear_tmp, resample, same_on_batch, align_corners)
def random_rotation_generator(batch_size: int, degrees: FloatUnionType,
interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,
- same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ same_on_batch: bool = False,
+ align_corners: bool = False) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
Args:
@@ -232,6 +242,7 @@ def random_rotation_generator(batch_size: int, degrees: FloatUnionType,
range of degrees to select from will be (-degrees, +degrees)
interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
+ align_corners (bool): interpolation flag. Default: False.
"""
if not torch.is_tensor(degrees):
if isinstance(degrees, (float, int)):
@@ -253,17 +264,18 @@ def random_rotation_generator(batch_size: int, degrees: FloatUnionType,
degrees = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
- return dict(
+ return dict( # type: ignore
degrees=degrees,
- interpolation=torch.tensor(Resample.get(interpolation).value)
- )
+ interpolation=torch.tensor(Resample.get(interpolation).value),
+ align_corners=align_corners)
def _get_random_affine_params(
batch_size: int, height: int, width: int,
degrees: TupleFloat, translate: Optional[TupleFloat],
scales: Optional[TupleFloat], shears: Optional[TupleFloat],
- resample: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False,
+ align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```affine``` transformation random affine transform.
The returned matrix is Bx3x3.
@@ -297,20 +309,22 @@ def _get_random_affine_params(
sy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
else:
sx = sy = torch.tensor([0] * batch_size)
- return dict(
+ return dict( # type: ignore
translations=translations,
center=center,
scale=scale,
angle=angle,
sx=sx,
sy=sy,
- resample=torch.tensor(Resample.get(resample).value)
+ resample=torch.tensor(Resample.get(resample).value),
+ align_corners=align_corners
)
def random_crop_generator(
batch_size: int, input_size: Tuple[int, int], size: Tuple[int, int], resize_to: Optional[Tuple[int, int]] = None,
- interpolation: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False
+ interpolation: Union[str, int, Resample] = Resample.BILINEAR.name, same_on_batch: bool = False,
+ align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
Args:
@@ -320,7 +334,8 @@ def random_crop_generator(
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
- """
+ align_corners (bool): interpolation flag. Default: False.
+ """
x_diff = input_size[1] - size[1]
y_diff = input_size[0] - size[0]
@@ -352,7 +367,9 @@ def random_crop_generator(
[0, resize_to[0] - 1],
]]).repeat(batch_size, 1, 1)
- return {'src': crop_src, 'dst': crop_dst, 'interpolation': torch.tensor(Resample.get(interpolation).value)}
+ return {'src': crop_src, 'dst': crop_dst, # type: ignore
+ 'interpolation': torch.tensor(Resample.get(interpolation).value),
+ 'align_corners': align_corners}
def random_crop_size_generator(size: Tuple[int, int], scale: Tuple[float, float], ratio: Tuple[float, float],
@@ -438,7 +455,8 @@ def random_rectangles_params_generator(batch_size: int, height: int, width: int,
def center_crop_params_generator(batch_size: int, height: int, width: int,
- size: Tuple[int, int]) -> Dict[str, torch.Tensor]:
+ size: Tuple[int, int],
+ align_corners: bool = False) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
Args:
batch_size (int): the tensor batch size.
@@ -483,4 +501,5 @@ def center_crop_params_generator(batch_size: int, height: int, width: int,
[dst_w - 1, dst_h - 1],
[0, dst_h - 1],
]]).expand(points_src.shape[0], -1, -1)
- return {'src': points_src, 'dst': points_dst, 'interpolation': torch.tensor(Resample.BILINEAR.value)}
+ return {'src': points_src, 'dst': points_dst, # type: ignore
+ 'interpolation': torch.tensor(Resample.BILINEAR.value), 'align_corners': align_corners}
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 582f9383b..557e314bd 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -391,7 +391,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,
LAF_renorm = denormalize_laf(LAF, img)
grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), # type: ignore
- [B * N, ch, PS, PS], align_corners=True)
+ [B * N, ch, PS, PS], align_corners=False)
grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w) - 1.0
grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h) - 1.0
return grid
@@ -425,7 +425,7 @@ def extract_patches_simple(img: torch.Tensor,
for i in range(B):
grid = generate_patch_grid_from_normalized_LAF(img[i:i + 1], nlaf[i:i + 1], PS).to(img.device)
out.append(F.grid_sample(img[i:i + 1].expand(grid.size(0), ch, h, w), grid, # type: ignore
- padding_mode="border", align_corners=True))
+ padding_mode="border", align_corners=False))
return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
@@ -470,7 +470,7 @@ def extract_patches_from_pyramid(img: torch.Tensor,
nlaf[i:i + 1, scale_mask, :, :],
PS)
patches = F.grid_sample(cur_img[i:i + 1].expand(grid.size(0), ch, h, w), grid, # type: ignore
- padding_mode="border", align_corners=True)
+ padding_mode="border", align_corners=False)
out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)
cur_img = kornia.pyrdown(cur_img)
cur_pyr_level += 1
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 4b34b21fc..8d7a476f7 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -46,7 +46,7 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> tor
# Finally, interpolate the scale value
scale_val = F.grid_sample( # type: ignore
sigmas[0].log2().view(1, 1, 1, -1).expand(scale_grid.size(0), 1, 1, L),
- scale_grid, align_corners=True)
+ scale_grid, align_corners=False)
# Replace the scale_x_y
out = torch.cat([torch.pow(2.0, scale_val).view(B, N, 1), max_coords[:, :, 1:]], dim=2)
@@ -56,7 +56,7 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> tor
def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:
"""Downsamples a mask based on the given octave shape."""
mask_shape = octave_shape[-2:]
- mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=True) # type: ignore
+ mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=False) # type: ignore
return mask_octave.unsqueeze(1)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 27d81ed07..4103d94d2 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -77,13 +77,16 @@ def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
# based on:
# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L166
-def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear') -> torch.Tensor:
+def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',
+ align_corners: bool = False) -> torch.Tensor:
r"""Apply an affine transformation to the image.
Args:
tensor (torch.Tensor): The image tensor to be warped.
matrix (torch.Tensor): The 2x3 affine transformation matrix.
mode (str): 'bilinear' | 'nearest'
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The warped image.
@@ -100,7 +103,8 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear') -
# warp the input tensor
height: int = tensor.shape[-2]
width: int = tensor.shape[-1]
- warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode)
+ warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode,
+ align_corners=align_corners)
# return in the original shape
if is_unbatched:
@@ -113,7 +117,8 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear') -
# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L185
def rotate(tensor: torch.Tensor, angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None, mode: str = 'bilinear') -> torch.Tensor:
+ center: Union[None, torch.Tensor] = None, mode: str = 'bilinear',
+ align_corners: bool = False) -> torch.Tensor:
r"""Rotate the image anti-clockwise about the centre.
See :class:`~kornia.Rotate` for details.
@@ -142,10 +147,11 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,
rotation_matrix: torch.Tensor = _compute_rotation_matrix(angle, center)
# warp using the affine transform
- return affine(tensor, rotation_matrix[..., :2, :3], mode)
+ return affine(tensor, rotation_matrix[..., :2, :3], mode, align_corners)
-def translate(tensor: torch.Tensor, translation: torch.Tensor) -> torch.Tensor:
+def translate(tensor: torch.Tensor, translation: torch.Tensor,
+ align_corners: bool = False) -> torch.Tensor:
r"""Translate the tensor in pixel units.
See :class:`~kornia.Translate` for details.
@@ -164,11 +170,12 @@ def translate(tensor: torch.Tensor, translation: torch.Tensor) -> torch.Tensor:
translation_matrix: torch.Tensor = _compute_translation_matrix(translation)
# warp using the affine transform
- return affine(tensor, translation_matrix[..., :2, :3])
+ return affine(tensor, translation_matrix[..., :2, :3], align_corners=align_corners)
def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None) -> torch.Tensor:
+ center: Union[None, torch.Tensor] = None,
+ align_corners: bool = False) -> torch.Tensor:
r"""Scales the input image.
See :class:`~kornia.Scale` for details.
@@ -191,10 +198,10 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)
# warp using the affine transform
- return affine(tensor, scaling_matrix[..., :2, :3])
+ return affine(tensor, scaling_matrix[..., :2, :3], align_corners=align_corners)
-def shear(tensor: torch.Tensor, shear: torch.Tensor) -> torch.Tensor:
+def shear(tensor: torch.Tensor, shear: torch.Tensor, align_corners: bool = False) -> torch.Tensor:
r"""Shear the tensor.
See :class:`~kornia.Shear` for details.
@@ -213,10 +220,11 @@ def shear(tensor: torch.Tensor, shear: torch.Tensor) -> torch.Tensor:
shear_matrix: torch.Tensor = _compute_shear_matrix(shear)
# warp using the affine transform
- return affine(tensor, shear_matrix[..., :2, :3])
+ return affine(tensor, shear_matrix[..., :2, :3], align_corners=align_corners)
-def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]], interpolation: str = 'bilinear') -> torch.Tensor:
+def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],
+ interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
r"""Resize the input torch.Tensor to the given size.
See :class:`~kornia.Resize` for details.
@@ -240,8 +248,7 @@ def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]], interpolation
new_size = (ow, oh)
else:
new_size = size
-
- return torch.nn.functional.interpolate(input, size=new_size, mode=interpolation, align_corners=True)
+ return torch.nn.functional.interpolate(input, size=new_size, mode=interpolation, align_corners=align_corners)
class Resize(nn.Module):
@@ -254,18 +261,21 @@ class Resize(nn.Module):
to (size * height / width, size)
interpolation (str): algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' |
'bicubic' | 'trilinear' | 'area'. Default: 'bilinear'.
-
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The resized tensor.
"""
- def __init__(self, size: Union[int, Tuple[int, int]], interpolation: str = 'bilinear') -> None:
+ def __init__(self, size: Union[int, Tuple[int, int]], interpolation: str = 'bilinear',
+ align_corners: bool = False) -> None:
super(Resize, self).__init__()
self.size: Union[int, Tuple[int, int]] = size
self.interpolation: str = interpolation
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return resize(input, self.size, self.interpolation)
+ return resize(input, self.size, self.interpolation, align_corners=self.align_corners)
class Rotate(nn.Module):
@@ -277,18 +287,22 @@ class Rotate(nn.Module):
center (torch.Tensor): The center through which to rotate. The tensor
must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The rotated tensor.
"""
def __init__(self, angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None) -> None:
+ center: Union[None, torch.Tensor] = None,
+ align_corners: bool = False) -> None:
super(Rotate, self).__init__()
self.angle: torch.Tensor = angle
self.center: Union[None, torch.Tensor] = center
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return rotate(input, self.angle, self.center)
+ return rotate(input, self.angle, self.center, align_corners=self.align_corners)
class Translate(nn.Module):
@@ -298,17 +312,19 @@ class Translate(nn.Module):
translation (torch.Tensor): 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.
-
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The translated tensor.
"""
- def __init__(self, translation: torch.Tensor) -> None:
+ def __init__(self, translation: torch.Tensor, align_corners: bool = False) -> None:
super(Translate, self).__init__()
self.translation: torch.Tensor = translation
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return translate(input, self.translation)
+ return translate(input, self.translation, self.align_corners)
class Scale(nn.Module):
@@ -320,19 +336,22 @@ class Scale(nn.Module):
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.
-
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The scaled tensor.
"""
def __init__(self, scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None) -> None:
+ center: Union[None, torch.Tensor] = None,
+ align_corners: bool = False) -> None:
super(Scale, self).__init__()
self.scale_factor: torch.Tensor = scale_factor
self.center: Union[None, torch.Tensor] = center
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return scale(input, self.scale_factor, self.center)
+ return scale(input, self.scale_factor, self.center, self.align_corners)
class Shear(nn.Module):
@@ -343,14 +362,17 @@ class Shear(nn.Module):
shear (torch.Tensor): 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.
-
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: The skewed tensor.
"""
- def __init__(self, shear: torch.Tensor) -> None:
+ def __init__(self, shear: torch.Tensor,
+ align_corners: bool = False) -> None:
super(Shear, self).__init__()
self.shear: torch.Tensor = shear
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return shear(input, self.shear)
+ return shear(input, self.shear, self.align_corners)
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.py
index f04076837..bc07e60c0 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop.py
@@ -14,7 +14,7 @@ __all__ = [
def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],
- interpolation: str = 'bilinear') -> torch.Tensor:
+ interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
r"""Extracts crops from the input tensor and resizes them.
Args:
tensor (torch.Tensor): the reference tensor of shape BxCxHxW.
@@ -25,6 +25,8 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
coordinates must be in the x, y order.
size (Tuple[int, int]): a tuple with the height and width that will be
used to resize the extracted patches.
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
Returns:
torch.Tensor: tensor containing the patches with shape BxN1xN2
Example:
@@ -73,10 +75,12 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
[0, dst_h - 1],
]], device=tensor.device).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src, points_dst, interpolation)
+ return crop_by_boxes(tensor, points_src, points_dst, interpolation, align_corners)
-def center_crop(tensor: torch.Tensor, size: Tuple[int, int], interpolation: str = 'bilinear') -> torch.Tensor:
+def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
+ interpolation: str = 'bilinear',
+ align_corners: bool = True) -> torch.Tensor:
r"""Crops the given tensor at the center.
Args:
@@ -84,7 +88,8 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int], interpolation: str
(B, C, H, W).
size (Tuple[int, int]): a tuple with the expected height and width
of the output patch.
-
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
Returns:
torch.Tensor: the output tensor with patches.
@@ -143,10 +148,16 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int], interpolation: str
[dst_w - 1, dst_h - 1],
[0, dst_h - 1],
]], device=tensor.device).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src.to(tensor.dtype), points_dst.to(tensor.dtype), interpolation)
+ return crop_by_boxes(tensor,
+ points_src.to(tensor.dtype),
+ points_dst.to(tensor.dtype),
+ interpolation,
+ align_corners)
-def crop_by_boxes(tensor, src_box, dst_box, interpolation: str = 'bilinear') -> torch.Tensor:
+def crop_by_boxes(tensor, src_box, dst_box,
+ interpolation: str = 'bilinear',
+ align_corners: bool = False) -> torch.Tensor:
"""A wrapper performs crop transform with bounding boxes.
Note:
@@ -169,7 +180,7 @@ def crop_by_boxes(tensor, src_box, dst_box, interpolation: str = 'bilinear') ->
bbox = _infer_bounding_box(dst_box)
patches: torch.Tensor = warp_affine(
tensor, dst_trans_src[:, :2, :], (int(bbox[0].int().data.item()), int(bbox[1].int().data.item())),
- flags=interpolation)
+ flags=interpolation, align_corners=align_corners)
# return in the original shape
if is_unbatched:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 87146e666..ad4440ed9 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -27,18 +27,20 @@ __all__ = [
def transform_warp_impl(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,
dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int],
- grid_mode: str, padding_mode: str) -> torch.Tensor:
+ grid_mode: str, padding_mode: str,
+ align_corners: bool) -> torch.Tensor:
"""Compute the transform in normalized cooridnates and perform the warping.
"""
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
dst_pix_trans_src_pix, dsize_src, dsize_dst)
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
- return homography_warp(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode)
+ return homography_warp(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners)
def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
- flags: str = 'bilinear', border_mode: str = 'zeros') -> torch.Tensor:
+ flags: str = 'bilinear', border_mode: str = 'zeros',
+ align_corners: bool = False) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -58,6 +60,8 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
'bilinear' | 'nearest'. Default: 'bilinear'.
border_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
Tensor: the warped input image.
@@ -88,12 +92,13 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
# launches the warper
h, w = src.shape[-2:]
- return transform_warp_impl(src, M, (h, w), dsize, flags, border_mode)
+ return transform_warp_impl(src, M, (h, w), dsize, flags, border_mode, align_corners)
def warp_affine(src: torch.Tensor, M: torch.Tensor,
dsize: Tuple[int, int], flags: str = 'bilinear',
- padding_mode: str = 'zeros') -> torch.Tensor:
+ padding_mode: str = 'zeros',
+ align_corners: bool = False) -> torch.Tensor:
r"""Applies an affine transformation to a tensor.
The function warp_affine transforms the source tensor using
@@ -111,6 +116,8 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
Returns:
torch.Tensor: the warped tensor.
@@ -147,9 +154,9 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], # type: ignore
[B, C, out_size[0], out_size[1]],
- align_corners=True)
+ align_corners=align_corners)
return F.grid_sample(src, grid, # type: ignore
- align_corners=True,
+ align_corners=align_corners,
mode=flags,
padding_mode=padding_mode)
@@ -370,7 +377,8 @@ def get_rotation_matrix2d(
def remap(tensor: torch.Tensor, map_x: torch.Tensor,
- map_y: torch.Tensor) -> torch.Tensor:
+ map_y: torch.Tensor,
+ align_corners: bool = False) -> torch.Tensor:
r"""Applies a generic geometrical transformation to a tensor.
The function remap transforms the source tensor using the specified map:
@@ -385,6 +393,8 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,
The tensor must be in the shape of (B, H, W).
map_y (torch.Tensor): the flow in the y-direction in pixel coordinates.
The tensor must be in the shape of (B, H, W).
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Returns:
torch.Tensor: the warped tensor.
@@ -421,7 +431,7 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,
map_xy_norm = map_xy_norm.expand(batch_size, -1, -1, -1)
# warp ans return
- tensor_warped: torch.Tensor = F.grid_sample(tensor, map_xy_norm, align_corners=True) # type: ignore
+ tensor_warped: torch.Tensor = F.grid_sample(tensor, map_xy_norm, align_corners=align_corners) # type: ignore
return tensor_warped
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 042d1d2ce..863693eef 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -33,9 +33,11 @@ class PyrDown(nn.Module):
r"""Blurs a tensor and downsamples it.
Args:
- borde_type (str): the padding mode to be applied before convolving.
+ border_type (str): the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Return:
torch.Tensor: the downsampled tensor.
@@ -49,10 +51,11 @@ class PyrDown(nn.Module):
>>> output = kornia.transform.PyrDown()(input) # 1x2x2x2
"""
- def __init__(self, border_type: str = 'reflect') -> None:
+ def __init__(self, border_type: str = 'reflect', align_corners: bool = False) -> None:
super(PyrDown, self).__init__()
self.border_type: str = border_type
self.kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
if not torch.is_tensor(input):
@@ -66,7 +69,7 @@ class PyrDown(nn.Module):
# downsample.
out: torch.Tensor = F.interpolate(x_blur, scale_factor=0.5, mode='bilinear',
- align_corners=False)
+ align_corners=self.align_corners)
return out
@@ -77,6 +80,8 @@ class PyrUp(nn.Module):
borde_type (str): the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Return:
torch.Tensor: the upsampled tensor.
@@ -90,10 +95,11 @@ class PyrUp(nn.Module):
>>> output = kornia.transform.PyrUp()(input) # 1x2x8x8
"""
- def __init__(self, border_type: str = 'reflect'):
+ def __init__(self, border_type: str = 'reflect', align_corners: bool = False):
super(PyrUp, self).__init__()
self.border_type: str = border_type
self.kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
+ self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
if not torch.is_tensor(input):
@@ -105,7 +111,7 @@ class PyrUp(nn.Module):
# upsample tensor
b, c, height, width = input.shape
x_up: torch.Tensor = F.interpolate(input, size=(height * 2, width * 2),
- mode='bilinear', align_corners=True)
+ mode='bilinear', align_corners=self.align_corners)
# blurs upsampled tensor
x_blur: torch.Tensor = filter2D(x_up, self.kernel, self.border_type)
@@ -229,26 +235,26 @@ class ScalePyramid(nn.Module):
def pyrdown(
input: torch.Tensor,
- border_type: str = 'reflect') -> torch.Tensor:
+ border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
r"""Blurs a tensor and downsamples it.
See :class:`~kornia.transform.PyrDown` for details.
"""
- return PyrDown(border_type)(input)
+ return PyrDown(border_type, align_corners)(input)
-def pyrup(input: torch.Tensor, border_type: str = 'reflect') -> torch.Tensor:
+def pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
r"""Upsamples a tensor and then blurs it.
See :class:`~kornia.transform.PyrUp` for details.
"""
- return PyrUp(border_type)(input)
+ return PyrUp(border_type, align_corners)(input)
def build_pyramid(
input: torch.Tensor,
max_level: int,
- border_type: str = 'reflect') -> List[torch.Tensor]:
+ border_type: str = 'reflect', align_corners: bool = False) -> List[torch.Tensor]:
r"""Constructs the Gaussian pyramid for an image.
The function constructs a vector of images and builds the Gaussian pyramid
@@ -258,9 +264,11 @@ def build_pyramid(
input (torch.Tensor): the tensor to be used to constructuct the pyramid.
max_level (int): 0-based index of the last (the smallest) pyramid layer.
It must be non-negative.
- borde_type (str): the padding mode to be applied before convolving.
+ border_type (str): the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
+ align_corners(bool): interpolation flag. Default: False. See
+
Shape:
- Input: :math:`(B, C, H, W)`
- Output :math:`[(B, NL, C, H, W), (B, NL, C, H/2, W/2), ...]`
@@ -282,7 +290,7 @@ def build_pyramid(
for _ in range(max_level - 1):
img_curr: torch.Tensor = pyramid[-1]
- img_down: torch.Tensor = pyrdown(img_curr, border_type)
+ img_down: torch.Tensor = pyrdown(img_curr, border_type, align_corners)
pyramid.append(img_down)
return pyramid
diff --git a/kornia/geometry/warp/depth_warper.py b/kornia/geometry/warp/depth_warper.py
index b1844c1ab..4204b757c 100644
--- a/kornia/geometry/warp/depth_warper.py
+++ b/kornia/geometry/warp/depth_warper.py
@@ -35,13 +35,16 @@ class DepthWarper(nn.Module):
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners(bool): interpolation flag. Default: True. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
"""
def __init__(self,
pinhole_dst: PinholeCamera,
height: int, width: int,
mode: str = 'bilinear',
- padding_mode: str = 'zeros'):
+ padding_mode: str = 'zeros',
+ align_corners: bool = True):
super(DepthWarper, self).__init__()
# constructor members
self.width: int = width
@@ -49,6 +52,7 @@ class DepthWarper(nn.Module):
self.mode: str = mode
self.padding_mode: str = padding_mode
self.eps = 1e-6
+ self.align_corners: bool = align_corners
# state members
self._pinhole_dst: PinholeCamera = pinhole_dst
@@ -190,7 +194,7 @@ class DepthWarper(nn.Module):
"""
return F.grid_sample(patch_dst, self.warp_grid(depth_src), # type: ignore
mode=self.mode, padding_mode=self.padding_mode,
- align_corners=True)
+ align_corners=self.align_corners)
# functional api
@@ -199,7 +203,8 @@ def depth_warp(pinhole_dst: PinholeCamera,
pinhole_src: PinholeCamera,
depth_src: torch.Tensor,
patch_dst: torch.Tensor,
- height: int, width: int):
+ height: int, width: int,
+ align_corners: bool = True):
r"""Function that warps a tensor from destination frame to reference
given the depth in the reference frame.
@@ -215,6 +220,6 @@ def depth_warp(pinhole_dst: PinholeCamera,
>>> image_src = kornia.depth_warp(pinhole_dst, pinhole_src,
>>> depth_src, image_dst, height, width) # NxCxHxW
"""
- warper = DepthWarper(pinhole_dst, height, width)
+ warper = DepthWarper(pinhole_dst, height, width, align_corners=align_corners)
warper.compute_projection_matrix(pinhole_src)
return warper(depth_src, patch_dst)
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index 5cfae7e87..2f7721e1a 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -33,6 +33,8 @@ class HomographyWarper(nn.Module):
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
normalized_coordinates (bool): wether to use a grid with
normalized coordinates.
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
"""
def __init__(
@@ -41,14 +43,15 @@ class HomographyWarper(nn.Module):
width: int,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- normalized_coordinates: bool = True) -> None:
+ normalized_coordinates: bool = True,
+ align_corners: bool = False) -> None:
super(HomographyWarper, self).__init__()
self.width: int = width
self.height: int = height
self.mode: str = mode
self.padding_mode: str = padding_mode
self.normalized_coordinates: bool = normalized_coordinates
-
+ self.align_corners: bool = align_corners
# create base grid to compute the flow
self.grid: torch.Tensor = create_meshgrid(
height, width, normalized_coordinates=normalized_coordinates)
@@ -148,7 +151,7 @@ class HomographyWarper(nn.Module):
return F.grid_sample(patch_src, warped_grid, # type: ignore
mode=self.mode, padding_mode=self.padding_mode,
- align_corners=True)
+ align_corners=self.align_corners)
# functional api
@@ -156,7 +159,8 @@ def homography_warp(patch_src: torch.Tensor,
src_homo_dst: torch.Tensor,
dsize: Tuple[int, int],
mode: str = 'bilinear',
- padding_mode: str = 'zeros') -> torch.Tensor:
+ padding_mode: str = 'zeros',
+ align_corners: bool = False) -> torch.Tensor:
r"""Function that warps image patchs or tensors by homographies.
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
@@ -173,7 +177,8 @@ def homography_warp(patch_src: torch.Tensor,
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
-
+ align_corners(bool): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
Return:
torch.Tensor: Patch sampled at locations from source to destination.
@@ -183,7 +188,7 @@ def homography_warp(patch_src: torch.Tensor,
>>> output = kornia.homography_warp(input, homography, (32, 32))
"""
height, width = dsize
- warper = HomographyWarper(height, width, mode, padding_mode)
+ warper = HomographyWarper(height, width, mode, padding_mode, align_corners=align_corners)
return warper(patch_src, src_homo_dst)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 1fbace9b6..2fa06e4fa 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1268,7 +1268,7 @@ class TestRandomCrop:
[3., 4., 5.],
[6., 7., 8.]
]]]).to(device)
- rc = RandomCrop(size=(2, 3), padding=None)
+ rc = RandomCrop(size=(2, 3), padding=None, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
@@ -1285,13 +1285,13 @@ class TestRandomCrop:
[0., 1., 2.],
[3., 4., 5.],
]]).repeat(batch_size, 1, 1, 1).to(device)
- rc = RandomCrop(size=(2, 3), padding=None)
+ rc = RandomCrop(size=(2, 3), padding=None, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
def test_same_on_batch(self, device):
- f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True)
+ f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True, align_corners=True)
input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
@@ -1311,7 +1311,7 @@ class TestRandomCrop:
[0., 0., 0.],
[1., 2., 0.]
]]]).to(device)
- rc = RandomCrop(size=(2, 3), padding=1)
+ rc = RandomCrop(size=(2, 3), padding=1, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
@@ -1331,7 +1331,7 @@ class TestRandomCrop:
[1., 2., 10.],
[4., 5., 10.]
]]]).to(device)
- rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
@@ -1351,7 +1351,7 @@ class TestRandomCrop:
[8., 8., 8.],
[1., 2., 8.]
]]]).to(device)
- rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
@@ -1366,7 +1366,7 @@ class TestRandomCrop:
[9., 9., 9.],
[0., 1., 2.]
]]).repeat(batch_size, 1, 1, 1).to(device)
- rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9)
+ rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True)
out = rc(inp)
assert_allclose(out, expected)
@@ -1393,10 +1393,9 @@ class TestRandomResizedCrop:
[6., 7., 8.]
]]).to(device)
- expected = torch.tensor([[[
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000]
- ]]]).to(device)
+ expected = torch.tensor(
+ [[[[5.3750, 5.8750, 4.5938],
+ [6.3437, 6.7812, 5.2500]]]]).to(device)
rrc = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
@@ -1420,11 +1419,10 @@ class TestRandomResizedCrop:
[6., 7., 8.]
]]).to(device)
- expected = torch.tensor([[[
- [3., 4., 5.],
- [4.5, 5.5, 6.5],
- [6., 7., 8.]
- ]]]).to(device)
+ expected = torch.tensor(
+ [[[[3.7500, 4.7500, 5.7500],
+ [5.2500, 6.2500, 7.2500],
+ [4.5000, 5.2500, 6.0000]]]]).to(device)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
@@ -1439,15 +1437,13 @@ class TestRandomResizedCrop:
[6., 7., 8.]
]]).repeat(batch_size, 1, 1, 1).to(device)
- expected = torch.tensor([[[
- [0., 1., 2.],
- [1.5, 2.5, 3.5],
- [3., 4., 5.],
- ]], [[
- [3., 4., 5.],
- [4.5, 5.5, 6.5],
- [6., 7., 8.],
- ]]]).to(device)
+ expected = torch. tensor(
+ [[[[0.0000, 0.7500, 1.5000],
+ [0.7500, 1.7500, 2.7500],
+ [2.2500, 3.2500, 4.2500]]],
+ [[[3.7500, 4.7500, 5.7500],
+ [5.2500, 6.2500, 7.2500],
+ [4.5000, 5.2500, 6.0000]]]]).to(device)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.py
index 60b80623a..91f7703bd 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -19,7 +19,9 @@ class TestPerspective:
end_points = torch.rand(1, 4, 2).to(device)
params = dict(
- batch_prob=batch_prob, start_points=start_points, end_points=end_points, interpolation=torch.tensor(1))
+ batch_prob=batch_prob, start_points=start_points,
+ end_points=end_points, interpolation=torch.tensor(1),
+ align_corners=False)
out_data = F.apply_perspective(x_data, params)
assert out_data.shape == x_data.shape
@@ -40,7 +42,8 @@ class TestPerspective:
batch_prob=batch_prob,
start_points=start_points,
end_points=end_points,
- interpolation=torch.tensor(1)
+ interpolation=torch.tensor(1),
+ align_corners=False
)
assert gradcheck(F.apply_perspective, (input, params,), raise_exception=True)
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
index a9049e454..2d384c5a5 100644
--- a/test/feature/test_scale_space_detector.py
+++ b/test/feature/test_scale_space_detector.py
@@ -40,8 +40,8 @@ class TestScaleSpaceDetector:
lafs, resps = det(inp)
expected_laf = torch.tensor([[[[6.0543, 0.0000, 16.0], [0.0, 6.0543, 16.0]]]], device=device)
expected_resp = torch.tensor([[0.0804]], device=device)
- assert_allclose(expected_laf, lafs, rtol=0.0001, atol=1e-04)
- assert_allclose(expected_resp, resps, rtol=0.0001, atol=1e-04)
+ assert_allclose(expected_laf, lafs, rtol=0.001, atol=1e-03)
+ assert_allclose(expected_resp, resps, rtol=0.001, atol=1e-03)
def test_toy_mask(self, device):
if "cuda" in str(device):
@@ -61,8 +61,8 @@ class TestScaleSpaceDetector:
expected_laf = torch.tensor([[[[6.0478, 0.0000, 4.9978],
[0.0000, 6.0478, 4.9993]]]], device=device)
expected_resp = torch.tensor([[0.0]], device=device)
- assert_allclose(expected_laf, lafs)
- assert_allclose(expected_resp, resps)
+ assert_allclose(expected_laf, lafs, rtol=0.001, atol=1e-03)
+ assert_allclose(expected_resp, resps, rtol=0.001, atol=1e-03)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 31, 21
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index eadb8b33a..eea458238 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -1,5 +1,4 @@
import pytest
-
import kornia as kornia
import kornia.testing as utils # test utils
from test.common import device
@@ -55,7 +54,7 @@ class TestRotate:
]]).to(device)
# prepare transformation
angle = torch.tensor([90.]).to(device)
- transform = kornia.Rotate(angle)
+ transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected)
def test_angle90_batch2(self, device):
@@ -79,7 +78,7 @@ class TestRotate:
]]]).to(device)
# prepare transformation
angle = torch.tensor([90., -90.]).to(device)
- transform = kornia.Rotate(angle)
+ transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected)
def test_angle90_batch2_broadcast(self, device):
@@ -103,7 +102,7 @@ class TestRotate:
]]]).to(device)
# prepare transformation
angle = torch.tensor([90.]).to(device)
- transform = kornia.Rotate(angle)
+ transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected)
def test_gradcheck(self, device):
@@ -145,7 +144,7 @@ class TestTranslate:
]]).to(device)
# prepare transformation
translation = torch.tensor([[1., 0.]]).to(device)
- transform = kornia.Translate(translation)
+ transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected)
def test_dxdy_batch(self, device):
@@ -169,7 +168,7 @@ class TestTranslate:
]]]).to(device)
# prepare transformation
translation = torch.tensor([[1., 0.], [1., 1.]]).to(device)
- transform = kornia.Translate(translation)
+ transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected)
def test_dxdy_batch_broadcast(self, device):
@@ -193,7 +192,7 @@ class TestTranslate:
]]]).to(device)
# prepare transformation
translation = torch.tensor([[1., 0.]]).to(device)
- transform = kornia.Translate(translation)
+ transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected)
def test_gradcheck(self, device):
@@ -322,12 +321,11 @@ class TestShear:
[1., 1., 1., 1.],
[1., 1., 1., 1.]
]]).to(device)
- expected = torch.tensor([[
- [1., 1., 1., 1.],
- [.5, 1., 1., 1.],
- [0., 1., 1., 1.],
- [0., .5, 1., 1.]
- ]]).to(device)
+ expected = torch.tensor(
+ [[[0.75, 1., 1., 1.],
+ [0.25, 1., 1., 1.],
+ [0., 0.75, 1., 1.],
+ [0., 0.25, 1., 1.]]]).to(device)
# prepare transformation
shear = torch.tensor([[0.5, 0.0]]).to(device)
@@ -342,12 +340,11 @@ class TestShear:
[1., 1., 1., 1.],
[1., 1., 1., 1.]
]]).to(device)
- expected = torch.tensor([[
- [1., .5, 0., 0.],
- [1., 1., 1., .5],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]]).to(device)
+ expected = torch.tensor(
+ [[[0.75, 0.25, 0., 0.],
+ [1., 1., 0.75, 0.25],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]]]).to(device)
# prepare transformation
shear = torch.tensor([[0.0, 0.5]]).to(device)
@@ -363,17 +360,15 @@ class TestShear:
[1., 1., 1., 1.]
]]).repeat(2, 1, 1, 1).to(device)
- expected = torch.tensor([[[
- [1., 1., 1., 1.],
- [.5, 1., 1., 1.],
- [0., 1., 1., 1.],
- [0., .5, 1., 1.]
- ]], [[
- [1., .5, 0., 0.],
- [1., 1., 1., .5],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]]]).to(device)
+ expected = torch.tensor(
+ [[[[0.75, 1., 1., 1.],
+ [0.25, 1., 1., 1.],
+ [0., 0.75, 1., 1.],
+ [0., 0.25, 1., 1.]]],
+ [[[0.75, 0.25, 0., 0.],
+ [1., 1., 0.75, 0.25],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]]]]).to(device)
# prepare transformation
shear = torch.tensor([[0.5, 0.0], [0.0, 0.5]]).to(device)
@@ -390,11 +385,10 @@ class TestShear:
]]).repeat(2, 1, 1, 1).to(device)
expected = torch.tensor([[[
- [1., 1., 1., 1.],
- [.5, 1., 1., 1.],
- [0., 1., 1., 1.],
- [0., .5, 1., 1.]
- ]]]).to(device)
+ [0.75, 1., 1., 1.],
+ [0.25, 1., 1., 1.],
+ [0., 0.75, 1., 1.],
+ [0., 0.25, 1., 1.]]]]).to(device)
# prepare transformation
shear = torch.tensor([[0.5, 0.0]]).to(device)
@@ -458,7 +452,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.823560708200617, 7.06797949691645]
+ scale, shear = 0.7785685905190581, [11.8235607082617, 7.06797949691645]
matrix_expected = T([[1.27536969, 4.26828945e-01, -3.23493180e+01],
[2.18297196e-03, 1.29424165e+00, -9.19962753e+00]])
center = T([float(width), float(height)]).view(1, 2) / 2. + 0.5
diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.py
index be8482669..8add481bf 100644
--- a/test/geometry/transform/test_crop.py
+++ b/test/geometry/transform/test_crop.py
@@ -63,10 +63,9 @@ class TestCropAndResize:
]]).to(device)
height, width = 2, 3
- expected = torch.tensor([[
- [6., 6.5, 7.],
- [10., 10.5, 11.],
- ]]).to(device)
+ expected = torch.tensor(
+ [[[6.7222, 7.1667, 7.6111],
+ [9.3889, 9.8333, 10.2778]]]).to(device)
boxes = torch.tensor([[
[1., 1.],
@@ -112,7 +111,7 @@ class TestCropAndResize:
[1., 3.],
]]).to(device) # 2x4x2
- patches = kornia.crop_and_resize(inp, boxes, (height, width))
+ patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=True)
assert_allclose(patches, expected)
def test_crop_batch_broadcast(self, device):
@@ -144,7 +143,7 @@ class TestCropAndResize:
[1., 2.],
]]).to(device) # 1x4x2
- patches = kornia.crop_and_resize(inp, boxes, (height, width))
+ patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=True)
assert_allclose(patches, expected)
def test_gradcheck(self, device):
@@ -336,7 +335,7 @@ class TestCropByBoxes:
[10., 11.],
]]).to(device)
- patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst, align_corners=True)
assert_allclose(patches, expected)
def test_crop_by_boxes_resizing(self, device):
@@ -366,7 +365,7 @@ class TestCropByBoxes:
[10., 10.5, 11.],
]]).to(device)
- patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst, align_corners=True)
assert_allclose(patches, expected)
def test_gradcheck(self, device):
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index afbfc39e7..bf75447ee 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -27,16 +27,16 @@ def test_warp_perspective_rotation(batch_shape, device):
# apply transformation and inverse
_, _, h, w = patch.shape
- patch_warped = kornia.warp_perspective(patch, M, dsize=(height, width))
+ patch_warped = kornia.warp_perspective(patch, M, dsize=(height, width), align_corners=True)
patch_warped_inv = kornia.warp_perspective(
- patch_warped, torch.inverse(M), dsize=(height, width))
+ patch_warped, torch.inverse(M), dsize=(height, width), align_corners=True)
# generate mask to compute error
mask = torch.ones_like(patch)
mask_warped_inv = kornia.warp_perspective(
- kornia.warp_perspective(patch, M, dsize=(height, width)),
+ kornia.warp_perspective(patch, M, dsize=(height, width), align_corners=True),
torch.inverse(M),
- dsize=(height, width))
+ dsize=(height, width), align_corners=True)
assert_allclose(mask_warped_inv * patch,
mask_warped_inv * patch_warped_inv)
@@ -175,11 +175,10 @@ class TestWarpPerspective:
[13, 14, 15, 16],
]]]).expand(batch_size, channels, -1, -1).to(device)
- expected = torch.FloatTensor([[[
- [1, 2, 3],
- [5, 6, 7],
- [9, 10, 11],
- ]]]).to(device)
+ expected = torch.tensor(
+ [[[[0.2500, 0.9167, 1.5833],
+ [2.1667, 5.1667, 6.5000],
+ [4.8333, 10.5000, 11.8333]]]]).to(device)
# warp and assert
patch_warped = kornia.warp_perspective(patch, dst_trans_src,
@@ -219,12 +218,11 @@ class TestWarpPerspective:
[13, 14, 15, 16],
]]]).to(device)
- expected = torch.FloatTensor([[[
- [6.000, 6.333, 6.666, 7.000],
- [7.333, 7.666, 8.000, 8.333],
- [8.666, 9.000, 9.333, 9.666],
- [10.000, 10.333, 10.666, 11.000],
- ]]]).to(device)
+ expected = torch.tensor(
+ [[[[5.1667, 5.6111, 6.0556, 6.5000],
+ [6.9444, 7.3889, 7.8333, 8.2778],
+ [8.7222, 9.1667, 9.6111, 10.0556],
+ [10.5000, 10.9444, 11.3889, 11.8333]]]]).to(device)
# warp and assert
patch_warped = kornia.warp_perspective(patch, dst_trans_src,
@@ -248,7 +246,7 @@ class TestWarpAffine:
aff_ab[..., -1] += offset
img_b = torch.arange(float(height * width)).view(
1, channels, height, width).repeat(batch_size, 1, 1, 1).to(device)
- img_a = kornia.warp_affine(img_b, aff_ab, (height, width))
+ img_a = kornia.warp_affine(img_b, aff_ab, (height, width), align_corners=True)
assert_allclose(img_b[..., :2, :3], img_a[..., 1:, 1:])
def test_gradcheck(self, device):
@@ -273,7 +271,7 @@ class TestRemap:
input = torch.ones(1, 1, height, width).to(device)
grid = kornia.utils.create_meshgrid(
height, width, normalized_coordinates=False).to(device)
- input_warped = kornia.remap(input, grid[..., 0], grid[..., 1])
+ input_warped = kornia.remap(input, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input, input_warped)
def test_shift(self, device):
@@ -293,7 +291,7 @@ class TestRemap:
height, width, normalized_coordinates=False).to(device)
grid += 1. # apply shift in both x/y direction
- input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1])
+ input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected)
def test_shift_batch(self, device):
@@ -321,7 +319,7 @@ class TestRemap:
grid[0, ..., 0] += 1. # apply shift in the x direction
grid[1, ..., 1] += 1. # apply shift in the y direction
- input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1])
+ input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected)
def test_shift_batch_broadcast(self, device):
@@ -341,7 +339,7 @@ class TestRemap:
height, width, normalized_coordinates=False).to(device)
grid += 1. # apply shift in both x/y direction
- input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1])
+ input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected)
def test_gradcheck(self, device):
diff --git a/test/geometry/warp/test_homography_warper.py b/test/geometry/warp/test_homography_warper.py
index 8bc179d71..98b544401 100644
--- a/test/geometry/warp/test_homography_warper.py
+++ b/test/geometry/warp/test_homography_warper.py
@@ -21,7 +21,7 @@ class TestHomographyWarper:
dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3).to(device)
# instantiate warper
- warper = kornia.HomographyWarper(height, width)
+ warper = kornia.HomographyWarper(height, width, align_corners=True)
# warp from source to destination
patch_dst = warper(patch_src, dst_homo_src)
@@ -83,7 +83,8 @@ class TestHomographyWarper:
# instantiate warper
warper = kornia.HomographyWarper(height, width,
- normalized_coordinates=False)
+ normalized_coordinates=False,
+ align_corners=True)
flow = warper.warp_grid(dst_homo_src)
# the grid the src plus the offset should be equal to the flow
@@ -102,7 +103,7 @@ class TestHomographyWarper:
dst_homo_src = utils.create_eye_batch(batch_size, eye_size=3).to(device)
# instantiate warper warp from source to destination
- warper = kornia.HomographyWarper(height // 2, width // 2)
+ warper = kornia.HomographyWarper(height // 2, width // 2, align_corners=True)
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
@@ -126,7 +127,7 @@ class TestHomographyWarper:
dst_homo_src[..., 0, 2] = offset / (width - 1) # apply offset in x
# instantiate warper and from source to destination
- warper = kornia.HomographyWarper(height, width)
+ warper = kornia.HomographyWarper(height, width, align_corners=True)
patch_dst = warper(patch_src, dst_homo_src)
assert_allclose(patch_src[..., 1:], patch_dst[..., :-1])
@@ -145,7 +146,7 @@ class TestHomographyWarper:
dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)
# instantiate warper and warp from source to destination
- warper = kornia.HomographyWarper(height, width)
+ warper = kornia.HomographyWarper(height, width, align_corners=True)
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
@@ -173,7 +174,7 @@ class TestHomographyWarper:
dst_homo_src = utils.create_eye_batch(batch_size, eye_size).to(device)
# instantiate warper
- warper = kornia.HomographyWarper(height, width)
+ warper = kornia.HomographyWarper(height, width, align_corners=True)
for i in range(self.num_tests):
# generate homography noise
@@ -199,7 +200,7 @@ class TestHomographyWarper:
# check functional api
patch_dst_to_src_functional = kornia.homography_warp(
- patch_dst, torch.inverse(dst_homo_src_i), (height, width))
+ patch_dst, torch.inverse(dst_homo_src_i), (height, width), align_corners=True)
assert_allclose(
patch_dst_to_src, patch_dst_to_src_functional)
@@ -221,7 +222,7 @@ class TestHomographyWarper:
dst_homo_src, requires_grad=False) # to var
# instantiate warper
- warper = kornia.HomographyWarper(height, width)
+ warper = kornia.HomographyWarper(height, width, align_corners=True)
# evaluate function gradient
assert gradcheck(warper, (patch_src, dst_homo_src,),