Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Remove assert statement from non-test files (#1206)

deepsource-autofix[bot]cc269cb88d8a
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index a6f9ba81f..2377d38ac 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1032,7 +1032,8 @@ class RandomCrop(GeometricAugmentationBase2D):
)
def compute_padding(self, shape: torch.Size) -> List[int]:
- assert len(shape) == 4, f"Expected BCHW. Got {shape}."
+ if len(shape) != 4:
+ raise AssertionError(f"Expected BCHW. Got {shape}.")
padding = [0, 0, 0, 0]
if self.padding is not None:
if isinstance(self.padding, int):
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 67f0f163d..ff43cf6af 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -268,12 +268,15 @@ class AugmentationBase2D(_AugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], (
- f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
- )
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 2:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
+ if len(mat.shape) != 2:
+ raise AssertionError('Input tensor is in non-batch mode ' 'but transformation matrix is not')
else:
raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
@@ -418,12 +421,15 @@ class AugmentationBase3D(_AugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 5:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], (
- f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
- )
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 4:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
+ if len(mat.shape) != 2:
+ raise AssertionError('Input tensor is in non-batch mode ' 'but transformation matrix is not')
else:
raise ValueError(f'Unrecognized output shape. Expected 3, 4 or 5, got {len(inp.shape)}')
@@ -459,12 +465,15 @@ class MixAugmentationBase(_BasicAugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], (
- f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
- )
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 2:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
+ if len(mat.shape) != 2:
+ raise AssertionError('Input tensor is in non-batch mode ' 'but transformation matrix is not')
else:
raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index a1ce126d2..925d2e79f 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -101,9 +101,8 @@ class AugmentationSequential(ImageSequential):
self.data_keys = [DataKey.get(inp) for inp in data_keys]
- assert all(
- in_type in DataKey for in_type in self.data_keys
- ), f"`data_keys` must be in {DataKey}. Got {data_keys}."
+ if not all(in_type in DataKey for in_type in self.data_keys):
+ raise AssertionError(f"`data_keys` must be in {DataKey}. Got {data_keys}.")
if self.data_keys[0] != DataKey.INPUT:
raise NotImplementedError(f"The first input must be {DataKey.INPUT}.")
@@ -243,9 +242,11 @@ class AugmentationSequential(ImageSequential):
"""
if data_keys is None:
data_keys = cast(List[Union[str, int, DataKey]], self.data_keys)
- assert len(args) == len(data_keys), (
- "The number of inputs must align with the number of data_keys, " f"Got {len(args)} and {len(data_keys)}."
- )
+ if len(args) != len(data_keys):
+ raise AssertionError(
+ "The number of inputs must align with the number of data_keys, "
+ f"Got {len(args)} and {len(data_keys)}."
+ )
if params is None:
if self._params is None:
raise ValueError(
@@ -315,9 +316,10 @@ class AugmentationSequential(ImageSequential):
else:
data_keys = [DataKey.get(inp) for inp in data_keys]
- assert len(args) == len(
- data_keys
- ), f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
+ if len(args) != len(data_keys):
+ raise AssertionError(
+ f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
+ )
if params is None:
if DataKey.INPUT in data_keys:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 9e2736cfa..1e1958f05 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -97,13 +97,13 @@ class ImageSequential(SequentialBase):
random_apply = (random_apply[0], max_length + 1)
else:
raise ValueError(f"Non-readable random_apply. Got {random_apply}.")
- if random_apply is not False:
- assert (
- isinstance(random_apply, (tuple,))
- and len(random_apply) == 2
- and isinstance(random_apply[0], (int,))
- and isinstance(random_apply[0], (int,))
- ), f"Expect a tuple of (int, int). Got {random_apply}."
+ if random_apply is not False and not (
+ isinstance(random_apply, (tuple,))
+ and len(random_apply) == 2
+ and isinstance(random_apply[0], (int,))
+ and isinstance(random_apply[0], (int,))
+ ):
+ raise AssertionError(f"Expect a tuple of (int, int). Got {random_apply}.")
return random_apply
def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:
@@ -175,7 +175,8 @@ class ImageSequential(SequentialBase):
elif isinstance(module, (_AugmentationBase,)):
input = module(input, params=param.data)
else:
- assert param.data is None, f"Non-augmentaion operation {param.name} require empty parameters. Got {param}."
+ if param.data is not None:
+ raise AssertionError(f"Non-augmentaion operation {param.name} require empty parameters. Got {param}.")
# In case of return_transform = True
if isinstance(input, (tuple, list)):
input = (module(input[0]), input[1])
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 88c960228..bd7250ea5 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -87,7 +87,8 @@ class VideoSequential(ImageSequential):
)
self.same_on_frame = same_on_frame
self.data_format = data_format.upper()
- assert self.data_format in ["BCTHW", "BTCHW"], f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."
+ if self.data_format not in ["BCTHW", "BTCHW"]:
+ raise AssertionError(f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`.")
self._temporal_channel: int
if self.data_format == "BCTHW":
self._temporal_channel = 2
@@ -181,7 +182,8 @@ class VideoSequential(ImageSequential):
self, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[ParamItem]] = None
) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:
"""Define the video computation performed."""
- assert len(input.shape) == 5, f"Input must be a 5-dim tensor. Got {input.shape}."
+ if len(input.shape) != 5:
+ raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")
if params is None:
params = self.forward_parameters(input.shape)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index c4930450d..6db364791 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -136,12 +136,10 @@ def random_perspective_generator(
The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
- assert (
- distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1
- ), f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}."
- assert (
- type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'height' and 'width' must be integers. Got {height}, {width}."
+ if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}.")
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
start_points: torch.Tensor = torch.tensor(
[[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
@@ -217,9 +215,8 @@ def random_affine_generator(
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(degrees, "degrees")
- assert (
- isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0
- ), f"`width` and `height` must be positive integers. Got {width}, {height}."
+ if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
+ raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
_device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])
degrees = degrees.to(device=device, dtype=dtype)
@@ -229,9 +226,8 @@ def random_affine_generator(
# compute tensor ranges
if scale is not None:
scale = scale.to(device=device, dtype=dtype)
- assert len(scale.shape) == 1 and (
- len(scale) == 2 or len(scale) == 4
- ), f"`scale` shall have 2 or 4 elements. Got {scale}."
+ if not (len(scale.shape) == 1 and (len(scale) == 2 or len(scale) == 4)):
+ raise AssertionError(f"`scale` shall have 2 or 4 elements. Got {scale}.")
_joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
_scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
if len(scale) == 4:
@@ -243,9 +239,8 @@ def random_affine_generator(
if translate is not None:
translate = translate.to(device=device, dtype=dtype)
- assert (
- 0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])
- ), f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}."
+ if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):
+ raise AssertionError(f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.")
max_dx: torch.Tensor = translate[0] * width
max_dy: torch.Tensor = translate[1] * height
translations = torch.stack(
@@ -384,13 +379,13 @@ def random_crop_generator(
size = torch.tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = size.to(device=_device, dtype=_dtype)
- assert size.shape == torch.Size([batch_size, 2]), (
- "If `size` is a tensor, it must be shaped as (B, 2). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
- )
- assert (
- input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()
- ), f"Got non-positive input size or size. {input_size}, {size}."
+ if size.shape != torch.Size([batch_size, 2]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 2). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
+ )
+ if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
+ raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
size = size.floor()
x_diff = input_size[1] - size[:, 1] + 1
@@ -428,13 +423,14 @@ def random_crop_generator(
size[:, 0],
)
else:
- assert (
+ if not (
len(resize_to) == 2
and isinstance(resize_to[0], (int,))
and isinstance(resize_to[1], (int,))
and resize_to[0] > 0
and resize_to[1] > 0
- ), f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}."
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}.")
crop_dst = torch.tensor(
[[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],
device=_device,
@@ -483,9 +479,8 @@ def random_crop_size_generator(
_common_param_check(batch_size, same_on_batch)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
- assert (
- len(size) == 2 and type(size[0]) is int and size[1] > 0 and type(size[1]) is int and size[1] > 0
- ), f"'height' and 'width' must be integers. Got {size}."
+ if not (len(size) == 2 and type(size[0]) is int and size[1] > 0 and type(size[1]) is int and size[1] > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {size}.")
_device, _dtype = _extract_device_dtype([scale, ratio])
@@ -568,12 +563,10 @@ def random_rectangles_params_generator(
"""
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([ratio, scale])
- assert (
- type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'height' and 'width' must be integers. Got {height}, {width}."
- assert (
- isinstance(value, (int, float)) and value >= 0 and value <= 1
- ), f"'value' must be a number between 0 - 1. Got {value}."
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ if not (isinstance(value, (int, float)) and value >= 0 and value <= 1):
+ raise AssertionError(f"'value' must be a number between 0 - 1. Got {value}.")
_joint_range_check(scale, 'scale', bounds=(0, float('inf')))
_joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
@@ -685,12 +678,10 @@ def center_crop_generator(
_common_param_check(batch_size)
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
- assert (
- type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'height' and 'width' must be integers. Got {height}, {width}."
- assert (
- height >= size[0] and width >= size[1]
- ), f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}."
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ if not (height >= size[0] and width >= size[1]):
+ raise AssertionError(f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}.")
# unpack input sizes
dst_h, dst_w = size
@@ -764,13 +755,13 @@ def random_motion_blur_generator(
_device, _dtype = _extract_device_dtype([angle, direction])
if isinstance(kernel_size, int):
- assert (
- kernel_size >= 3 and kernel_size % 2 == 1
- ), f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
+ if not (kernel_size >= 3 and kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
elif isinstance(kernel_size, tuple):
# kernel_size is fixed across the batch
- assert len(kernel_size) == 2, f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}."
+ if len(kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}.")
ksize_factor = (
_adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
)
@@ -1045,10 +1036,10 @@ def random_cutmix_generator(
_device, _dtype = _extract_device_dtype([beta, cut_size])
beta = torch.as_tensor(1.0 if beta is None else beta, device=device, dtype=dtype)
cut_size = torch.as_tensor([0.0, 1.0] if cut_size is None else cut_size, device=device, dtype=dtype)
- assert num_mix >= 1 and isinstance(num_mix, (int,)), f"`num_mix` must be an integer greater than 1. Got {num_mix}."
- assert (
- type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'height' and 'width' must be integers. Got {height}, {width}."
+ if not (num_mix >= 1 and isinstance(num_mix, (int,))):
+ raise AssertionError(f"`num_mix` must be an integer greater than 1. Got {num_mix}.")
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
_joint_range_check(cut_size, 'cut_size', bounds=(0, 1))
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 2bb0eef4a..d878a93ce 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -30,7 +30,8 @@ def random_rotation_generator3d(
- pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
- roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
"""
- assert degrees.shape == torch.Size([3, 2]), f"'degrees' must be the shape of (3, 2). Got {degrees.shape}."
+ if degrees.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
_device, _dtype = _extract_device_dtype([degrees])
degrees = degrees.to(device=device, dtype=dtype)
yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
@@ -90,12 +91,14 @@ def random_affine_generator3d(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
- assert (
+ if not (
type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}."
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
_device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
- assert degrees.shape == torch.Size([3, 2]), f"'degrees' must be the shape of (3, 2). Got {degrees.shape}."
+ if degrees.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
degrees = degrees.to(device=device, dtype=dtype)
yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
@@ -104,7 +107,8 @@ def random_affine_generator3d(
# compute tensor ranges
if scale is not None:
- assert scale.shape == torch.Size([3, 2]), f"'scale' must be the shape of (3, 2). Got {scale.shape}."
+ if scale.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'scale' must be the shape of (3, 2). Got {scale.shape}.")
scale = scale.to(device=device, dtype=dtype)
scale = torch.stack(
[
@@ -118,7 +122,8 @@ def random_affine_generator3d(
scale = torch.ones(batch_size, device=device, dtype=dtype).repeat(1, 3)
if translate is not None:
- assert translate.shape == torch.Size([3]), f"'translate' must be the shape of (2). Got {translate.shape}."
+ if translate.shape != torch.Size([3]):
+ raise AssertionError(f"'translate' must be the shape of (2). Got {translate.shape}.")
translate = translate.to(device=device, dtype=dtype)
max_dx: torch.Tensor = translate[0] * width
max_dy: torch.Tensor = translate[1] * height
@@ -140,7 +145,8 @@ def random_affine_generator3d(
center = center.expand(batch_size, -1)
if shears is not None:
- assert shears.shape == torch.Size([6, 2]), f"'shears' must be the shape of (6, 2). Got {shears.shape}."
+ if shears.shape != torch.Size([6, 2]):
+ raise AssertionError(f"'shears' must be the shape of (6, 2). Got {shears.shape}.")
shears = shears.to(device=device, dtype=dtype)
sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
@@ -200,14 +206,12 @@ def random_motion_blur_generator3d(
_device, _dtype = _extract_device_dtype([angle, direction])
_joint_range_check(direction, 'direction', (-1, 1))
if isinstance(kernel_size, int):
- assert (
- kernel_size >= 3 and kernel_size % 2 == 1
- ), f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
+ if not (kernel_size >= 3 and kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype).int()
elif isinstance(kernel_size, tuple):
- assert (
- len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1]
- ), f"`kernel_size` must be greater than 3. Got range {kernel_size}."
+ if not (len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1]):
+ raise AssertionError(f"`kernel_size` must be greater than 3. Got range {kernel_size}.")
# kernel_size is fixed across the batch
ksize_factor = (
_adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
@@ -215,7 +219,8 @@ def random_motion_blur_generator3d(
else:
raise TypeError(f"Unsupported type: {type(kernel_size)}")
- assert angle.shape == torch.Size([3, 2]), f"'angle' must be the shape of (3, 2). Got {angle.shape}."
+ if angle.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'angle' must be the shape of (3, 2). Got {angle.shape}.")
angle = angle.to(device=device, dtype=dtype)
yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
@@ -260,12 +265,12 @@ def center_crop_generator3d(
"""
if not isinstance(size, (tuple, list)) and len(size) == 3:
raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
- assert (
+ if not (
type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ), f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}."
- assert (
- depth >= size[0] and height >= size[1] and width >= size[2]
- ), f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}."
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+ if not (depth >= size[0] and height >= size[1] and width >= size[2]):
+ raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
if batch_size == 0:
return dict(src=torch.zeros([0, 8, 3]), dst=torch.zeros([0, 8, 3]))
@@ -364,11 +369,12 @@ def random_crop_generator3d(
size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
else:
size = size.to(device=device, dtype=dtype)
- assert size.shape == torch.Size([batch_size, 3]), (
- "If `size` is a tensor, it must be shaped as (B, 3). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
- )
- assert (
+ if size.shape != torch.Size([batch_size, 3]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 3). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
+ )
+ if not (
len(input_size) == 3
and isinstance(input_size[0], (int,))
and isinstance(input_size[1], (int,))
@@ -376,7 +382,8 @@ def random_crop_generator3d(
and input_size[0] > 0
and input_size[1] > 0
and input_size[2] > 0
- ), f"`input_size` must be a tuple of 3 positive integers. Got {input_size}."
+ ):
+ raise AssertionError(f"`input_size` must be a tuple of 3 positive integers. Got {input_size}.")
x_diff = input_size[2] - size[:, 2] + 1
y_diff = input_size[1] - size[:, 1] + 1
@@ -422,7 +429,7 @@ def random_crop_generator3d(
size[:, 0].to(device=_device, dtype=_dtype) - 1,
)
else:
- assert (
+ if not (
len(resize_to) == 3
and isinstance(resize_to[0], (int,))
and isinstance(resize_to[1], (int,))
@@ -430,7 +437,8 @@ def random_crop_generator3d(
and resize_to[0] > 0
and resize_to[1] > 0
and resize_to[2] > 0
- ), f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}."
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}.")
crop_dst = torch.tensor(
[
[
@@ -481,9 +489,8 @@ def random_perspective_generator3d(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
- assert (
- distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1
- ), f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}"
+ if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}")
_device, _dtype = _extract_device_dtype([distortion_scale])
distortion_scale = distortion_scale.to(device=device, dtype=dtype)
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 625ab0a0d..9ff6bf983 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -46,7 +46,8 @@ def _validate_input3d(f: Callable) -> Callable:
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
input_shape = len(input.shape)
- assert input_shape == 5, f'Expect input of 5 dimensions, got {input_shape} instead'
+ if input_shape != 5:
+ raise AssertionError(f'Expect input of 5 dimensions, got {input_shape} instead')
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return f(input, *args, **kwargs)
@@ -151,14 +152,15 @@ def _transform_output_shape(
trans_matrix = None
if trans_matrix is not None:
- if len(out_tensor.shape) > len(shape): # if output is broadcasted
- assert trans_matrix.shape[0] == 1, (
+ if len(out_tensor.shape) > len(shape) and trans_matrix.shape[0] != 1:
+ raise AssertionError(
f'Dimension 0 of transformation matrix is ' f'expected to be 1, got {trans_matrix.shape[0]}'
)
trans_matrix = trans_matrix.squeeze(0)
for dim in range(len(out_tensor.shape) - len(shape)):
- assert out_tensor.shape[0] == 1, f'Dimension {dim} of input is ' f'expected to be 1, got {out_tensor.shape[0]}'
+ if out_tensor.shape[0] != 1:
+ raise AssertionError(f'Dimension {dim} of input is ' f'expected to be 1, got {out_tensor.shape[0]}')
out_tensor = out_tensor.squeeze(0)
return (out_tensor, trans_matrix) if is_tuple else out_tensor # type: ignore
@@ -269,4 +271,5 @@ def _adapted_beta(
def _shape_validation(param: torch.Tensor, shape: Union[tuple, list], name: str) -> None:
- assert param.shape == torch.Size(shape), f"Invalid shape for {name}. Expected {shape}. Got {param.shape}"
+ if param.shape != torch.Size(shape):
+ raise AssertionError(f"Invalid shape for {name}. Expected {shape}. Got {param.shape}")
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index e769826db..a74380e63 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -5,9 +5,10 @@ import torch
def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
"""Valid batch_size and same_on_batch params."""
- assert type(batch_size) is int and batch_size >= 0, f"`batch_size` shall be a positive integer. Got {batch_size}."
- if same_on_batch is not None:
- assert type(same_on_batch) is bool, f"`same_on_batch` shall be boolean. Got {same_on_batch}."
+ if not (type(batch_size) is int and batch_size >= 0):
+ raise AssertionError(f"`batch_size` shall be a positive integer. Got {batch_size}.")
+ if same_on_batch is not None and type(same_on_batch) is not bool:
+ raise AssertionError(f"`same_on_batch` shall be boolean. Got {same_on_batch}.")
def _range_bound(
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index fca4e6c96..f132f3e17 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -401,9 +401,8 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(thresholds)}")
if isinstance(thresholds, torch.Tensor) and len(thresholds.shape) != 0:
- assert (
- input.size(0) == len(thresholds) and len(thresholds.shape) == 1
- ), f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}"
+ if not (input.size(0) == len(thresholds) and len(thresholds.shape) == 1):
+ raise AssertionError(f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}")
# TODO: I am not happy about this line, but no easy to do batch-wise operation
thresholds = thresholds.to(input.device).to(input.dtype)
thresholds = torch.stack([x.expand(*input.shape[-3:]) for x in thresholds])
@@ -464,14 +463,12 @@ def solarize(
if isinstance(additions, float):
additions = torch.tensor(additions)
- assert torch.all(
- (additions < 0.5) * (additions > -0.5)
- ), f"The value of 'addition' is between -0.5 and 0.5. Got {additions}."
+ if not torch.all((additions < 0.5) * (additions > -0.5)):
+ raise AssertionError(f"The value of 'addition' is between -0.5 and 0.5. Got {additions}.")
if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:
- assert (
- input.size(0) == len(additions) and len(additions.shape) == 1
- ), f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}"
+ if not (input.size(0) == len(additions) and len(additions.shape) == 1):
+ raise AssertionError(f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}")
# TODO: I am not happy about this line, but no easy to do batch-wise operation
additions = additions.to(input.device).to(input.dtype)
additions = torch.stack([x.expand(*input.shape[-3:]) for x in additions])
@@ -548,17 +545,20 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
res = []
if len(bits.shape) == 1:
- assert (
- bits.shape[0] == input.shape[0]
- ), f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."
+ if bits.shape[0] != input.shape[0]:
+ raise AssertionError(
+ f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."
+ )
for i in range(input.shape[0]):
res.append(_posterize_one(input[i], bits[i]))
return torch.stack(res, dim=0)
- assert (
- bits.shape == input.shape[: len(bits.shape)]
- ), f"Batch and channel must be equal between bits and input. Got {bits.shape}, {input.shape[:len(bits.shape)]}."
+ if bits.shape != input.shape[: len(bits.shape)]:
+ raise AssertionError(
+ "Batch and channel must be equal between bits and input. "
+ f"Got {bits.shape}, {input.shape[:len(bits.shape)]}."
+ )
_input = input.view(-1, *input.shape[len(bits.shape) :])
_bits = bits.flatten()
for i in range(input.shape[0]):
@@ -592,8 +592,8 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
if not isinstance(factor, torch.Tensor):
factor = torch.tensor(factor, device=input.device, dtype=input.dtype)
- if len(factor.size()) != 0:
- assert factor.shape == torch.Size([input.size(0)]), (
+ if len(factor.size()) != 0 and factor.shape != torch.Size([input.size(0)]):
+ raise AssertionError(
"Input batch size shall match with factor size if factor is not a 0-dim tensor. "
f"Got {input.size(0)} and {factor.shape}"
)
@@ -632,11 +632,13 @@ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor)
Returns:
: image tensor with the batch in the zero position.
"""
- assert isinstance(input1, torch.Tensor), f"`input1` must be a tensor. Got {input1}."
- assert isinstance(input2, torch.Tensor), f"`input1` must be a tensor. Got {input2}."
+ if not isinstance(input1, torch.Tensor):
+ raise AssertionError(f"`input1` must be a tensor. Got {input1}.")
+ if not isinstance(input2, torch.Tensor):
+ raise AssertionError(f"`input1` must be a tensor. Got {input2}.")
- if isinstance(factor, torch.Tensor):
- assert len(factor.size()) == 0, f"Factor shall be a float or single element tensor. Got {factor}."
+ if isinstance(factor, torch.Tensor) and len(factor.size()) != 0:
+ raise AssertionError(f"Factor shall be a float or single element tensor. Got {factor}.")
if factor == 0.0:
return input1
if factor == 1.0:
@@ -775,8 +777,10 @@ def invert(input: torch.Tensor, max_val: torch.Tensor = torch.tensor(1.0)) -> to
>>> invert(img, torch.tensor([[[[1.]]]])).shape
torch.Size([1, 3, 4, 4])
"""
- assert isinstance(input, torch.Tensor), f"Input is not a torch.Tensor. Got: {type(input)}"
- assert isinstance(max_val, torch.Tensor), f"max_val is not a torch.Tensor. Got: {type(max_val)}"
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input is not a torch.Tensor. Got: {type(input)}")
+ if not isinstance(max_val, torch.Tensor):
+ raise AssertionError(f"max_val is not a torch.Tensor. Got: {type(max_val)}")
return max_val.to(input.dtype) - input
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index ab41dbbee..2f90b7c51 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -60,8 +60,10 @@ def _compute_tiles(
.unfold(3, kernel_horz, kernel_horz)
.squeeze(1)
).contiguous() # GH x GW x C x TH x TW
- assert tiles.shape[-5] == grid_size[0] # check the grid size
- assert tiles.shape[-4] == grid_size[1]
+ if tiles.shape[-5] != grid_size[0]:
+ raise AssertionError
+ if tiles.shape[-4] != grid_size[1]:
+ raise AssertionError
return tiles, batch
@@ -79,9 +81,12 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2).
"""
- assert padded_imgs.dim() == 4, "Images Tensor must be 4D."
- assert padded_imgs.shape[-2] % tile_size[0] == 0, "Images are not correctly padded."
- assert padded_imgs.shape[-1] % tile_size[1] == 0, "Images are not correctly padded."
+ if padded_imgs.dim() != 4:
+ raise AssertionError("Images Tensor must be 4D.")
+ if padded_imgs.shape[-2] % tile_size[0] != 0:
+ raise AssertionError("Images are not correctly padded.")
+ if padded_imgs.shape[-1] % tile_size[1] != 0:
+ raise AssertionError("Images are not correctly padded.")
# tiles to be interpolated are built by dividing in 4 each alrady existing
interp_kernel_vert: int = tile_size[0] // 2
@@ -94,9 +99,12 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
.unfold(3, interp_kernel_horz, interp_kernel_horz)
.squeeze(1)
).contiguous() # 2GH x 2GW x C x TH/2 x TW/2
- assert interp_tiles.shape[-3] == c
- assert interp_tiles.shape[-2] == tile_size[0] / 2
- assert interp_tiles.shape[-1] == tile_size[1] / 2
+ if interp_tiles.shape[-3] != c:
+ raise AssertionError
+ if interp_tiles.shape[-2] != tile_size[0] / 2:
+ raise AssertionError
+ if interp_tiles.shape[-1] != tile_size[1] / 2:
+ raise AssertionError
return interp_tiles
@@ -121,7 +129,8 @@ def _compute_luts(
Lut for each tile (B, GH, GW, C, 256).
"""
- assert tiles_x_im.dim() == 6, "Tensor must be 6D."
+ if tiles_x_im.dim() != 6:
+ raise AssertionError("Tensor must be 6D.")
b, gh, gw, c, th, tw = tiles_x_im.shape
pixels: int = th * tw
@@ -166,8 +175,10 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
mapped luts (B, 2GH, 2GW, 4, C, 256)
"""
- assert interp_tiles.dim() == 6, "interp_tiles tensor must be 6D."
- assert luts.dim() == 5, "luts tensor must be 5D."
+ if interp_tiles.dim() != 6:
+ raise AssertionError("interp_tiles tensor must be 6D.")
+ if luts.dim() != 5:
+ raise AssertionError("luts tensor must be 5D.")
# gh, gw -> 2x the number of tiles used to compute the histograms
# th, tw -> /2 the sizes of the tiles used to compute the histograms
@@ -220,8 +231,10 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2)
"""
- assert interp_tiles.dim() == 6, "interp_tiles tensor must be 6D."
- assert luts.dim() == 5, "luts tensor must be 5D."
+ if interp_tiles.dim() != 6:
+ raise AssertionError("interp_tiles tensor must be 6D.")
+ if luts.dim() != 5:
+ raise AssertionError("luts tensor must be 5D.")
mapped_luts: torch.Tensor = _map_luts(interp_tiles, luts) # Bx2GHx2GWx4xCx256
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 453895f02..9538057f1 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -20,13 +20,16 @@ def match_nn(
- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
"""
- assert len(desc1.shape) == 2
- assert len(desc2.shape) == 2
+ if len(desc1.shape) != 2:
+ raise AssertionError
+ if len(desc2.shape) != 2:
+ raise AssertionError
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
- assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
+ raise AssertionError
match_dists, idxs_in_2 = torch.min(dm, dim=1)
idxs_in1: torch.Tensor = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
@@ -52,13 +55,16 @@ def match_mnn(
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
where 0 <= B3 <= min(B1, B2)
"""
- assert len(desc1.shape) == 2
- assert len(desc2.shape) == 2
+ if len(desc1.shape) != 2:
+ raise AssertionError
+ if len(desc2.shape) != 2:
+ raise AssertionError
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
- assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
+ raise AssertionError
ms = min(dm.size(0), dm.size(1))
match_dists, idxs_in_2 = torch.min(dm, dim=1)
@@ -97,14 +103,18 @@ def match_snn(
- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
"""
- assert len(desc1.shape) == 2
- assert len(desc2.shape) == 2
- assert desc2.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
+ if len(desc1.shape) != 2:
+ raise AssertionError
+ if len(desc2.shape) != 2:
+ raise AssertionError
+ if desc2.shape[0] < 2:
+ raise AssertionError
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
- assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
+ raise AssertionError
vals, idxs_in_2 = torch.topk(dm, 2, dim=1, largest=False)
ratio = vals[:, 0] / vals[:, 1]
@@ -137,15 +147,20 @@ def match_smnn(
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
"""
- assert len(desc1.shape) == 2
- assert len(desc2.shape) == 2
- assert desc1.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
- assert desc2.shape[0] >= 2 # to performs second nearest check, we need at least two descriptors
+ if len(desc1.shape) != 2:
+ raise AssertionError
+ if len(desc2.shape) != 2:
+ raise AssertionError
+ if desc1.shape[0] < 2:
+ raise AssertionError
+ if desc2.shape[0] < 2:
+ raise AssertionError
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
- assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+ if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
+ raise AssertionError
dists1, idx1 = match_snn(desc1, desc2, th, dm)
dists2, idx2 = match_snn(desc2, desc1, th, dm.t())
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index 9d1c27695..29741ccb3 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -34,8 +34,10 @@ class NonMaximaSuppression2d(nn.Module):
@staticmethod
def _compute_zero_padding2d(kernel_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
- assert isinstance(kernel_size, tuple), type(kernel_size)
- assert len(kernel_size) == 2, kernel_size
+ if not isinstance(kernel_size, tuple):
+ raise AssertionError(type(kernel_size))
+ if len(kernel_size) != 2:
+ raise AssertionError(kernel_size)
def pad(x):
return (x - 1) // 2 # zero padding function
@@ -44,7 +46,8 @@ class NonMaximaSuppression2d(nn.Module):
return (pad(ky), pad(ky), pad(kx), pad(kx))
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
- assert len(x.shape) == 4, x.shape
+ if len(x.shape) != 4:
+ raise AssertionError(x.shape)
B, CH, H, W = x.size()
# find local maximum values
max_non_center = (
@@ -74,8 +77,10 @@ class NonMaximaSuppression3d(nn.Module):
@staticmethod
def _compute_zero_padding3d(kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int, int, int, int]:
- assert isinstance(kernel_size, tuple), type(kernel_size)
- assert len(kernel_size) == 3, kernel_size
+ if not isinstance(kernel_size, tuple):
+ raise AssertionError(type(kernel_size))
+ if len(kernel_size) != 3:
+ raise AssertionError(kernel_size)
def pad(x):
return (x - 1) // 2 # zero padding function
@@ -84,7 +89,8 @@ class NonMaximaSuppression3d(nn.Module):
return pad(kd), pad(kd), pad(ky), pad(ky), pad(kx), pad(kx)
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
- assert len(x.shape) == 5, x.shape
+ if len(x.shape) != 5:
+ raise AssertionError(x.shape)
# find local maximum values
B, CH, D, H, W = x.size()
max_non_center = (
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 67ba8b64d..efaeb220a 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -185,9 +185,8 @@ def max_blur_pool2d(
def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: int):
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(
- -2
- ), f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
+ if not (len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2)):
+ raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))
@@ -196,9 +195,8 @@ def _max_blur_pool_by_kernel2d(
input: torch.Tensor, kernel: torch.Tensor, stride: int, max_pool_size: int, ceil_mode: bool
):
"""Compute max_blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(
- -2
- ), f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
+ if not (len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2)):
+ raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
# compute local maxima
input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
# blur and downsample
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 7c99a25ca..4e619d8cf 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -11,7 +11,8 @@ def _compute_padding(kernel_size: List[int]) -> List[int]:
"""Computes padding tuple."""
# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
- assert len(kernel_size) >= 2, kernel_size
+ if len(kernel_size) < 2:
+ raise AssertionError(kernel_size)
computed = [k // 2 for k in kernel_size]
# for even kernels we need to do asymetric padding :(
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 0d84779c2..6e0c0cd3d 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -55,7 +55,8 @@ def get_motion_kernel2d(
angle = cast(torch.Tensor, angle)
if angle.dim() == 0:
angle = angle.unsqueeze(0)
- assert angle.dim() == 1, f"angle must be a 1-dim tensor. Got {angle}."
+ if angle.dim() != 1:
+ raise AssertionError(f"angle must be a 1-dim tensor. Got {angle}.")
if not isinstance(direction, torch.Tensor):
direction = torch.tensor([direction], device=device, dtype=dtype)
@@ -63,11 +64,11 @@ def get_motion_kernel2d(
direction = cast(torch.Tensor, direction)
if direction.dim() == 0:
direction = direction.unsqueeze(0)
- assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."
+ if direction.dim() != 1:
+ raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")
- assert direction.size(0) == angle.size(
- 0
- ), f"direction and angle must have the same length. Got {direction} and {angle}."
+ if direction.size(0) != angle.size(0):
+ raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")
kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)
# direction from [-1, 1] to [0, 1] range
@@ -82,7 +83,8 @@ def get_motion_kernel2d(
# kernel[:, kernel_size // 2, :] = direction[:, None].repeat(1, kernel_size) + m * torch.arange(0, kernel_size)
k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
kernel = torch.nn.functional.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
- assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])
+ if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):
+ raise AssertionError
kernel = kernel.unsqueeze(1)
# rotate (counterclockwise) kernel by given angle
kernel = rotate(kernel, angle, mode=mode, align_corners=True)
@@ -156,7 +158,8 @@ def get_motion_kernel3d(
angle = cast(torch.Tensor, angle)
if angle.dim() == 1:
angle = angle.unsqueeze(0)
- assert len(angle.shape) == 2 and angle.size(1) == 3, f"angle must be (B, 3). Got {angle}."
+ if not (len(angle.shape) == 2 and angle.size(1) == 3):
+ raise AssertionError(f"angle must be (B, 3). Got {angle}.")
if not isinstance(direction, torch.Tensor):
direction = torch.tensor([direction], device=device, dtype=dtype)
@@ -164,11 +167,11 @@ def get_motion_kernel3d(
direction = cast(torch.Tensor, direction)
if direction.dim() == 0:
direction = direction.unsqueeze(0)
- assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."
+ if direction.dim() != 1:
+ raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")
- assert direction.size(0) == angle.size(
- 0
- ), f"direction and angle must have the same length. Got {direction} and {angle}."
+ if direction.size(0) != angle.size(0):
+ raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")
kernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)
# direction from [-1, 1] to [0, 1] range
@@ -182,7 +185,8 @@ def get_motion_kernel3d(
kernel = torch.nn.functional.pad(
k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0]
)
- assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])
+ if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):
+ raise AssertionError
kernel = kernel.unsqueeze(1)
# rotate (counterclockwise) kernel by given angle
kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 17fecdf02..f8c3d08af 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -145,7 +145,8 @@ def motion_blur(
>>> torch.allclose(out_1[0], out_1[1])
False
"""
- assert border_type in ["constant", "reflect", "replicate", "circular"]
+ if border_type not in ["constant", "reflect", "replicate", "circular"]:
+ raise AssertionError
kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction, mode)
return kornia.filter2d(input, kernel, border_type)
@@ -188,6 +189,7 @@ def motion_blur3d(
>>> torch.allclose(out_1[0], out_1[1])
False
"""
- assert border_type in ["constant", "reflect", "replicate", "circular"]
+ if border_type not in ["constant", "reflect", "replicate", "circular"]:
+ raise AssertionError
kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction, mode)
return kornia.filter3d(input, kernel, border_type)
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index aeeacaabd..f75de75d3 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -14,9 +14,8 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,
bottom-left. The coordinates must be in the x, y order.
"""
- assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
- [4, 2]
- ), f"Box shape must be (B, 4, 2). Got {boxes.shape}."
+ if not (len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([4, 2])):
+ raise AssertionError(f"Box shape must be (B, 4, 2). Got {boxes.shape}.")
if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):
raise ValueError(
@@ -43,28 +42,24 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.
The coordinates must be in the x, y, z order.
"""
- assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
- [8, 3]
- ), f"Box shape must be (B, 8, 3). Got {boxes.shape}."
+ if not (len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([8, 3])):
+ raise AssertionError(f"Box shape must be (B, 8, 3). Got {boxes.shape}.")
left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
widths = left - right + 1
- assert torch.allclose(
- widths.permute(1, 0), widths[:, 0]
- ), f"Boxes must have be cube, while get different widths {widths}."
+ if not torch.allclose(widths.permute(1, 0), widths[:, 0]):
+ raise AssertionError(f"Boxes must have be cube, while get different widths {widths}.")
bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
heights = bot - upper + 1
- assert torch.allclose(
- heights.permute(1, 0), heights[:, 0]
- ), f"Boxes must have be cube, while get different heights {heights}."
+ if not torch.allclose(heights.permute(1, 0), heights[:, 0]):
+ raise AssertionError(f"Boxes must have be cube, while get different heights {heights}.")
depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
- assert torch.allclose(
- depths.permute(1, 0), depths[:, 0]
- ), f"Boxes must have be cube, while get different depths {depths}."
+ if not torch.allclose(depths.permute(1, 0), depths[:, 0]):
+ raise AssertionError(f"Boxes must have be cube, while get different depths {depths}.")
return True
@@ -312,22 +307,21 @@ def bbox_generator(
[3, 3],
[1, 3]]])
"""
- assert x_start.shape == y_start.shape and x_start.dim() in [
- 0,
- 1,
- ], f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
- assert width.shape == height.shape and width.dim() in [
- 0,
- 1,
- ], f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
- assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (
- "All tensors must be in the same dtype. Got "
- f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
- )
- assert x_start.device == y_start.device == width.device == height.device, (
- "All tensors must be in the same device. Got "
- f"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device})."
- )
+ if not (x_start.shape == y_start.shape and x_start.dim() in [0, 1]):
+ raise AssertionError(f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}.")
+ if not (width.shape == height.shape and width.dim() in [0, 1]):
+ raise AssertionError(f"`width` and `height` must be a scalar or (B,). Got {width}, {height}.")
+ if not x_start.dtype == y_start.dtype == width.dtype == height.dtype:
+ raise AssertionError(
+ "All tensors must be in the same dtype. Got "
+ f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
+ )
+ if not x_start.device == y_start.device == width.device == height.device:
+ raise AssertionError(
+ "All tensors must be in the same device. Got "
+ f"`x_start`({x_start.device}), `y_start`({x_start.device}), "
+ f"`width`({width.device}), `height`({height.device})."
+ )
bbox = torch.tensor([[[0, 0], [0, 0], [0, 0], [0, 0]]], device=x_start.device, dtype=x_start.dtype).repeat(
1 if x_start.dim() == 0 else len(x_start), 1, 1
@@ -393,24 +387,24 @@ def bbox_generator3d(
[43, 54, 65],
[ 3, 54, 65]]])
"""
- assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [
- 0,
- 1,
- ], f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
- assert width.shape == height.shape == depth.shape and width.dim() in [
- 0,
- 1,
- ], f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
- assert x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype, (
- "All tensors must be in the same dtype. "
- f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
- f"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype})."
- )
- assert x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device, (
- "All tensors must be in the same device. "
- f"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), "
- f"`width`({width.device}), `height`({height.device}) and `depth`({depth.device})."
- )
+ if not (x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1]):
+ raise AssertionError(
+ f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
+ )
+ if not (width.shape == height.shape == depth.shape and width.dim() in [0, 1]):
+ raise AssertionError(f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}.")
+ if not x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype:
+ raise AssertionError(
+ "All tensors must be in the same dtype. "
+ f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
+ f"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype})."
+ )
+ if not x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device:
+ raise AssertionError(
+ "All tensors must be in the same device. "
+ f"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), "
+ f"`width`({width.device}), `height`({height.device}) and `depth`({depth.device})."
+ )
# front
bbox = torch.tensor(
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 982006321..ea94efc05 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -12,8 +12,10 @@ def inverseTiltProjection(taux: torch.Tensor, tauy: torch.Tensor) -> torch.Tenso
Returns:
torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.
"""
- assert taux.dim() == tauy.dim()
- assert taux.numel() == tauy.numel()
+ if taux.dim() != tauy.dim():
+ raise AssertionError
+ if taux.numel() != tauy.numel():
+ raise AssertionError
ndim = taux.dim()
taux = taux.reshape(-1)
@@ -60,9 +62,12 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor)
Returns:
Undistorted 2D points with shape :math:`(*, N, 2)`.
"""
- assert points.dim() >= 2 and points.shape[-1] == 2
- assert K.shape[-2:] == (3, 3)
- assert dist.shape[-1] in [4, 5, 8, 12, 14]
+ if not (points.dim() >= 2 and points.shape[-1] == 2):
+ raise AssertionError
+ if K.shape[-2:] != (3, 3):
+ raise AssertionError
+ if dist.shape[-1] not in [4, 5, 8, 12, 14]:
+ raise AssertionError
if dist.shape[-1] < 14:
dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]])
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index b7ebf7d8c..ee58b2104 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -66,7 +66,8 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 4, 4)`.
"""
- assert self._check_valid_params(self._intrinsics, "intrinsics")
+ if not self._check_valid_params(self._intrinsics, "intrinsics"):
+ raise AssertionError
return self._intrinsics
@property
@@ -76,7 +77,8 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 4, 4)`.
"""
- assert self._check_valid_params(self._extrinsics, "extrinsics")
+ if not self._check_valid_params(self._extrinsics, "extrinsics"):
+ raise AssertionError
return self._extrinsics
@property
@@ -387,7 +389,8 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
# warnings.warn("pinhole_matrix will be deprecated in version 0.2, "
# "use PinholeCamera.camera_matrix instead",
# PendingDeprecationWarning)
- assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
+ if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
+ raise AssertionError(pinholes.shape)
# unpack pinhole values
fx, fy, cx, cy = torch.chunk(pinholes[..., :4], 4, dim=1) # Nx1
# create output container
@@ -430,7 +433,8 @@ def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Te
# warnings.warn("inverse_pinhole_matrix will be deprecated in version 0.2, "
# "use PinholeCamera.intrinsics_inverse() instead",
# PendingDeprecationWarning)
- assert len(pinhole.shape) == 2 and pinhole.shape[1] == 12, pinhole.shape
+ if not (len(pinhole.shape) == 2 and pinhole.shape[1] == 12):
+ raise AssertionError(pinhole.shape)
# unpack pinhole values
fx, fy, cx, cy = torch.chunk(pinhole[..., :4], 4, dim=1) # Nx1
# create output container
@@ -473,8 +477,10 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
# warnings.warn("scale_pinhole will be deprecated in version 0.2, "
# "use PinholeCamera.scale() instead",
# PendingDeprecationWarning)
- assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
- assert len(scale.shape) == 1, scale.shape
+ if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
+ raise AssertionError(pinholes.shape)
+ if len(scale.shape) != 1:
+ raise AssertionError(scale.shape)
pinholes_scaled = pinholes.clone()
pinholes_scaled[..., :6] = pinholes[..., :6] * scale.unsqueeze(-1)
return pinholes_scaled
@@ -491,7 +497,8 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
tensor of extrinsic transformation matrices of size (N, 4, 4).
"""
- assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
+ if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
+ raise AssertionError(pinholes.shape)
optical_pose_parent = pinholes[..., 6:]
# TODO: where is rtvec_to_pose?
return rtvec_to_pose(optical_pose_parent) # type: ignore
@@ -534,8 +541,10 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> to
homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4
"""
# TODO: Add doctest once having `rtvec_to_pose`.
- assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole_i.shape
- assert pinhole_i.shape == pinhole_ref.shape, pinhole_ref.shape
+ if not (len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12):
+ raise AssertionError(pinhole_i.shape)
+ if pinhole_i.shape != pinhole_ref.shape:
+ raise AssertionError(pinhole_ref.shape)
i_pose_base = get_optical_pose_base(pinhole_i)
ref_pose_base = get_optical_pose_base(pinhole_ref)
i_pose_ref = torch.matmul(i_pose_base, inverse_transformation(ref_pose_base))
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 4d693dbbe..daf75d1ad 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -20,10 +20,14 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
The essential matrix with shape :math:`(*, 3, 3)`.
"""
- assert len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3), F_mat.shape
- assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
- assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
- assert len(F_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+ if not (len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3)):
+ raise AssertionError(F_mat.shape)
+ if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):
+ raise AssertionError(K1.shape)
+ if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):
+ raise AssertionError(K2.shape)
+ if not len(F_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):
+ raise AssertionError
return K2.transpose(-2, -1) @ F_mat @ K1
@@ -42,7 +46,8 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch
The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.
"""
- assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
+ if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:]):
+ raise AssertionError(E_mat.shape)
# decompose matrix by its singular values
U, S, V = torch.svd(E_mat)
@@ -86,10 +91,14 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:
The Essential matrix with the shape :math:`(*, 3, 3)`.
"""
- assert len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3), R1.shape
- assert len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1), t1.shape
- assert len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3), R2.shape
- assert len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1), t2.shape
+ if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):
+ raise AssertionError(R1.shape)
+ if not (len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1)):
+ raise AssertionError(t1.shape)
+ if not (len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3)):
+ raise AssertionError(R2.shape)
+ if not (len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1)):
+ raise AssertionError(t2.shape)
# first compute the camera relative motion
R, t = relative_camera_motion(R1, t1, R2, t2)
@@ -114,7 +123,8 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tens
The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`.
"""
- assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
+ if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:]):
+ raise AssertionError(E_mat.shape)
# decompose the essential matrix by its possible poses
R1, R2, t = decompose_essential_matrix(E_mat)
@@ -159,15 +169,23 @@ def motion_from_essential_choose_solution(
The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.
"""
- assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape
- assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
- assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
- assert len(x1.shape) >= 2 and x1.shape[-1] == 2, x1.shape
- assert len(x2.shape) >= 2 and x2.shape[-1] == 2, x2.shape
- assert len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+ if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:]):
+ raise AssertionError(E_mat.shape)
+ if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):
+ raise AssertionError(K1.shape)
+ if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):
+ raise AssertionError(K2.shape)
+ if not (len(x1.shape) >= 2 and x1.shape[-1] == 2):
+ raise AssertionError(x1.shape)
+ if not (len(x2.shape) >= 2 and x2.shape[-1] == 2):
+ raise AssertionError(x2.shape)
+ if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):
+ raise AssertionError
if mask is not None:
- assert len(mask.shape) >= 1, mask.shape
- assert mask.shape == x1.shape[:-1], mask.shape
+ if len(mask.shape) < 1:
+ raise AssertionError(mask.shape)
+ if mask.shape != x1.shape[:-1]:
+ raise AssertionError(mask.shape)
unbatched = len(E_mat.shape) == 2
@@ -250,10 +268,14 @@ def relative_camera_motion(
translation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`.
"""
- assert len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3), R1.shape
- assert len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1), t1.shape
- assert len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3), R2.shape
- assert len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1), t2.shape
+ if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):
+ raise AssertionError(R1.shape)
+ if not (len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1)):
+ raise AssertionError(t1.shape)
+ if not (len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3)):
+ raise AssertionError(R2.shape)
+ if not (len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1)):
+ raise AssertionError(t2.shape)
# compute first the relative rotation
R = R2 @ R1.transpose(-2, -1)
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 6c23924ee..6af7436a1 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -26,8 +26,10 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
in the shape :math:`(B, 3, 3)`.
"""
- assert len(points.shape) == 3, points.shape
- assert points.shape[-1] == 2, points.shape
+ if len(points.shape) != 3:
+ raise AssertionError(points.shape)
+ if points.shape[-1] != 2:
+ raise AssertionError(points.shape)
x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1x2
@@ -60,7 +62,8 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
the normalized transformation matrix with same shape as the input.
"""
- assert len(M.shape) >= 2, M.shape
+ if len(M.shape) < 2:
+ raise AssertionError(M.shape)
norm_val: torch.Tensor = M[..., -1:, -1:]
return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
@@ -79,8 +82,10 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
the computed fundamental matrix with shape :math:`(B, 3, 3)`.
"""
- assert points1.shape == points2.shape, (points1.shape, points2.shape)
- assert len(weights.shape) == 2 and weights.shape[1] == points1.shape[1], weights.shape
+ if points1.shape != points2.shape:
+ raise AssertionError(points1.shape, points2.shape)
+ if not (len(weights.shape) == 2 and weights.shape[1] == points1.shape[1]):
+ raise AssertionError(weights.shape)
points1_norm, transform1 = normalize_points(points1)
points2_norm, transform2 = normalize_points(points2)
@@ -127,8 +132,10 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
"""
- assert len(points.shape) == 3 and points.shape[2] == 2, points.shape
- assert len(F_mat.shape) == 3 and F_mat.shape[-2:] == (3, 3), F_mat.shape
+ if not (len(points.shape) == 3 and points.shape[2] == 2):
+ raise AssertionError(points.shape)
+ if not (len(F_mat.shape) == 3 and F_mat.shape[-2:] == (3, 3)):
+ raise AssertionError(F_mat.shape)
points_h: torch.Tensor = kornia.convert_points_to_homogeneous(points)
@@ -157,10 +164,14 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
The fundamental matrix with shape :math:`(*, 3, 3)`.
"""
- assert len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3), E_mat.shape
- assert len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3), K1.shape
- assert len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3), K2.shape
- assert len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2])
+ if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):
+ raise AssertionError(E_mat.shape)
+ if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):
+ raise AssertionError(K1.shape)
+ if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):
+ raise AssertionError(K2.shape)
+ if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):
+ raise AssertionError
return K2.inverse().transpose(-2, -1) @ E_mat @ K1.inverse()
@@ -181,9 +192,12 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te
The fundamental matrix with shape :math:`(*, 3, 3)`.
"""
- assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shape
- assert len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4), P2.shape
- assert P1.shape[:-2] == P2.shape[:-2] # this function does not support broadcasting
+ if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):
+ raise AssertionError(P1.shape)
+ if not (len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4)):
+ raise AssertionError(P2.shape)
+ if P1.shape[:-2] != P2.shape[:-2]:
+ raise AssertionError
def vstack(x, y):
return torch.cat([x, y], dim=-2)
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index b81ff6953..f795c3e44 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -15,7 +15,8 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
The constructed cross_product_matrix symmetric matrix with shape :math:`(B, 3, 3)`.
"""
- assert len(x.shape) == 2 and x.shape[1] == 3, x.shape
+ if not (len(x.shape) == 2 and x.shape[1] == 3):
+ raise AssertionError(x.shape)
# get vector compononens
x0 = x[..., 0]
x1 = x[..., 1]
@@ -39,8 +40,10 @@ def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:
The identity matrix with same size as input :math:`(*, N, N)`.
"""
- assert n > 0, (type(n), n)
- assert len(input.shape) >= 1, input.shape
+ if n <= 0:
+ raise AssertionError(type(n), n)
+ if len(input.shape) < 1:
+ raise AssertionError(input.shape)
identity = torch.eye(n, device=input.device, dtype=input.dtype)
return identity[None].repeat(input.shape[0], 1, 1)
@@ -58,8 +61,10 @@ def vec_like(n, tensor):
The vector with same size as input :math:`(*, N, 1)`.
"""
- assert n > 0, (type(n), n)
- assert len(tensor.shape) >= 1, tensor.shape
+ if n <= 0:
+ raise AssertionError(type(n), n)
+ if len(tensor.shape) < 1:
+ raise AssertionError(tensor.shape)
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].repeat(tensor.shape[0], 1, 1)
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 4acb603f0..91b126265 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -20,8 +20,10 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
The camera matrix with the shape of :math:`(B, 3, 3)`.
"""
- assert len(input.shape) == 4, input.shape
- assert focal > 0, focal
+ if len(input.shape) != 4:
+ raise AssertionError(input.shape)
+ if focal <= 0:
+ raise AssertionError(focal)
B, _, H, W = input.shape
@@ -87,10 +89,14 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
The projection matrix P with shape :math:`(B, 4, 4)`.
"""
- assert K.shape[-2:] == (3, 3), K.shape
- assert R.shape[-2:] == (3, 3), R.shape
- assert t.shape[-2:] == (3, 1), t.shape
- assert len(K.shape) == len(R.shape) == len(t.shape)
+ if K.shape[-2:] != (3, 3):
+ raise AssertionError(K.shape)
+ if R.shape[-2:] != (3, 3):
+ raise AssertionError(R.shape)
+ if t.shape[-2:] != (3, 1):
+ raise AssertionError(t.shape)
+ if not len(K.shape) == len(R.shape) == len(t.shape):
+ raise AssertionError
Rt: torch.Tensor = torch.cat([R, t], dim=-1) # 3x4
Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
@@ -114,8 +120,10 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
- The Translation vector with shape :math:`(B, 3)`.
"""
- assert P.shape[-2:] == (3, 4), "P must be of shape [B, 3, 4]"
- assert len(P.shape) == 3
+ if P.shape[-2:] != (3, 4):
+ raise AssertionError("P must be of shape [B, 3, 4]")
+ if len(P.shape) != 3:
+ raise AssertionError
submat_3x3 = P[:, 0:3, 0:3]
last_column = P[:, 0:3, 3].unsqueeze(-1)
@@ -179,8 +187,10 @@ def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
The projection matrices with shape :math:`(*, 4, 4, 2)`.
"""
- assert len(F_mat.shape) >= 2, F_mat.shape
- assert F_mat.shape[-2:] == (3, 3), F_mat.shape
+ if len(F_mat.shape) < 2:
+ raise AssertionError(F_mat.shape)
+ if F_mat.shape[-2:] != (3, 3):
+ raise AssertionError(F_mat.shape)
R1 = numeric.eye_like(3, F_mat) # Bx3x3
t1 = numeric.vec_like(3, F_mat) # Bx3
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index ebfa5f2b5..29a23dca7 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -30,13 +30,20 @@ def triangulate_points(
The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.
"""
- assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shape
- assert len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4), P2.shape
- assert len(P1.shape[:-2]) == len(P2.shape[:-2]), (P1.shape, P2.shape)
- assert len(points1.shape) >= 2 and points1.shape[-1] == 2, points1.shape
- assert len(points2.shape) >= 2 and points2.shape[-1] == 2, points2.shape
- assert len(points1.shape[:-2]) == len(points2.shape[:-2]), (points1.shape, points2.shape)
- assert len(P1.shape[:-2]) == len(points1.shape[:-2]), (P1.shape, points1.shape)
+ if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):
+ raise AssertionError(P1.shape)
+ if not (len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4)):
+ raise AssertionError(P2.shape)
+ if len(P1.shape[:-2]) != len(P2.shape[:-2]):
+ raise AssertionError(P1.shape, P2.shape)
+ if not (len(points1.shape) >= 2 and points1.shape[-1] == 2):
+ raise AssertionError(points1.shape)
+ if not (len(points2.shape) >= 2 and points2.shape[-1] == 2):
+ raise AssertionError(points2.shape)
+ if len(points1.shape[:-2]) != len(points2.shape[:-2]):
+ raise AssertionError(points1.shape, points2.shape)
+ if len(P1.shape[:-2]) != len(points1.shape[:-2]):
+ raise AssertionError(P1.shape, points1.shape)
# allocate and construct the equations matrix with shape (*, 4, 4)
points_shape = max(points1.shape, points2.shape) # this allows broadcasting
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 564fa4589..6b397d591 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -25,9 +25,12 @@ def find_homography_dlt(
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
"""
- assert points1.shape == points2.shape, points1.shape
- assert len(points1.shape) >= 1 and points1.shape[-1] == 2, points1.shape
- assert points1.shape[1] >= 4, points1.shape
+ if points1.shape != points2.shape:
+ raise AssertionError(points1.shape)
+ if not (len(points1.shape) >= 1 and points1.shape[-1] == 2):
+ raise AssertionError(points1.shape)
+ if points1.shape[1] < 4:
+ raise AssertionError(points1.shape)
device, dtype = _extract_device_dtype([points1, points2])
@@ -49,7 +52,8 @@ def find_homography_dlt(
A = A.transpose(-2, -1) @ A
else:
# We should use provided weights
- assert len(weights.shape) == 2 and weights.shape == points1.shape[:2], weights.shape
+ if not (len(weights.shape) == 2 and weights.shape == points1.shape[:2]):
+ raise AssertionError(weights.shape)
w_diag = torch.diag_embed(weights.unsqueeze(dim=-1).repeat(1, 1, 2).reshape(weights.shape[0], -1))
A = A.transpose(-2, -1) @ w_diag @ A
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 06325b4e6..c04416643 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -33,7 +33,8 @@ __all__ = [
def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
"""Computes the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W)."""
- assert 2 <= len(tensor.shape) <= 4, f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}."
+ if not 2 <= len(tensor.shape) <= 4:
+ raise AssertionError(f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}.")
height, width = tensor.shape[-2:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
@@ -43,7 +44,8 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
"""Computes the center of tensor plane for (D, H, W), (C, D, H, W) and (B, C, D, H, W)."""
- assert 3 <= len(tensor.shape) <= 5, f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}."
+ if not 3 <= len(tensor.shape) <= 5:
+ raise AssertionError(f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}.")
depth, height, width = tensor.shape[-3:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
@@ -73,9 +75,8 @@ def _compute_rotation_matrix3d(
pitch = pitch.unsqueeze(dim=1)
roll = roll.unsqueeze(dim=1)
- assert (
- len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2
- ), f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}."
+ if not (len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2):
+ raise AssertionError(f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}.")
angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)
scales: torch.Tensor = torch.ones_like(yaw)
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index cdc8dd709..4fc2c2fb5 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -74,7 +74,8 @@ def crop_and_resize(
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
- assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
# unpack input data
dst_h, dst_w = size
@@ -131,7 +132,8 @@ def center_crop(
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
- assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
# unpack input sizes
dst_h, dst_w = size
@@ -224,16 +226,19 @@ def crop_by_boxes(
_validate_bbox(src_box)
_validate_bbox(dst_box)
- assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor), dst_box.to(tensor))
bbox: Tuple[torch.Tensor, torch.Tensor] = _infer_bbox_shape(dst_box)
- assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (
- f"Cropping height, width and depth must be exact same in a batch. " f"Got height {bbox[0]} and width {bbox[1]}."
- )
+ if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
+ raise AssertionError(
+ f"Cropping height, width and depth must be exact same in a batch. "
+ f"Got height {bbox[0]} and width {bbox[1]}."
+ )
h_out: int = int(bbox[0][0].item())
w_out: int = int(bbox[1][0].item())
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
index 1e860f79a..8830b26a1 100644
--- a/kornia/geometry/transform/crop/crop3d.py
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -89,7 +89,8 @@ def crop_and_resize3d(
raise TypeError("Input boxes type is not a torch.Tensor. Got {}".format(type(boxes)))
if not isinstance(size, (tuple, list)) and len(size) != 3:
raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
- assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 5:
+ raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
# unpack input data
dst_d, dst_h, dst_w = size[0], size[1], size[2]
@@ -168,7 +169,8 @@ def center_crop3d(
if not isinstance(tensor, (torch.Tensor)):
raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
- assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 5:
+ raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
if not isinstance(size, (tuple, list)) and len(size) == 3:
raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
@@ -312,7 +314,8 @@ def crop_by_boxes3d(
_validate_bbox3d(src_box)
_validate_bbox3d(dst_box)
- assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+ if len(tensor.shape) != 5:
+ raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
@@ -321,10 +324,11 @@ def crop_by_boxes3d(
dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
bbox = _infer_bbox_shape3d(dst_box)
- assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all(), (
- "Cropping height, width and depth must be exact same in a batch."
- f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}."
- )
+ if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all()):
+ raise AssertionError(
+ "Cropping height, width and depth must be exact same in a batch."
+ f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}."
+ )
patches: torch.Tensor = crop_by_transform_mat3d(
tensor,
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index d92cc51f2..88a96166b 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -48,9 +48,12 @@ def warp_affine3d(
.. note::
This function is often used in conjuntion with :func:`get_perspective_transform3d`.
"""
- assert len(src.shape) == 5, src.shape
- assert len(M.shape) == 3 and M.shape[-2:] == (3, 4), M.shape
- assert len(dsize) == 3, dsize
+ if len(src.shape) != 5:
+ raise AssertionError(src.shape)
+ if not (len(M.shape) == 3 and M.shape[-2:] == (3, 4)):
+ raise AssertionError(M.shape)
+ if len(dsize) != 3:
+ raise AssertionError(dsize)
B, C, D, H, W = src.size()
# TODO: remove the statement below in kornia v0.6
@@ -99,8 +102,10 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
the projection matrix with shape :math:`(*, 3, 4)`.
"""
- assert len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3), rmat.shape
- assert len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1), tvec.shape
+ if not (len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3)):
+ raise AssertionError(rmat.shape)
+ if not (len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1)):
+ raise AssertionError(tvec.shape)
return torch.cat([rmat, tvec], dim=-1) # Bx3x4
@@ -126,10 +131,14 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
.. note::
This function is often used in conjuntion with :func:`warp_affine3d`.
"""
- assert len(center.shape) == 2 and center.shape[-1] == 3, center.shape
- assert len(angles.shape) == 2 and angles.shape[-1] == 3, angles.shape
- assert center.device == angles.device, (center.device, angles.device)
- assert center.dtype == angles.dtype, (center.dtype, angles.dtype)
+ if not (len(center.shape) == 2 and center.shape[-1] == 3):
+ raise AssertionError(center.shape)
+ if not (len(angles.shape) == 2 and angles.shape[-1] == 3):
+ raise AssertionError(angles.shape)
+ if center.device != angles.device:
+ raise AssertionError(center.device, angles.device)
+ if center.dtype != angles.dtype:
+ raise AssertionError(center.dtype, angles.dtype)
# create rotation matrix
angle_axis_rad: torch.Tensor = K.deg2rad(angles)
@@ -241,10 +250,11 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
"Inputs must have same batch size dimension. Expect {} but got {}".format(src.shape, dst.shape)
)
- assert src.device == dst.device and src.dtype == dst.dtype, (
- f"Expect `src` and `dst` to be in the same device (Got {src.dtype}, {dst.dtype}) "
- f"with the same dtype (Got {src.dtype}, {dst.dtype})."
- )
+ if not (src.device == dst.device and src.dtype == dst.dtype):
+ raise AssertionError(
+ f"Expect `src` and `dst` to be in the same device (Got {src.dtype}, {dst.dtype}) "
+ f"with the same dtype (Got {src.dtype}, {dst.dtype})."
+ )
# we build matrix A by using only 4 point correspondence. The linear
# system is solved with the least square method, so here
diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.py
index 3a5476726..d76d61822 100644
--- a/kornia/losses/depth_smooth.py
+++ b/kornia/losses/depth_smooth.py
@@ -6,12 +6,14 @@ import torch.nn as nn
def _gradient_x(img: torch.Tensor) -> torch.Tensor:
- assert len(img.shape) == 4, img.shape
+ if len(img.shape) != 4:
+ raise AssertionError(img.shape)
return img[:, :, :, :-1] - img[:, :, :, 1:]
def _gradient_y(img: torch.Tensor) -> torch.Tensor:
- assert len(img.shape) == 4, img.shape
+ if len(img.shape) != 4:
+ raise AssertionError(img.shape)
return img[:, :, :-1, :] - img[:, :, 1:, :]
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 9d1aaa752..f8db05c43 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -37,7 +37,8 @@ def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
"""Converts the input tensor to a valid variable to check the gradient.
`gradcheck` needs 64-bit floating point and requires gradient.
"""
- assert torch.is_tensor(tensor), type(tensor)
+ if not torch.is_tensor(tensor):
+ raise AssertionError(type(tensor))
return tensor.requires_grad_(requires_grad).type(dtype)
@@ -103,7 +104,8 @@ def cartesian_product_of_parameters(**possible_parameters):
def default_with_one_parameter_changed(*, default={}, **possible_parameters):
- assert isinstance(default, dict), f"default should be a dict not a {type(default)}"
+ if not isinstance(default, dict):
+ raise AssertionError(f"default should be a dict not a {type(default)}")
for parameter_name, possible_values in possible_parameters.items():
for v in possible_values:
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index b3b271078..66630a754 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -33,8 +33,10 @@ def draw_rectangle(
batch, c, h, w = image.shape
batch_rect, num_rectangle, num_points = rectangle.shape
- assert batch == batch_rect, "Image batch and rectangle batch must be equal"
- assert num_points == 4, "Number of points in rectangle must be 4"
+ if batch != batch_rect:
+ raise AssertionError("Image batch and rectangle batch must be equal")
+ if num_points != 4:
+ raise AssertionError("Number of points in rectangle must be 4")
# clone rectangle, in case it's been expanded assignment from clipping causes problems
rectangle = rectangle.long().clone()
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 47d169901..8f8e42fd2 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -41,7 +41,8 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
impossible to be used by fp16 or others. What this function does, is cast
input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -55,7 +56,8 @@ def _torch_histc_cast(input: torch.Tensor, bins: int, min: int, max: int) -> tor
impossible to be used by fp16 or others. What this function does, is cast
input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -71,7 +73,8 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -88,7 +91,8 @@ def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tenso
impossible to be used by fp16 or others. What this function does, is cast
input data type to fp32, apply torch.svd, and cast back to the input dtype.
"""
- assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
+ if not isinstance(input, torch.Tensor):
+ raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32