Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

update to python 3.8

edgarriba4831da680c02
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 5406875cb..451c00fcd 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -45,6 +45,13 @@ jobs:
environment:
- PYTHON_VERSION: "3.7"
+ python_3_8:
+ <<: *common
+ docker:
+ - image: circleci/python:3.8.0
+ environment:
+ - PYTHON_VERSION: "3.8"
+
workflows:
version: 2
test:
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index a950eae78..c99f79c32 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -262,6 +262,7 @@ class RandomErasing(AugmentationBase):
[1., 0., 0.]]]])
"""
# Note: Extra params, inplace=False in Torchvision.
+
def __init__(
self, p: float = 0.5, scale: Tuple[float, float] = (0.02, 0.33), ratio: Tuple[float, float] = (0.3, 3.3),
value: float = 0., return_transform: bool = False, same_on_batch: bool = False
@@ -462,6 +463,7 @@ class RandomRotation(AugmentationBase):
[ 0.0000, 0.0000, 1.0000]]]))
"""
# 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, align_corners: bool = False
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index e88d47f6d..f789b69de 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -246,8 +246,8 @@ def compute_hflip_transformation(input: torch.Tensor, params: Dict[str, torch.Te
trans_mat: torch.Tensor = torch.eye(3, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
w: int = input.shape[-1]
flip_mat: torch.Tensor = torch.tensor([[-1, 0, w],
- [0, 1, 0],
- [0, 0, 1]])
+ [0, 1, 0],
+ [0, 0, 1]])
trans_mat[to_flip] = flip_mat.type_as(input)
return trans_mat
@@ -288,8 +288,8 @@ def compute_vflip_transformation(input: torch.Tensor, params: Dict[str, torch.Te
h: int = input.shape[-2]
flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],
- [0, -1, h],
- [0, 0, 1]])
+ [0, -1, h],
+ [0, 0, 1]])
trans_mat[to_flip] = flip_mat.type_as(input)
@@ -398,12 +398,12 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> t
_, _, height, width = x_data.shape
# compute the homography between the input points
- transform = compute_perspective_transformation(input, params)
+ transform: torch.Tensor = compute_perspective_transformation(input, params)
out_data: torch.Tensor = x_data.clone()
# process valid samples
- mask = params['batch_prob'].to(input.device)
+ mask: torch.Tensor = params['batch_prob'].to(input.device)
# TODO: look for a workaround for this hack. In CUDA it fails when no elements found.
# TODO: this if statement is super weird and sum here is not the propeer way to check
@@ -412,11 +412,13 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> t
if bool(mask.sum() > 0) and ('interpolation' in params):
# 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], # type: ignore
- (height, width),
- flags=resample_name,
- align_corners=params['align_corners'])
+ resample_name: str = Resample(params['interpolation'].item()).name.lower()
+ align_corners: bool = cast(bool, params['align_corners'].item())
+
+ out_data[mask] = warp_perspective(
+ x_data[mask], transform[mask], (height, width),
+ flags=resample_name, align_corners=align_corners)
+
return out_data.view_as(input)
@@ -467,13 +469,14 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.
height, width = x_data.shape[-2:]
# concatenate transforms
- transform = compute_affine_transformation(input, params)
+ transform: torch.Tensor = compute_affine_transformation(input, params)
- resample_name = Resample(params['resample'].item()).name.lower()
+ resample_name: str = Resample(params['resample'].item()).name.lower()
+ align_corners: bool = cast(bool, params['align_corners'].item())
- out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :], # type: ignore
+ out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :],
(height, width), resample_name,
- align_corners=params['align_corners'])
+ align_corners=align_corners)
return out_data.view_as(input)
@@ -502,9 +505,10 @@ 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( # type: ignore
- input, angles, mode=Resample(params['interpolation'].item()).name.lower(),
- align_corners=params['align_corners'])
+ resample_mode: str = Resample(params['interpolation'].item()).name.lower()
+ align_corners: bool = cast(bool, params['align_corners'].item())
+
+ transformed: torch.Tensor = rotate(input, angles, mode=resample_mode, align_corners=align_corners)
return transformed
@@ -541,12 +545,11 @@ 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( # type: ignore
- input,
- params['src'],
- params['dst'],
- Resample.get(params['interpolation'].item()).name.lower(), # type: ignore
- align_corners=params['align_corners'])
+ resample_mode: str = Resample.get(params['interpolation'].item()).name.lower() # type: ignore
+ align_corners: bool = cast(bool, params['align_corners'].item())
+
+ return crop_by_boxes(
+ input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]):
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index e36bf4489..4907c8be9 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -10,6 +10,7 @@ from kornia.augmentation.utils import (
_check_and_bound
)
+# TODO: remove this since it does not help readability
from .types import (
TupleFloat,
UnionFloat,
@@ -18,9 +19,14 @@ from .types import (
)
-def random_color_jitter_generator(batch_size: int, brightness: FloatUnionType = 0.,
- contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,
- hue: FloatUnionType = 0., same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+def random_color_jitter_generator(
+ batch_size: int,
+ brightness: FloatUnionType = 0.,
+ contrast: FloatUnionType = 0.,
+ saturation: FloatUnionType = 0.,
+ hue: FloatUnionType = 0.,
+ same_on_batch: bool = False
+) -> Dict[str, torch.Tensor]:
r"""Generator random color jiter parameters for a batch of images.
Args:
@@ -37,35 +43,44 @@ def random_color_jitter_generator(batch_size: int, brightness: FloatUnionType =
See :class:`~kornia.augmentation.ColorJitter` for details.
"""
- brightness_bound: torch.Tensor = _check_and_bound(brightness, 'brightness', center=1., bounds=(0, 2))
- contrast_bound: torch.Tensor = _check_and_bound(contrast, 'contrast', center=1.)
- saturation_bound: torch.Tensor = _check_and_bound(saturation, 'saturation', center=1.)
+ brightness_bound: torch.Tensor = _check_and_bound(
+ brightness, 'brightness', center=1., bounds=(0, 2))
+
+ contrast_bound: torch.Tensor = _check_and_bound(
+ contrast, 'contrast', center=1.)
+
+ saturation_bound: torch.Tensor = _check_and_bound(
+ saturation, 'saturation', center=1.)
+
hue_bound: torch.Tensor = _check_and_bound(hue, 'hue', bounds=(-0.5, 0.5))
- brightness_factor = _adapted_uniform((batch_size,), brightness_bound[0], brightness_bound[1], same_on_batch)
+ brightness_factor = _adapted_uniform(
+ (batch_size,), brightness_bound[0], brightness_bound[1], same_on_batch)
- contrast_factor = _adapted_uniform((batch_size,), contrast_bound[0], contrast_bound[1], same_on_batch)
+ contrast_factor = _adapted_uniform(
+ (batch_size,), contrast_bound[0], contrast_bound[1], same_on_batch)
- hue_factor = _adapted_uniform((batch_size,), hue_bound[0], hue_bound[1], same_on_batch)
+ hue_factor = _adapted_uniform(
+ (batch_size,), hue_bound[0], hue_bound[1], same_on_batch)
- saturation_factor = _adapted_uniform((batch_size,), saturation_bound[0], saturation_bound[1], same_on_batch)
+ saturation_factor = _adapted_uniform(
+ (batch_size,), saturation_bound[0], saturation_bound[1], same_on_batch)
- return {
- "brightness_factor": brightness_factor,
- "contrast_factor": contrast_factor,
- "hue_factor": hue_factor,
- "saturation_factor": saturation_factor,
- "order": torch.randperm(4)
- }
+ return dict(brightness_factor=brightness_factor,
+ contrast_factor=contrast_factor,
+ hue_factor=hue_factor,
+ saturation_factor=saturation_factor,
+ order=torch.randperm(4))
-def random_prob_generator(batch_size: int, p: float = 0.5, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+def random_prob_generator(
+ batch_size: int, p: float = 0.5, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
r"""Generator random probabilities for a batch of inputs.
Args:
batch_size (int): the number of images.
- p (float): probability of the image being flipped or grayscaled. Default value is 0.5
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ p (float): probability of the image being flipped or grayscaled. Default value is 0.5.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
Returns:
dict: generated parameter dictionary.
@@ -80,13 +95,18 @@ def random_prob_generator(batch_size: int, p: float = 0.5, same_on_batch: bool =
probs: torch.Tensor = _adapted_uniform((batch_size,), 0, 1, same_on_batch)
- batch_prob: torch.Tensor = probs < p
+ batch_prob: torch.Tensor = (probs < p)
- return {'batch_prob': batch_prob}
+ return dict(batch_prob=batch_prob)
-def _get_perspective_params(batch_size: int, width: int, height: int, distortion_scale: float,
- same_on_batch: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
+def _get_perspective_params(
+ batch_size: int,
+ width: int,
+ height: int,
+ distortion_scale: float,
+ same_on_batch: bool = False
+) -> Tuple[torch.Tensor, torch.Tensor]:
start_points: torch.Tensor = torch.tensor([[
[0., 0],
[width - 1, 0],
@@ -113,8 +133,13 @@ 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,
+ 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,
align_corners: bool = False,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
@@ -127,7 +152,7 @@ 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
+ align_corners(bool): interpolation flag. Default: False. See
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
@@ -143,21 +168,22 @@ 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
+ params['align_corners'] = torch.tensor(align_corners)
return params
def random_affine_generator(
- batch_size: int,
- height: int,
- width: int,
- degrees: UnionFloat,
- translate: Optional[TupleFloat] = None,
- scale: Optional[TupleFloat] = None,
- shear: Optional[UnionFloat] = None,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- same_on_batch: bool = False,
- align_corners: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size: int,
+ height: int,
+ width: int,
+ degrees: UnionFloat,
+ translate: Optional[TupleFloat] = None,
+ scale: Optional[TupleFloat] = None,
+ shear: Optional[UnionFloat] = None,
+ 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`` for a random affine transform.
Args:
@@ -181,7 +207,7 @@ 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
+ align_corners(bool): interpolation flag. Default: False. See
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
"""
@@ -230,10 +256,13 @@ def random_affine_generator(
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,
- align_corners: bool = False) -> Dict[str, torch.Tensor]:
+def random_rotation_generator(
+ batch_size: int,
+ degrees: FloatUnionType,
+ 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 ``rotate`` for a random rotate transform.
Args:
@@ -264,17 +293,21 @@ def random_rotation_generator(batch_size: int, degrees: FloatUnionType,
degrees = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
- return dict( # type: ignore
- degrees=degrees,
- interpolation=torch.tensor(Resample.get(interpolation).value),
- align_corners=align_corners)
+ return dict(degrees=degrees,
+ interpolation=torch.tensor(Resample.get(interpolation).value),
+ align_corners=torch.tensor(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,
+ 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,
align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```affine``` transformation random affine transform.
@@ -304,26 +337,30 @@ def _get_random_affine_params(
center: torch.Tensor = torch.tensor(
[width, height], dtype=torch.float32).view(1, 2) / 2. - 0.5
center = center.expand(batch_size, -1)
+
if shears is not None:
sx = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
sy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
else:
sx = sy = torch.tensor([0] * batch_size)
- return dict( # type: ignore
- translations=translations,
- center=center,
- scale=scale,
- angle=angle,
- sx=sx,
- sy=sy,
- resample=torch.tensor(Resample.get(resample).value),
- align_corners=align_corners
- )
+
+ return dict(translations=translations,
+ center=center,
+ scale=scale,
+ angle=angle,
+ sx=sx,
+ sy=sy,
+ resample=torch.tensor(Resample.get(resample).value),
+ align_corners=torch.tensor(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,
+ 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,
align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
@@ -367,26 +404,35 @@ def random_crop_generator(
[0, resize_to[0] - 1],
]]).repeat(batch_size, 1, 1)
- return {'src': crop_src, 'dst': crop_dst, # type: ignore
- 'interpolation': torch.tensor(Resample.get(interpolation).value),
- 'align_corners': align_corners}
+ return dict(src=crop_src,
+ dst=crop_dst,
+ interpolation=torch.tensor(Resample.get(interpolation).value),
+ align_corners=torch.tensor(align_corners))
-def random_crop_size_generator(size: Tuple[int, int], scale: Tuple[float, float], ratio: Tuple[float, float],
- same_on_batch: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
+def random_crop_size_generator(
+ size: Tuple[int, int],
+ scale: Tuple[float, float],
+ ratio: Tuple[float, float],
+ same_on_batch: bool = False
+) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
+
Args:
- size (Tuple[int, int]): expected output size of each edge
- scale: range of size of the origin size cropped
- ratio: range of aspect ratio of the origin aspect ratio cropped
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ size (Tuple[int, int]): expected output size of each edge.
+ scale: range of size of the origin size cropped.
+ ratio: range of aspect ratio of the origin aspect ratio cropped.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
"""
- area = _adapted_uniform((10,), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
- log_ratio = _adapted_uniform((10,), math.log(ratio[0]), math.log(ratio[1]), same_on_batch)
+ area = _adapted_uniform(
+ (10,), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
+ log_ratio = _adapted_uniform(
+ (10,), math.log(ratio[0]), math.log(ratio[1]), same_on_batch)
aspect_ratio = torch.exp(log_ratio)
w = torch.sqrt(area * aspect_ratio).int()
h = torch.sqrt(area / aspect_ratio).int()
+
# Element-wise w, h condition
cond = ((0 < h) * (h < size[1]) * (0 < w) * (w < size[0])).int()
if torch.sum(cond) > 0:
@@ -406,9 +452,16 @@ def random_crop_size_generator(size: Tuple[int, int], scale: Tuple[float, float]
return (h, w)
-def random_rectangles_params_generator(batch_size: int, height: int, width: int, p: float,
- scale: Tuple[float, float], ratio: Tuple[float, float],
- value: float = 0., same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+def random_rectangles_params_generator(
+ batch_size: int,
+ height: int,
+ width: int,
+ p: float,
+ scale: Tuple[float, float],
+ ratio: Tuple[float, float],
+ value: float = 0.,
+ same_on_batch: bool = False
+) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```erasing``` transformation for erasing transform
Args:
@@ -416,15 +469,16 @@ def random_rectangles_params_generator(batch_size: int, height: int, width: int,
height (int) : height of the image.
width (int): width of the image.
p (float): probability of applying random earaing.
- scale ([int, int]): range of size of the origin size cropped
- ratio ([int, int]): range of aspect ratio of the origin aspect ratio cropped
+ scale ([int, int]): range of size of the origin size cropped.
+ ratio ([int, int]): range of aspect ratio of the origin aspect ratio cropped.
value (float): value to be filled in the erased area.
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
"""
batch_prob = random_prob_generator(batch_size, p, same_on_batch)['batch_prob']
zeros = torch.zeros((batch_size,))
images_area = height * width
- target_areas = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch) * images_area
+ target_areas = _adapted_uniform(
+ (batch_size,), scale[0], scale[1], same_on_batch) * images_area
if ratio[0] < 1. and ratio[1] > 1.:
aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0], 1, same_on_batch)
aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1], same_on_batch)
@@ -432,15 +486,20 @@ def random_rectangles_params_generator(batch_size: int, height: int, width: int,
aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
aspect_ratios = _adapted_uniform((batch_size,), ratio[0], ratio[1], same_on_batch)
+
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
- torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.)),
+ torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)),
+ torch.tensor(1.)),
torch.tensor(float(height))
).int()
+
widths = torch.min(
- torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.)),
+ torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)),
+ torch.tensor(1.)),
torch.tensor(float(width))
).int()
+
xs = (_adapted_uniform((batch_size,), 0, 1, same_on_batch) * (torch.tensor(width) - widths + 1).float()).int()
ys = (_adapted_uniform((batch_size,), 0, 1, same_on_batch) * (torch.tensor(height) - heights + 1).float()).int()
@@ -450,19 +509,23 @@ def random_rectangles_params_generator(batch_size: int, height: int, width: int,
params["xs"] = xs
params["ys"] = ys
params["values"] = torch.tensor([value] * batch_size)
-
return params
-def center_crop_params_generator(batch_size: int, height: int, width: int,
- size: Tuple[int, int],
- align_corners: bool = False) -> Dict[str, torch.Tensor]:
+def center_crop_params_generator(
+ batch_size: int,
+ height: int,
+ width: int,
+ 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.
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (h, w).
+ align_corners (bool): interpolation flag. Default: False.
"""
if not isinstance(size, (tuple, list,)) and len(size) == 2:
@@ -484,6 +547,7 @@ def center_crop_params_generator(batch_size: int, height: int, width: int,
end_x = start_x + dst_w - 1
end_y = start_y + dst_h - 1
+
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
points_src: torch.Tensor = torch.tensor([[
@@ -501,5 +565,7 @@ 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, # type: ignore
- 'interpolation': torch.tensor(Resample.BILINEAR.value), 'align_corners': align_corners}
+ return dict(src=points_src,
+ dst=points_dst,
+ interpolation=torch.tensor(Resample.BILINEAR.value),
+ align_corners=torch.tensor(align_corners))
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index c85fb3017..60e4d093e 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -86,13 +86,14 @@ class LuvToRgb(nn.Module):
return luv_to_rgb(image)
-def rgb_to_luv(image: torch.Tensor) -> torch.Tensor:
+def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Converts a RGB image to Luv.
See :class:`~kornia.color.RgbToLuv` for details.
Args:
image (torch.Tensor): RGB image
+ eps (float): for numerically stability when dividing. Default: 1e-8.
Returns:
torch.Tensor : Luv image
@@ -127,8 +128,6 @@ def rgb_to_luv(image: torch.Tensor) -> torch.Tensor:
116. * torch.pow(y, 1. / 3.) - 16.,
903.3 * y)
- eps: float = torch.finfo(torch.float64).eps # For numerical stability
-
# Compute reference white point
xyz_ref_white: Tuple[float, float, float] = (.95047, 1., 1.08883)
u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
@@ -145,13 +144,14 @@ def rgb_to_luv(image: torch.Tensor) -> torch.Tensor:
return out
-def luv_to_rgb(image: torch.Tensor) -> torch.Tensor:
+def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Converts a Luv image to RGB.
See :class:`~kornia.color.LuvToRgb` for details.
Args:
image (torch.Tensor): Luv image
+ eps (float): for numerically stability when dividing. Default: 1e-8.
Returns:
torch.Tensor : RGB image
@@ -176,8 +176,6 @@ def luv_to_rgb(image: torch.Tensor) -> torch.Tensor:
u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
v_w: float = (9 * xyz_ref_white[1]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
- eps: float = torch.finfo(torch.float64).eps # For numerical stability when dividing
-
a: torch.Tensor = u_w + u / (13 * L + eps)
d: torch.Tensor = v_w + v / (13 * L + eps)
c: torch.Tensor = 3 * y * (5 * d - 3)
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 5e2a3b50f..9afcac5e3 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -6,7 +6,7 @@ import torch.nn.functional as F
urls: Dict[str, str] = dict()
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
-urls["liberty_aug"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
+urls["liberty_aug"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
class HardNet(nn.Module):
@@ -31,6 +31,7 @@ class HardNet(nn.Module):
>>> hardnet = kornia.feature.HardNet()
>>> descs = hardnet(input) # 16x128
"""
+
def __init__(self, pretrained: bool = False) -> None:
super(HardNet, self).__init__()
self.features = nn.Sequential(
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 75edd2cc7..0704c0fd6 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -25,6 +25,7 @@ class SOSNet(nn.Module):
>>> sosnet = kornia.feature.SOSNet()
>>> descs = sosnet(input) # 8x128
"""
+
def __init__(self, pretrained: bool = False) -> None:
super(SOSNet, self).__init__()
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index ad4440ed9..8bbb3e4fe 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -486,7 +486,7 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:
sy_tan = torch.tan(sy) # type: ignore
zeros = torch.zeros_like(sx) # type: ignore
ones = torch.ones_like(sx) # type: ignore
- shear_mat = torch.stack([ones, -sx_tan, sx_tan * x, # type: ignore # noqa: E241
+ shear_mat = torch.stack([ones, -sx_tan, sx_tan * x, # type: ignore # noqa: E241
-sy_tan, ones + sx_tan * sy_tan, sy_tan * (-sx_tan * x + y)], # noqa: E241
dim=-1).view(-1, 2, 3)
shear_mat = convert_affinematrix_to_homography(shear_mat)
diff --git a/requirements.txt b/requirements.txt
index e1537059f..62ee9ddc2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,30 +1,29 @@
# core dependencies
pytorch==1.5.0
-cudatoolkit==10.2.89
# package
-setuptools==41.4.0
+setuptools>=41.4.0
# utils
torchvision==0.6.0
-opencv==4.1.1
-ipython==7.8.0
-jupyter==1.0.0
-matplotlib==3.1.1
+opencv
+ipython
+jupyter
+matplotlib
# test
-pytest==5.1.2
-pytest-cov==2.7.1
-flake8==3.7.8
-autopep8==1.4.4
-mypy==0.720
-mypy_extensions==0.4.1
+pytest>=5.1.2
+pytest-cov
+flake8
+autopep8
+mypy
+mypy_extensions
# docs
-sphinx==2.1.2
-sphinx-gallery==0.4.0
-sphinx_rtd_theme==0.4.3
-sphinxcontrib-bibtex==0.4.2
-nbsphinx==0.4.2
-nbconvert==5.5.0
-notebook==6.0.1
+sphinx
+sphinx-gallery
+sphinx_rtd_theme
+sphinxcontrib-bibtex
+nbsphinx
+nbconvert
+notebook
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 2fa06e4fa..633a0830c 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1421,8 +1421,8 @@ class TestRandomResizedCrop:
expected = torch.tensor(
[[[[3.7500, 4.7500, 5.7500],
- [5.2500, 6.2500, 7.2500],
- [4.5000, 5.2500, 6.0000]]]]).to(device)
+ [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 91f7703bd..4e39b84f0 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -21,7 +21,7 @@ class TestPerspective:
params = dict(
batch_prob=batch_prob, start_points=start_points,
end_points=end_points, interpolation=torch.tensor(1),
- align_corners=False)
+ align_corners=torch.tensor(False))
out_data = F.apply_perspective(x_data, params)
assert out_data.shape == x_data.shape
@@ -43,7 +43,7 @@ class TestPerspective:
start_points=start_points,
end_points=end_points,
interpolation=torch.tensor(1),
- align_corners=False
+ align_corners=torch.tensor(False)
)
assert gradcheck(F.apply_perspective, (input, params,), raise_exception=True)