π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): preserve tensor output for visualization (#4959)
NiteeshGowda72d9c2d0ceedbd
diff --git a/changelog.d/4959.fixed.md b/changelog.d/4959.fixed.mdnew file mode 100644index 000000000..072692abf--- /dev/null+++ b/changelog.d/4959.fixed.md@@ -0,0 +1,4 @@+`ImageSequential.show()` / `.save()` and `AugmentationSequential.show()` / `.save()` now work after a call with+`output_type="numpy"` or `"pil"`. The containers cached the converted output, so `.show()` raised `TypeError: Input+tensor must be a PyTorch tensor.` for NumPy and `AttributeError: 'list' object has no attribute 'shape'` for PIL. They+now cache the augmented tensor before converting the output; the returned output is unchanged. Closes #4956.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex e7115f46c..e05da3745 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -626,10 +626,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if not self._disable_features:# TODO: Some more behaviour for AugmentationSequential needs to be revisited later# e.g. We convert only images, etc.- decorated_forward = self.convert_input_output(- input_names_to_handle=input_names_to_handle, output_type=output_type- )(super(ImageSequential, self).__call__)- _output_image = decorated_forward(*inputs, **kwargs)+ self._check_output_type(output_type)+ # run the forward pass in tensor mode and convert the output to ``output_type`` only after the image+ # has been cached, so ``.show()`` / ``.save()`` never receive a NumPy array or PIL images+ decorated_forward = self.convert_input_output(input_names_to_handle=input_names_to_handle)(+ super(ImageSequential, self).__call__+ )+ tensor_output = decorated_forward(*inputs, **kwargs)in_data_keys: Optional[List[DataKey]]original_keys: Optional[Tuple[str, ...]] = None@@ -642,8 +645,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# cache a detached view of the augmented image for ``.show()`` / ``.save()``, which move it to the# CPU themselves, so the forward pass pays no device-to-host copy or syncif not is_exporting():- image = self._select_output_image(_output_image, data_keys, original_keys)+ image = self._select_output_image(tensor_output, data_keys, original_keys)self._output_image = image.detach() if isinstance(image, torch.Tensor) else image+ _output_image = self._convert_output(tensor_output, output_type)else:_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)return _output_imagediff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex c36aba9a2..c7d292d8a 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -437,14 +437,13 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):"""# Wrap the forward method with the decoratorif not self._disable_features:- decorated_forward = self.convert_input_output(- input_names_to_handle=input_names_to_handle, output_type=output_type- )(super().__call__)- _output_image = decorated_forward(*inputs, **kwargs)- if output_type == "pt":- self._output_image = self._detach_tensor_to_cpu(_output_image)- else:- self._output_image = _output_image+ self._check_output_type(output_type)+ # run the forward pass in tensor mode, cache that tensor for ``.show()`` / ``.save()``, and convert the+ # output to ``output_type`` only afterwards, so the helpers never receive a NumPy array or PIL images+ decorated_forward = self.convert_input_output(input_names_to_handle=input_names_to_handle)(super().__call__)+ tensor_output = decorated_forward(*inputs, **kwargs)+ self._store_output_image(tensor_output, "pt")+ _output_image = self._convert_output(tensor_output, output_type)else:_output_image = super().__call__(*inputs, **kwargs)return _output_imagediff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 2dcf53b21..ae83360d3 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -53,8 +53,7 @@ class ImageModuleMixIn:"""# Validate output_type at the start- if output_type not in ("pt", "numpy", "pil"):- raise ValueError(f"Invalid output_type '{output_type}'. Must be one of 'pt', 'numpy', or 'pil'.")+ self._check_output_type(output_type)def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:@wraps(func)@@ -76,29 +75,44 @@ class ImageModuleMixIn:if name in input_names_to_handle:kwargs[name] = self.to_tensor(value)- # Call the actual forward method- tensor_outputs = func(*args, **kwargs)+ # Call the actual forward method and convert its outputs to the desired type+ return self._convert_output(func(*args, **kwargs), output_type)- if not isinstance(tensor_outputs, tuple):- tensor_outputs = (tensor_outputs,)+ return wrapper- # Convert outputs to the desired type- outputs = []- for output in tensor_outputs:- if output_type == "pt":- outputs.append(output)- elif output_type == "numpy":- outputs.append(self.to_numpy(output))- elif output_type == "pil":- outputs.append(self.to_pil(output))- else:- raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")+ return decorator- return outputs if len(outputs) > 1 else outputs[0]+ @staticmethod+ def _check_output_type(output_type: str) -> None:+ if output_type not in ("pt", "numpy", "pil"):+ raise ValueError(f"Invalid output_type '{output_type}'. Must be one of 'pt', 'numpy', or 'pil'.")- return wrapper+ def _convert_output(self, tensor_outputs: Any, output_type: str) -> Any:+ """Convert a forward output to ``output_type`` the way :meth:`convert_input_output` does.- return decorator+ Args:+ tensor_outputs: The forward output: a tensor, or a tuple whose elements are converted one by one.+ output_type: Desired output type ('pt', 'numpy', or 'pil').++ Returns:+ The converted output, or a list of converted outputs for a tuple of several.++ """+ if not isinstance(tensor_outputs, tuple):+ tensor_outputs = (tensor_outputs,)++ outputs = []+ for output in tensor_outputs:+ if output_type == "pt":+ outputs.append(output)+ elif output_type == "numpy":+ outputs.append(self.to_numpy(output))+ elif output_type == "pil":+ outputs.append(self.to_pil(output))+ else:+ raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")++ return outputs if len(outputs) > 1 else outputs[0]def _is_valid_arg(self, arg: Any) -> bool:"""Check if the argument is a valid type for conversion.diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.pyindex de315dce4..c71fae330 100644--- a/tests/augmentation/container/test_sequential_aug.py+++ b/tests/augmentation/container/test_sequential_aug.py@@ -100,6 +100,43 @@ class TestConventionImageSequential(BaseTester):self.assert_close(inverted, out.flip(-1)) # only the flip was undone, the blur was skippedassert (inverted - x).abs().max().item() > 0.1 # and the round trip is not the input+ @pytest.mark.parametrize("container", ["ImageSequential", "AugmentationSequential"])+ @pytest.mark.parametrize("output_type", ["numpy", "pil"])+ def test_show_and_save_after_a_numpy_or_pil_output_4956(self, container, output_type, tmp_path, device, dtype):+ # `.show()` / `.save()` render a tensor cache, so the container caches the augmented tensor before it+ # converts the output to NumPy or PIL; it used to cache the converted output and the helpers failed on it+ from PIL import Image as PILImage++ if output_type == "numpy" and dtype == torch.bfloat16:+ pytest.skip("NumPy has no bfloat16")+ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)+ aug = getattr(K, container)(K.RandomHorizontalFlip(p=1.0))++ output = aug(image, output_type=output_type)++ if output_type == "numpy":+ assert output.shape == (2, 3, 6, 8) and not isinstance(output, torch.Tensor)+ else:+ assert len(output) == 2 and all(isinstance(out, PILImage.Image) for out in output)+ cached = aug._output_image+ assert isinstance(cached, torch.Tensor)+ assert not cached.requires_grad+ self.assert_close(cached.to(device), image.detach().flip(-1))+ if container == "AugmentationSequential":+ assert cached.device == image.device # no device-to-host copy in the forward pass (#4918)++ if dtype != torch.bfloat16: # `.show()` renders through `Tensor.numpy()`, which has no bfloat16 support+ assert isinstance(aug.show(display=False), PILImage.Image)+ output_path = tmp_path / "output.png"+ aug.save(name=str(output_path))+ assert output_path.is_file()++ @pytest.mark.parametrize("container", ["ImageSequential", "AugmentationSequential"])+ def test_invalid_output_type_raises(self, container, device, dtype):+ aug = getattr(K, container)(K.RandomHorizontalFlip(p=1.0))+ with pytest.raises(ValueError, match="Invalid output_type"):+ aug(torch.zeros(1, 3, 4, 4, device=device, dtype=dtype), output_type="jpg")+def test_convention_slice_crop_inverse_raises(self, device, dtype):seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))