Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Fix] fixed typing (#3198)

Jian Shi936cd8c30f47
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d16f77298..bed225407 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -515,6 +515,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
)(super(ImageSequential, self).__call__)
_output_image = decorated_forward(*inputs, **kwargs)
+ in_data_keys: Optional[List[DataKey]]
if len(inputs) == 1 and isinstance(inputs[0], dict):
original_keys, in_data_keys, inputs, invalid_data = self._preproc_dict_data(inputs[0])
else:
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 3aa411ae0..365b87c90 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -115,7 +115,7 @@ def compute_padding(
right_padding = ceil(horizontal_padding / 2)
# the new implementation with unfolding requires symmetric padding
padding = int(top_padding), int(bottom_padding), int(left_padding), int(right_padding)
- return cast(FullPadType, padding)
+ return padding
class ExtractTensorPatches(Module):
@@ -381,7 +381,6 @@ def combine_tensor_patches(
if unpadding:
unpadding = create_padding_tuple(unpadding)
- unpadding = cast(FullPadType, unpadding)
ones = torch.ones(
patches.shape[0],
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 41f06a876..5988bc7d4 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -61,6 +61,7 @@ from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3d
from .laplacian import Laplacian, laplacian
from .median import MedianBlur, median_blur
from .motion import MotionBlur, MotionBlur3D, motion_blur, motion_blur3d
+from .otsu_thresholding import OtsuThreshold, otsu_threshold
from .sobel import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d
from .unsharp import UnsharpMask, unsharp_mask
@@ -80,6 +81,7 @@ __all__ = [
"MedianBlur",
"MotionBlur",
"MotionBlur3D",
+ "OtsuThreshold",
"Sobel",
"SpatialGradient",
"SpatialGradient3d",
@@ -89,6 +91,7 @@ __all__ = [
"blur_pool2d",
"box_blur",
"canny",
+ "edge_aware_blur_pool2d",
"filter2d",
"filter2d_separable",
"filter3d",
@@ -125,6 +128,7 @@ __all__ = [
"median_blur",
"motion_blur",
"motion_blur3d",
+ "otsu_threshold",
"sobel",
"spatial_gradient",
"spatial_gradient3d",
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 33b93b9c4..78c9d89ff 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -26,11 +26,11 @@ from kornia.enhance.histogram import histogram as diff_histogram
from kornia.utils.helpers import _torch_histc_cast
-class ThreshOtsu(torch.nn.Module):
+class OtsuThreshold(torch.nn.Module):
"""Otsu thresholding module for PyTorch tensors."""
def __init__(self) -> None:
- """Initialize the ThreshOtsu module."""
+ """Initialize the OtsuThreshold module."""
super().__init__()
@staticmethod
@@ -107,7 +107,8 @@ class ThreshOtsu(torch.nn.Module):
Args:
x (torch.Tensor): Image or batch of images to threshold.
nbins (int, optional): Number of bins for histogram computation. Default is 256.
- slow_and_differentiable (bool, optional): If True, use a differentiable histogram computation. Default is False.
+ slow_and_differentiable (bool, optional): If True, use a differentiable histogram computation.
+ Default is False.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Thresholded tensor, threshold values.
@@ -132,7 +133,7 @@ class ThreshOtsu(torch.nn.Module):
"Tensor dtype not supported for Otsu thresholding.",
)
- histograms, bin_edges = ThreshOtsu.__histogram(x_flattened, bins=nbins, diff=slow_and_differentiable)
+ histograms, bin_edges = OtsuThreshold.__histogram(x_flattened, bins=nbins, diff=slow_and_differentiable)
best_thresholds = torch.zeros(nchannel, device=x_flattened.device, dtype=x.dtype)
# Iterate over each image/flattened channel in the batch
@@ -229,7 +230,7 @@ def otsu_threshold(
[ 0, 50, 60],
[70, 80, 90]]), tensor([40]))
"""
- module = ThreshOtsu()
+ module = OtsuThreshold()
result, threshold = module(x, nbins=nbins, slow_and_differentiable=slow_and_differentiable)
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
index d1a9ef6ed..63b6eafdf 100644
--- a/kornia/grad_estimator/ste.py
+++ b/kornia/grad_estimator/ste.py
@@ -60,7 +60,7 @@ class STEFunction(Function):
return output
@staticmethod
- def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, Tensor, None]: # type: ignore[override]
+ def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, Tensor, None]:
if ctx.grad_fn is None:
return grad_output.sum_to_size(ctx.in_shape), grad_output.sum_to_size(ctx.out_shape), None
return (
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index d6381c2b1..78f49fb0a 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -181,7 +181,7 @@ def _torch_inverse_cast(input: Tensor) -> Tensor:
return torch.linalg.inv(input.to(dtype)).to(input.dtype)
-def _torch_histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor:
+def _torch_histc_cast(input: Tensor, bins: int, min: Union[float, bool], max: Union[float, bool]) -> Tensor:
"""Make torch.histc work with other than fp32/64.
The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
@@ -384,4 +384,4 @@ def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:
else:
constructor_args[key] = value
# TODO: remove type ignore when https://github.com/python/mypy/issues/14941 be andressed
- return dataclass_type(**constructor_args) # type: ignore[return-value]
+ return dataclass_type(**constructor_args)
diff --git a/pyproject.toml b/pyproject.toml
index c49299a31..5869ec147 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -134,10 +134,14 @@ select = [
]
ignore = [
"PLR0915", # Allow condition check in list comprehension
+ "PLC0415", # `import` should be at the top-level of a file
"PLW2901", # Allow overwritten values on loops
+ "PLW1641", # Object does not implement `__hash__` method
"UP007", # Prefer Optional[], Union[] over | due to torch jit scripting
"UP006", # Prefer List[], over list due to torch jit scripting
"UP035", # Ignore deprecated typing because of jit scripting
+ "UP045", # Use `X | None` for type annotations
+ "RUF005", # Consider `(*points_in_cam_canonical.shape[:-1], 1)` instead of concatenation. Note: breaks JIT.
'D100', # Allow Undocumented public module
'D101', # TODO: Undocumented public class
'D102', # TODO: Undocumented public method
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index 8ccedb607..692f6451f 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -18,22 +18,22 @@
import pytest
import torch
-from kornia.filters.otsu_thresholding import ThreshOtsu, otsu_threshold
+from kornia.filters.otsu_thresholding import OtsuThreshold, otsu_threshold
from testing.base import BaseTester, assert_close
-class TestThreshOtsu(BaseTester):
+class TestOtsuThreshold(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
- op = ThreshOtsu()
+ op = OtsuThreshold()
thresh_result, thresh_value = op(img, nbins=4)
assert thresh_result.shape == img.shape
@pytest.mark.parametrize("input_shape", [(3, 3), (1, 3, 3), (1, 1, 3, 3), (2, 1, 1, 3, 3)])
def test_transform_input_shapes(self, input_shape, device, dtype):
img = torch.rand(input_shape, device=device, dtype=dtype)
- op = ThreshOtsu()
+ op = OtsuThreshold()
flat, orig_shape = op.transform_input(img)
assert orig_shape == img.shape
assert flat.ndim == 2
@@ -42,12 +42,12 @@ class TestThreshOtsu(BaseTester):
torch.manual_seed(0)
img = torch.rand(1, 4, 6, 1, device=device, dtype=dtype)
out_func_tensor, out_func_value = otsu_threshold(img, nbins=3, return_mask=False)
- out_class_tensor, out_class_value = ThreshOtsu()(img, nbins=3)
+ out_class_tensor, out_class_value = OtsuThreshold()(img, nbins=3)
assert_close(out_func_tensor, out_class_tensor)
def test_invalid_dim(self, device, dtype):
img = torch.rand(1, 1, 1, 1, 3, 3, device=device, dtype=dtype)
- op = ThreshOtsu()
+ op = OtsuThreshold()
with pytest.raises(ValueError, match="Unsupported tensor dimensionality"):
op.transform_input(img)
@@ -60,7 +60,7 @@ class TestThreshOtsu(BaseTester):
input = differentiable_input.clone().detach().requires_grad_(False)
- op = ThreshOtsu()
+ op = OtsuThreshold()
diff_thresh_result, diff_thresh_value = op(input, slow_and_differentiable=True)
thresh_result, thresh_value = op(input)
self.assert_close(diff_thresh_result, thresh_result)
@@ -74,7 +74,7 @@ class TestThreshOtsu(BaseTester):
[[0, 0, 0, 0], [0, 0, 0, 0], [200, 200, 200, 200], [200, 200, 200, 200]], device=device, dtype=dtype
)
- op = ThreshOtsu()
+ op = OtsuThreshold()
thresh_result, thresh_value = op(input)
self.assert_close(thresh_result, expected)
@@ -83,7 +83,7 @@ class TestThreshOtsu(BaseTester):
expected = torch.tensor([[0, 0, 0], [0, 50, 60], [70, 80, 90]], device=device, dtype=dtype)
- op = ThreshOtsu()
+ op = OtsuThreshold()
thresh_result, thresh_value = op(input)
self.assert_close(thresh_result, expected)
@@ -96,7 +96,7 @@ class TestThreshOtsu(BaseTester):
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]], device=device, dtype=dtype
)
- op = ThreshOtsu()
+ op = OtsuThreshold()
thresh_result, thresh_value = op(input)
self.assert_close(thresh_result, expected)