π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add [*, 3, H, W] support to Diff. JPEG (#2776)
Christoph Reich86f9104a8d5e
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.pyindex 8fae9332c..e5f38bb34 100644--- a/kornia/enhance/jpeg.py+++ b/kornia/enhance/jpeg.py@@ -13,6 +13,7 @@ from kornia.core.check import (KORNIA_CHECK_SHAPE,)from kornia.geometry.transform.affwarp import rescale+from kornia.utils.image import perform_keep_shape_image__all__ = ["jpeg_codec_differentiable", "JPEGCodecDifferentiable"]@@ -395,6 +396,7 @@ def _jpeg_decode(return rgb_decoded+@perform_keep_shape_imagedef jpeg_codec_differentiable(image_rgb: Tensor,jpeg_quality: Tensor,@@ -438,10 +440,10 @@ def jpeg_codec_differentiable(quantization table.Shape:- - image_rgb: :math:`(B, 3, H, W)`.- - jpeg_quality: :math:`(1)` or :math:`(B)`.- - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)`.- - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)`.+ - image_rgb: :math:`(*, 3, H, W)`.+ - jpeg_quality: :math:`(1)` or :math:`(B)` (if used batch dim. needs to match w/ image_rgb).+ - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb).+ - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb).Return:JPEG coded image of the shape :math:`(B, 3, H, W)`@@ -486,9 +488,9 @@ def jpeg_codec_differentiable(KORNIA_CHECK_IS_TENSOR(quantization_table_y)KORNIA_CHECK_IS_TENSOR(quantization_table_c)# Check shape of inputs- KORNIA_CHECK_SHAPE(image_rgb, ["B", "3", "H", "W"])+ KORNIA_CHECK_SHAPE(image_rgb, ["*", "3", "H", "W"])KORNIA_CHECK(- (image_rgb.shape[2] % 16 == 0) and (image_rgb.shape[3] % 16 == 0),+ (image_rgb.shape[-1] % 16 == 0) and (image_rgb.shape[-2] % 16 == 0),f"image dimension must be divisible by 16. Got the shape {image_rgb.shape}.",)KORNIA_CHECK_SHAPE(jpeg_quality, ["B"])@@ -503,11 +505,30 @@ def jpeg_codec_differentiable(# Check value range of JPEG qualityKORNIA_CHECK((jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0),- f"JPEG quality is out of range. Expected range is [0, 99], "+ f"JPEG quality is out of range. Expected range is [0, 100], "f"got [{jpeg_quality.amin().item()}, {jpeg_quality.amax().item()}]. Consider clipping jpeg_quality.",)- # Get original shape- H, W = image_rgb.shape[2:]+ # Get height and shape+ H, W = image_rgb.shape[-2:]+ # Check matching batch dimensions+ if quantization_table_y.shape[0] != 1:+ KORNIA_CHECK(+ quantization_table_y.shape[0] == image_rgb.shape[0],+ f"Batch dimensions do not match. "+ f"Got {image_rgb.shape[0]} images and {quantization_table_y.shape[0]} quantization tables (Y).",+ )+ if quantization_table_c.shape[0] != 1:+ KORNIA_CHECK(+ quantization_table_c.shape[0] == image_rgb.shape[0],+ f"Batch dimensions do not match. "+ f"Got {image_rgb.shape[0]} images and {quantization_table_c.shape[0]} quantization tables (C).",+ )+ if jpeg_quality.shape[0] != 1:+ KORNIA_CHECK(+ jpeg_quality.shape[0] == image_rgb.shape[0],+ f"Batch dimensions do not match. "+ f"Got {image_rgb.shape[0]} images and {jpeg_quality.shape[0]} JPEG qualities.",+ )# Quantization tables to same device and dtype as input imagequantization_table_y = quantization_table_y.to(device, dtype)quantization_table_c = quantization_table_c.to(device, dtype)@@ -530,6 +551,8 @@ def jpeg_codec_differentiable()# Clip coded imageimage_rgb_jpeg = _differentiable_clipping(input=image_rgb_jpeg, min=0.0, max=255.0)+ # Back to original shape+ # image_rgb_jpeg = image_rgb_jpeg.view(original_shape)return image_rgb_jpeg@@ -569,10 +592,10 @@ class JPEGCodecDifferentiable(Module):quantization table.Shape:- - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)`.- - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)`.- - image_rgb: :math:`(B, 3, H, W)`.- - jpeg_quality: :math:`(1)` or :math:`(B)`.+ - quantization_table_y: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb).+ - quantization_table_c: :math:`(8, 8)` or :math:`(B, 8, 8)` (if used batch dim. needs to match w/ image_rgb).+ - image_rgb: :math:`(*, 3, H, W)`.+ - jpeg_quality: :math:`(1)` or :math:`(B)` (if used batch dim. needs to match w/ image_rgb).Example:@@ -630,7 +653,7 @@ class JPEGCodecDifferentiable(Module):) -> Tensor:# Perform encoding-decodingimage_rgb_jpeg: Tensor = jpeg_codec_differentiable(- image_rgb=image_rgb,+ image_rgb,jpeg_quality=jpeg_quality,quantization_table_c=self.quantization_table_c,quantization_table_y=self.quantization_table_y,diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.pyindex e8d5b77ff..d76f79032 100644--- a/tests/enhance/test_jpeg.py+++ b/tests/enhance/test_jpeg.py@@ -16,6 +16,17 @@ class TestDiffJPEG(BaseTester):assert img_jpeg is not Noneassert img_jpeg.shape == img.shape+ def test_multi_batch(self, device, dtype) -> None:+ """Here we test two batch dimensions."""+ B, H, W = 4, 32, 32+ img = 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)+ 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)+ assert img_jpeg is not None+ assert img_jpeg.shape == img.shape+def test_custom_qt(self, device, dtype) -> None:"""Here we test if we can handle custom quantization tables."""B, H, W = 4, 32, 32@@ -38,13 +49,24 @@ class TestDiffJPEG(BaseTester):assert img_jpeg is not Noneassert img_jpeg.shape == img.shape+ def test_non_batch_inp(self, device, dtype) -> None:+ """Here we test if we can handle non-batched inputs (input image, JPEG quality, and QT's)."""+ H, W = 32, 32+ img = torch.rand(3, H, W, device=device, dtype=dtype)+ jpeg_quality = torch.randint(low=0, 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 None+ assert img_jpeg.shape == img.shape+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 = 2jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(1904.0, jpeg_quality)- assert "Not a Tensor type. Got" in str(errinfo)+ assert "Input input type is not a" in str(errinfo)with pytest.raises(TypeError) as errinfo:B, H, W = 2, 32, 32@@ -84,6 +106,33 @@ class TestDiffJPEG(BaseTester):kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)assert "shape must be [" in str(errinfo)+ with pytest.raises(Exception) as errinfo:+ B, H, W = 4, 32, 32+ img = 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)+ 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)+ assert "Batch dimensions do not match." in str(errinfo)++ with pytest.raises(Exception) as errinfo:+ B, H, W = 4, 32, 32+ img = 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)+ 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)+ assert "Batch dimensions do not match." in str(errinfo)++ with pytest.raises(Exception) as errinfo:+ B, H, W = 4, 32, 32+ img = 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)+ 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)+ assert "Batch dimensions do not match." in str(errinfo)+def test_cardinality(self, device, dtype) -> None:B, H, W = 1, 16, 16img = torch.zeros(B, 3, H, W, device=device, dtype=dtype)@@ -979,8 +1028,6 @@ class TestDiffJPEG(BaseTester):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)- for name, _ in diff_jpeg_module.named_parameters():- print(name)img_jpeg = diff_jpeg_module(img, jpeg_quality)assert img_jpeg is not Noneassert img_jpeg.shape == img.shape@@ -992,8 +1039,6 @@ class TestDiffJPEG(BaseTester):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)- for name, _ in diff_jpeg_module.named_parameters():- print(name)img_jpeg = diff_jpeg_module(img, jpeg_quality)assert img_jpeg is not Noneassert img_jpeg.shape == img.shape