π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): return a finite image at jpeg_quality=0 (#4300)
abhijeet sharma3d6b4cada64d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1b89f0af3..f5e13d8fd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -351,6 +351,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `jpeg_codec_differentiable` no longer returns an all-`NaN` image at `jpeg_quality=0`, a value inside the+ `[0, 100]` range it documents and validates. `_jpeg_quality_to_scale` divides `5000` by the quality on the+ `< 50` branch, which is `inf` at `0`, and the polynomial floor of `inf` is `NaN`, poisoning the image and+ its gradient. A quality of exactly `0` is now given the scale of quality `1`, which is the table libjpeg+ gives quality `0`. The guard is that one point: a fractional quality in `(0, 1)` was already finite, keeps+ its own larger scale, and is untouched, so this endpoint is not the limit of the formula from above.+ Output and gradients for every quality `> 0` are byte-identical. The tests drew+ the 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 pinned+ cases of its own. (#4205)* `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/enhance/jpeg.py b/kornia/enhance/jpeg.pyindex e596257ed..d77423f69 100644--- a/kornia/enhance/jpeg.py+++ b/kornia/enhance/jpeg.py@@ -228,17 +228,27 @@ def _jpeg_quality_to_scale(Args:compression_strength (torch.Tensor): Compression strength ranging from 0 to 100. Any shape is supported.+ A strength of exactly 0 is given the scale of strength 1, matching libjpeg, which gives quality 0+ the quality-1 table. Fractional strengths in (0, 1) are left alone and scale as the formula says.Returns:scale (torch.Tensor): Scaling factor to be applied to quantization matrix. Same shape as input."""+ # ``5000 / 0`` is ``inf`` and the polynomial floor of ``inf`` is ``NaN``, which poisons the whole codec+ # for a documented input. libjpeg gives quality 0 the quality-1 table, so give it the quality-1 scale.+ # The guard is exactly the zero point: a fractional quality in (0, 1) is already finite, keeps its own+ # (larger) scale, and is not touched. ``torch.where`` rather than ``clamp`` also keeps the gradient at+ # every unguarded quality independent of the torch version (see #4229).+ strength: torch.Tensor = torch.where(+ compression_strength == 0.0, torch.ones_like(compression_strength), compression_strength+ )# Get scalescale: torch.Tensor = _differentiable_polynomial_floor(torch.where(- compression_strength < 50,- 5000.0 / compression_strength,- 200.0 - 2.0 * compression_strength,+ strength < 50,+ 5000.0 / strength,+ 200.0 - 2.0 * strength,))return scale@@ -517,6 +527,9 @@ def jpeg_codec_differentiable(Args:input: the RGB image to be coded.jpeg_quality: JPEG quality in the range :math:`[0, 100]` controlling the compression strength.+ A quality of exactly 0 is treated as 1, matching libjpeg, which gives quality 0 the quality-1+ table. This endpoint is not the limit of the formula as the quality approaches 0 from above:+ a fractional quality in (0, 1) is left alone and compresses harder still.quantization_table_y: quantization table for Y channel. Default: `None`, which will load the standardquantization table.quantization_table_c: quantization table for C channels. Default: `None`, which will load the standarddiff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.pyindex 8af5ac370..825d85b79 100644--- a/tests/enhance/test_jpeg.py+++ b/tests/enhance/test_jpeg.py@@ -28,7 +28,7 @@ class TestDiffJPEG(BaseTester):"""This test standard usage."""B, H, W = 2, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)assert img_jpeg is not Noneassert img_jpeg.shape == img.shape@@ -37,7 +37,7 @@ class TestDiffJPEG(BaseTester):"""Regression test for #3745: the image must be passable via the ``input=`` keyword."""B, H, W = 2, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(input=img, jpeg_quality=jpeg_quality)self.assert_close(img_jpeg, kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality))@@ -45,7 +45,7 @@ class TestDiffJPEG(BaseTester):"""This test standard usage."""B, H, W = 2, 33, 33img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)assert img_jpeg is not Noneassert img_jpeg.shape == img.shape@@ -54,7 +54,7 @@ class TestDiffJPEG(BaseTester):"""Here we test two batch dimensions."""B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(1,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(1,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -65,7 +65,7 @@ class TestDiffJPEG(BaseTester):"""Here we test if we can handle custom quantization tables."""B, H, W = 4, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -76,7 +76,7 @@ class TestDiffJPEG(BaseTester):"""Here we test if we can handle non-batched JPEG parameters (JPEG quality and QT's)."""B, H, W = 3, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(1,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(1,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(1, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(1, 8, 8), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -87,18 +87,65 @@ class TestDiffJPEG(BaseTester):"""Here we test if we can handle non-batched inputs (input image, JPEG quality, and QT's)."""H, W = 32, 32img = torch.rand(3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(1,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(1,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(8, 8), device=device, dtype=dtype)img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)assert img_jpeg is not Noneassert img_jpeg.shape == img.shape+ def test_quality_zero_is_finite(self, device, dtype) -> None:+ """A quality of 0 is inside the documented [0, 100] range and must not produce NaN (#4205)."""+ B, H, W = 2, 32, 32+ img = torch.rand(B, 3, H, W, device=device, dtype=dtype)+ jpeg_quality = torch.zeros(B, device=device, dtype=dtype).requires_grad_(True)++ img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)+ assert torch.isfinite(img_jpeg).all()++ img_jpeg.sum().backward()+ assert jpeg_quality.grad is not None+ assert torch.isfinite(jpeg_quality.grad).all()++ def test_quality_zero_matches_quality_one(self, device, dtype) -> None:+ """Quality 0 is clamped to 1, the strongest compression, as libjpeg does (#4205)."""+ B, H, W = 2, 32, 32+ img = torch.rand(B, 3, H, W, device=device, dtype=dtype)++ img_zero = kornia.enhance.jpeg_codec_differentiable(img, torch.zeros(B, device=device, dtype=dtype))+ img_one = kornia.enhance.jpeg_codec_differentiable(img, torch.ones(B, device=device, dtype=dtype))+ self.assert_close(img_zero, img_one)++ def test_sub_unit_quality_is_untouched(self, device, dtype) -> None:+ """The guard is exactly the zero point: a quality in (0, 1) was already finite and keeps its own+ (harsher) scale rather than collapsing onto quality 1 (#4205)."""+ B, H, W = 1, 32, 32+ img = torch.rand(B, 3, H, W, device=device, dtype=dtype)+ qt = torch.ones(1, 8, 8, device=device, dtype=dtype)++ img_half = kornia.enhance.jpeg_codec_differentiable(+ img, torch.tensor([0.5], device=device, dtype=dtype), qt, qt+ )+ img_one = kornia.enhance.jpeg_codec_differentiable(img, torch.tensor([1.0], device=device, dtype=dtype), qt, qt)++ assert torch.isfinite(img_half).all()+ assert (img_half - img_one).abs().max() > 1e-2++ def test_quality_zero_only_affects_its_own_batch_entry(self, device, dtype) -> None:+ """The guard is elementwise: a 0 in the batch must not disturb its batch-mates (#4205)."""+ B, H, W = 2, 32, 32+ img = torch.rand(B, 3, H, W, device=device, dtype=dtype)+ mixed = torch.tensor([0.0, 50.0], device=device, dtype=dtype)++ img_mixed = kornia.enhance.jpeg_codec_differentiable(img, mixed)+ img_alone = kornia.enhance.jpeg_codec_differentiable(img, torch.full((B,), 50.0, device=device, dtype=dtype))+ self.assert_close(img_mixed[1], img_alone[1])+def test_exception(self, device, dtype) -> None:"""Test exceptions (non-tensor input, wrong JPEG quality shape, wrong img shape, and wrong QT shape.)"""with pytest.raises(TypeError) as errinfo:B = 2- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(1904.0, jpeg_quality)assert "Input input type is not a torch.Tensor" in str(errinfo.value)@@ -115,7 +162,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 2, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B, 3, 2, 1), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B, 3, 2, 1), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)@@ -124,7 +171,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 7, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -139,7 +186,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 7), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -154,7 +201,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B * B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B * B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * 2, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -165,7 +212,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B * B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B * B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * 2, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -176,7 +223,7 @@ class TestDiffJPEG(BaseTester):with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B * 2,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B * 2,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)@@ -1073,7 +1120,7 @@ class TestDiffJPEG(BaseTester):def test_module(self, device, dtype) -> None:B, H, W = 4, 16, 16img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)diff_jpeg_module = kornia.enhance.JPEGCodecDifferentiable(qt_y, qt_c)@@ -1084,7 +1131,7 @@ class TestDiffJPEG(BaseTester):def test_module_with_param(self, device, dtype) -> None:B, H, W = 4, 16, 16img = torch.rand(B, 3, H, W, device=device, dtype=dtype)- jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=1, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.nn.Parameter(torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype))qt_c = torch.nn.Parameter(torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype))diff_jpeg_module = kornia.enhance.JPEGCodecDifferentiable(qt_y, qt_c)