π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(models): make ModelBase.save actually write its visualizations (#4331)
Dipak Chaudhari8b0d8b2e74ae
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f3100a25..8e784a22b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -370,6 +370,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the quality with `torch.randint(low=0, high=100)` unseeded at sixteen sites, so roughly one run in twenty of`tests/enhance/test_jpeg.py` went red on any job; the draws now start at `1` and the boundary has pinnedcases of its own. (#4205)+* `ModelBase.save` and `_save_outputs` write the visualizations they are given instead of raising.+ They handed `visualize`'s float output to `write_image` under a hard-coded `.png` name, but PNG is+ `uint8`/`uint16` only, so every container's `save` (`SemanticSegmentation`, `ObjectDetector`,+ `EdgeDetector`, `DepthEstimation`) raised on its first write and left an empty directory behind.+ Float images are now converted to `uint8`, clamped to `[0, 1]` first so an out-of-range+ visualization does not wrap. A batched `(B, 3, H, W)` output -- the shape the containers document+ -- is written as one file per item rather than passed whole to `write_image`, which takes+ `(3, H, W)` and rejected the rank with a message naming neither. (#4322)* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root intodiff --git a/kornia/models/base.py b/kornia/models/base.pyindex 7b84a8e0a..7ae1b4cdf 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -36,6 +36,45 @@ logger = logging.getLogger(__name__)ModelConfig = TypeVar("ModelConfig")+def _to_writable_png(image: torch.Tensor) -> torch.Tensor:+ """Convert a visualization tensor to the dtype ``write_image`` accepts for PNG.++ ``visualize`` returns float images in ``[0, 1]``, but ``write_image`` writes+ PNG only for ``uint8``/``uint16``; float32 is TIFF-only and every other+ float dtype is rejected outright.++ These are pictures for a human to look at, not data to round-trip, so the+ conversion is to ``uint8`` -- the same thing ``ImageModule`` already does+ before handing a tensor to PIL. Values are clamped first: a visualization+ that overshoots ``[0, 1]`` would otherwise wrap and put black where it+ should be white. Non-float images pass through untouched, so a ``uint8``+ or ``uint16`` visualization is written as-is.+ """+ if not image.is_floating_point():+ return image+ return (image.detach().clamp(0.0, 1.0) * 255).round().to(torch.uint8)+++def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:+ """Write one image, or one file per item of a batch.++ ``write_image`` takes ``(3, H, W)``, ``(1, H, W)`` or ``(H, W)``, but the+ containers document their inputs as ``(B, 3, H, W)`` and passed the batch+ straight through. The backend then rejects the rank with an error that+ names neither -- ``TypeError: argument 'image': 'ndarray' object is not an+ instance of 'ndarray'`` -- so a batch has to be split here.++ A batch of one still gets an index suffix, so a caller does not have to+ guess whether a file will be ``name.png`` or ``name_0.png``.+ """+ image = _to_writable_png(image)+ if image.dim() == 4:+ for i, item in enumerate(image):+ write_image(f"{path_stem}_{i}.png", item)+ else:+ write_image(f"{path_stem}.png", image)++class ModelBaseMixin:"""Provide common properties and utilities for Kornia model classes."""@@ -81,9 +120,9 @@ class ModelBaseMixin:timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")if isinstance(output, list):for i, out in enumerate(output):- write_image(os.path.join(directory, f"{self.name}_{timestamp}_{i}.png"), out)+ _write_png_batch(os.path.join(directory, f"{self.name}_{timestamp}_{i}"), out)else:- write_image(os.path.join(directory, f"{self.name}_{timestamp}.png"), output)+ _write_png_batch(os.path.join(directory, f"{self.name}_{timestamp}"), output)logger.info(f"Outputs are saved in {directory}")def _save_outputs(@@ -105,9 +144,9 @@ class ModelBaseMixin:timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")if isinstance(output, list):for i, out in enumerate(output):- write_image(os.path.join(directory, f"{self.name}{suffix}_{timestamp}_{i}.png"), out)+ _write_png_batch(os.path.join(directory, f"{self.name}{suffix}_{timestamp}_{i}"), out)else:- write_image(os.path.join(directory, f"{self.name}{suffix}_{timestamp}.png"), output)+ _write_png_batch(os.path.join(directory, f"{self.name}{suffix}_{timestamp}"), output)logger.info(f"Outputs are saved in {directory}")diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.pyindex 6ea0c5fa1..f28cfcee7 100644--- a/tests/models/test_model_base.py+++ b/tests/models/test_model_base.py@@ -123,3 +123,87 @@ class TestModelBaseMixinSaveOutputs:subdirs = list(kornia_outputs.iterdir())assert len(subdirs) == 1assert subdirs[0].name.startswith("dummy")+++class TestModelBaseMixinSaveWritesRealFiles:+ """`save` against the real `write_image`, not a mock.++ Every other test in this file patches `write_image`, which is why #4322+ shipped: the mock accepts any dtype and any rank, so nothing checked that+ what the containers hand it is something it can actually write. `visualize`+ returns float images and the containers document batched input, and+ `write_image` accepts neither -- PNG is uint8/uint16 only, and the rank has+ to be (3, H, W), (1, H, W) or (H, W).+ """++ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64, torch.float16])+ def test_a_float_visualization_is_written(self, tmp_path, dtype):+ mixin = DummyMixin()+ mixin.save(torch.rand(3, 8, 8, dtype=dtype), str(tmp_path))+ written = list(tmp_path.iterdir())+ assert len(written) == 1, f"expected one file, got {written}"+ assert written[0].stat().st_size > 0++ def test_a_batch_is_written_as_one_file_per_item(self, tmp_path):+ """The containers document (B, 3, H, W); write_image takes (3, H, W)."""+ mixin = DummyMixin()+ mixin.save(torch.rand(4, 3, 8, 8), str(tmp_path))+ assert len(list(tmp_path.iterdir())) == 4++ def test_a_batch_of_one_is_still_indexed(self, tmp_path):+ """So a caller does not have to guess between name.png and name_0.png."""+ mixin = DummyMixin()+ mixin.save(torch.rand(1, 3, 8, 8), str(tmp_path))+ written = list(tmp_path.iterdir())+ assert len(written) == 1+ assert written[0].name.endswith("_0.png")++ def test_the_written_file_is_a_readable_image(self, tmp_path):+ """Writing something unreadable would satisfy a file-count check."""+ from kornia.io import ImageLoadType, load_image++ mixin = DummyMixin()+ mixin.save(torch.rand(3, 8, 8), str(tmp_path))+ written = next(iter(tmp_path.iterdir()))+ image = load_image(str(written), ImageLoadType.UNCHANGED)+ assert image.shape == (3, 8, 8)+ assert image.dtype == torch.uint8++ def test_values_survive_the_conversion(self, tmp_path):+ """A float in [0, 1] must land on the matching 0-255 level."""+ from kornia.io import ImageLoadType, load_image++ mixin = DummyMixin()+ source = torch.tensor([[[0.0, 1.0], [0.5, 0.25]]]).repeat(3, 1, 1)+ mixin.save(source, str(tmp_path))+ written = next(iter(tmp_path.iterdir()))+ image = load_image(str(written), ImageLoadType.UNCHANGED)+ assert image[0].tolist() == [[0, 255], [128, 64]]++ def test_out_of_range_values_are_clamped_not_wrapped(self, tmp_path):+ """Without the clamp, 1.5 * 255 overflows uint8 and comes back dark."""+ from kornia.io import ImageLoadType, load_image++ mixin = DummyMixin()+ source = torch.tensor([[[1.5, -0.5]]]).repeat(3, 1, 1)+ mixin.save(source, str(tmp_path))+ written = next(iter(tmp_path.iterdir()))+ image = load_image(str(written), ImageLoadType.UNCHANGED)+ assert image[0].tolist() == [[255, 0]]++ def test_an_integer_image_is_passed_through(self, tmp_path):+ from kornia.io import ImageLoadType, load_image++ mixin = DummyMixin()+ source = torch.tensor([[[0, 255], [7, 64]]], dtype=torch.uint8).repeat(3, 1, 1)+ mixin.save(source, str(tmp_path))+ written = next(iter(tmp_path.iterdir()))+ image = load_image(str(written), ImageLoadType.UNCHANGED)+ assert image[0].tolist() == [[0, 255], [7, 64]]++ def test_save_outputs_writes_real_files_too(self, tmp_path):+ mixin = DummyMixin()+ mixin._save_outputs(torch.rand(2, 3, 8, 8), directory=str(tmp_path), suffix="_mask")+ written = sorted(p.name for p in tmp_path.iterdir())+ assert len(written) == 2+ assert all("_mask_" in name for name in written)