π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): avoid converting keyword options as images (#5231)
NiteeshGowda727101d7dde7d7
diff --git a/changelog.d/5231.fixed.md b/changelog.d/5231.fixed.mdnew file mode 100644index 000000000..b45887338--- /dev/null+++ b/changelog.d/5231.fixed.md@@ -0,0 +1 @@+`ImageModule`, `ImageSequential` and the augmentation containers no longer load a string argument as an image unless it is the first positional argument, or a keyword argument listed in `input_names_to_handle`. An option such as `mode="bilinear"` is now passed through unchanged even when a file of that name exists in the working directory. NumPy arrays, PIL images and tensors are converted as before.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 0e211c5aa..b964d5a71 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -631,7 +631,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert, if None, handle all inputs.+ input_names_to_handle: List of input names to convert.+ If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image+ path only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex c7d292d8a..e42875a90 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -427,7 +427,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert, if None, handle all inputs.+ input_names_to_handle: List of input names to convert.+ If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image+ path only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 918b80ad2..5b2ee7562 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -101,7 +101,9 @@ class ImageModuleMixIn:"""Convert input and output types for a function.Args:- input_names_to_handle: List of input names to convert, if None, handle all inputs.+ input_names_to_handle: List of input names to convert.+ If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image+ path only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').Returns:@@ -114,12 +116,16 @@ class ImageModuleMixIn:def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:@wraps(func)def wrapper(*args: Any, **kwargs: Any) -> Union[Any, List[Any]]:- # If input_names_to_handle is None, handle all inputsif input_names_to_handle is None:- # Convert all args to tensors- args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args)- # Convert all kwargs to tensors- kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()}+ # Convert image-like arguments while treating only the first positional string as an image path.+ args = tuple(+ self.to_tensor(arg) if (i == 0 or not isinstance(arg, str)) and self._is_valid_arg(arg) else arg+ for i, arg in enumerate(args)+ )+ kwargs = {+ k: self.to_tensor(v) if not isinstance(v, str) and self._is_valid_arg(v) else v+ for k, v in kwargs.items()+ }else:# Convert specified args to tensorsargs = list(args) # type:ignorediff --git a/kornia/core/module.py b/kornia/core/module.pyindex ac4091b1a..72ecb4957 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -79,7 +79,9 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert, if None, handle all inputs.+ input_names_to_handle: List of input names to convert.+ If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image+ path only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.@@ -153,7 +155,9 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert, if None, handle all inputs.+ input_names_to_handle: List of input names to convert.+ If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image+ path only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex a275e9a6d..2b298dba8 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -143,6 +143,31 @@ class TestImageModuleMixIn:result = dummy_func(sample_tensor)assert isinstance(result, PILImage.Image)+ def test_convert_input_output_default_passes_later_strings_through(self, img_module, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "bilinear").touch()++ @img_module.convert_input_output(output_type="pt")+ def dummy_func(image, other, mode="nearest"):+ return image, other, mode++ image = torch.zeros(3, 4, 6)+ result, other, mode = dummy_func(image, "bilinear", mode="bilinear")++ assert result is image+ assert other == "bilinear"+ assert mode == "bilinear"++ def test_convert_input_output_default_converts_arrays_and_pil_images_anywhere(self, img_module):+ @img_module.convert_input_output(output_type="pt")+ def dummy_func(a, b, c=None, d=None):+ return a, b, c, d++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ pil = PILImage.new("RGB", (6, 4))++ assert all(isinstance(t, torch.Tensor) for t in dummy_func(array, pil, c=array, d=pil))+def test_convert_input_output_selective_input_names(self, img_module, sample_image):# Only convert arguments named "image", leave others unchanged@img_module.convert_input_output(input_names_to_handle=["image"], output_type="pt")@@ -152,6 +177,35 @@ class TestImageModuleMixIn:result = dummy_func(sample_image, "not_an_image")assert isinstance(result, torch.Tensor)+ def test_convert_input_output_default_loads_first_positional_path(self, img_module, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ image_path = tmp_path / "mode.png"+ PILImage.new("RGB", (6, 4)).save(image_path)++ @img_module.convert_input_output(output_type="pt")+ def dummy_func(image, mode="nearest"):+ return image, mode++ image, mode = dummy_func(str(image_path), mode="mode.png")++ assert isinstance(image, torch.Tensor)+ assert image.shape == (3, 4, 6)+ assert mode == "mode.png"++ def test_convert_input_output_default_does_not_convert_keyword_file(self, img_module, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "bilinear").touch()++ @img_module.convert_input_output(output_type="pt")+ def dummy_func(image, mode="nearest"):+ return image, mode++ image = torch.zeros(3, 4, 6)+ result, mode = dummy_func(image, mode="bilinear")++ assert result is image+ assert mode == "bilinear"+def test_show_4d_tensor(self, img_module):img_module._output_image = torch.rand(4, 3, 16, 16)result = img_module.show(display=False)