Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Adds function to convert surface normals to RGB image

Dmytro Mishkincdd2e510672e
diff --git a/docs/source/color.rst b/docs/source/color.rst
index 4a292ed8f..b9a823dd5 100644
--- a/docs/source/color.rst
+++ b/docs/source/color.rst
@@ -39,11 +39,21 @@ RGB
.. autofunction:: rgb_to_linear_rgb
.. autofunction:: linear_rgb_to_rgb
+.. autofunction:: rgb_to_rgb255
+.. autofunction:: rgb255_to_rgb
+.. autofunction:: rgb255_to_normals
+.. autofunction:: normals_to_rgb255
+
.. autoclass:: RgbToBgr
.. autoclass:: BgrToRgb
.. autoclass:: LinearRgbToRgb
.. autoclass:: RgbToLinearRgb
+.. autoclass:: Rgb255ToRgb
+.. autoclass:: RgbToRgb255
+.. autoclass:: Rgb255ToNormals
+.. autoclass:: NormalsToRgb255
+
RGBA
----
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index 2ad89b86d..0b7522e37 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -14,6 +14,10 @@ from .rgb import (
RgbToBgr,
RgbToLinearRgb,
RgbToRgba,
+ RgbToRgb255,
+ Rgb255ToNormals,
+ Rgb255ToRgb,
+ NormalsToRgb255,
bgr_to_rgb,
bgr_to_rgba,
linear_rgb_to_rgb,
@@ -22,6 +26,10 @@ from .rgb import (
rgb_to_rgba,
rgba_to_bgr,
rgba_to_rgb,
+ rgb255_to_normals,
+ rgb255_to_rgb,
+ rgb_to_rgb255,
+ normals_to_rgb255
)
from .sepia import Sepia, sepia_from_rgb
from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb
@@ -105,6 +113,14 @@ __all__ = [
"rgb_to_linear_rgb",
"rgba_to_rgb",
"rgba_to_bgr",
+ "rgb_to_rgb255",
+ "rgb255_to_rgb",
+ "rgb255_to_normals",
+ "normals_to_rgb255",
+ "Rgb255ToNormals",
+ "Rgb255ToRgb",
+ "NormalsToRgb255",
+ "RgbToRgb255",
"RgbaToRgb",
"RgbaToBgr",
"RgbToLinearRgb",
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 1ac9d6761..04c952149 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -3,7 +3,8 @@ from typing import Union, cast
import torch
from kornia.core import ImageModule as Module
-from kornia.core import Tensor
+from kornia.core import Tensor, normalize
+from kornia.core.check import KORNIA_CHECK_IS_COLOR
def rgb_to_bgr(image: Tensor) -> Tensor:
@@ -230,6 +231,78 @@ def linear_rgb_to_rgb(image: Tensor) -> Tensor:
return rgb
+def normals_to_rgb255(image: Tensor) -> Tensor:
+ r"""Convert surface normals to RGB [0, 255] for visualization purposes.
+
+ Args:
+ image: surface normals to be converted to RGB with quantization of shape :math:`(*,3,H,W)`.
+
+ Returns:
+ RGB version of the image with shape of shape :math:`(*,3,H,W)`.
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> output = normals_to_rgb255(input) # 2x3x4x5
+ """
+ KORNIA_CHECK_IS_COLOR(image)
+ rgb255 = (0.5 * (image + 1.0)).clip(0.0, 1.0) * 255
+ return rgb255
+
+
+def rgb_to_rgb255(image: Tensor) -> Tensor:
+ r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.
+
+ Args:
+ image: RGB Image to be converted to RGB [0, 255] of shape :math:`(*,3,H,W)`.
+
+ Returns:
+ RGB version of the image with shape of shape :math:`(*,3,H,W)`.
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> output = rgb_to_rgb255(input) # 2x3x4x5
+ """
+ KORNIA_CHECK_IS_COLOR(image)
+ rgb255 = (image * 255).clip(0.0, 255.0)
+ return rgb255
+
+
+def rgb255_to_rgb(image: Tensor) -> Tensor:
+ r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.
+
+ Args:
+ image: RGB Image to be converted to RGB of shape :math:`(*,3,H,W)`.
+
+ Returns:
+ RGB version of the image with shape of shape :math:`(*,3,H,W)`.
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> output = rgb255_to_rgb(input) # 2x3x4x5
+ """
+ KORNIA_CHECK_IS_COLOR(image)
+ rgb = image / 255.0
+ return rgb
+
+
+def rgb255_to_normals(image: Tensor) -> Tensor:
+ r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.
+
+ Args:
+ image: RGB Image to be converted to surface normals of shape :math:`(*,3,H,W)`.
+
+ Returns:
+ surface normals version of the image with shape of shape :math:`(*,3,H,W)`.
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> output = rgb255_to_normals(input) # 2x3x4x5
+ """
+ KORNIA_CHECK_IS_COLOR(image)
+ normals = normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
+ return normals
+
+
class BgrToRgb(Module):
r"""Convert image from BGR to RGB.
@@ -439,3 +512,83 @@ class LinearRgbToRgb(Module):
def forward(self, image: Tensor) -> Tensor:
return linear_rgb_to_rgb(image)
+
+
+class NormalsToRgb255(Module):
+ r"""Convert surface normals to RGB [0, 255] for visualization purposes.
+
+ Returns:
+ RGB version of the image.
+
+ Shape:
+ - image: :math:`(*, 3, H, W)`
+ - output: :math:`(*, 3, H, W)`
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> rgb = NormalsToRgb255()
+ >>> output = rgb(input) # 2x3x4x5
+ """
+
+ def forward(self, image: Tensor) -> Tensor:
+ return normals_to_rgb255(image)
+
+
+class RgbToRgb255(Module):
+ r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.
+
+ Returns:
+ RGB version of the image.
+
+ Shape:
+ - image: :math:`(*, 3, H, W)`
+ - output: :math:`(*, 3, H, W)`
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> rgb = RgbToRgb255()
+ >>> output = rgb(input) # 2x3x4x5
+ """
+
+ def forward(self, image: Tensor) -> Tensor:
+ return rgb_to_rgb255(image)
+
+
+class Rgb255ToRgb(Module):
+ r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.
+
+ Returns:
+ RGB version of the image.
+
+ Shape:
+ - image: :math:`(*, 3, H, W)`
+ - output: :math:`(*, 3, H, W)`
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> rgb = Rgb255ToRgb()
+ >>> output = rgb(input) # 2x3x4x5
+ """
+
+ def forward(self, image: Tensor) -> Tensor:
+ return rgb255_to_rgb(image)
+
+
+class Rgb255ToNormals(Module):
+ r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.
+
+ Returns:
+ surface normals version of the image.
+
+ Shape:
+ - image: :math:`(*, 3, H, W)`
+ - output: :math:`(*, 3, H, W)`
+
+ Example:
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> normals = Rgb255ToNormals()
+ >>> output = normals(input) # 2x3x4x5
+ """
+
+ def forward(self, image: Tensor) -> Tensor:
+ return rgb255_to_normals(image)
\ No newline at end of file
diff --git a/tests/color/test_rgb.py b/tests/color/test_rgb.py
index aa017b57b..c7f7ae75a 100644
--- a/tests/color/test_rgb.py
+++ b/tests/color/test_rgb.py
@@ -358,3 +358,178 @@ class TestLinearRgb(BaseTester):
ops = kornia.color.LinearRgbToRgb().to(device, dtype)
fcn = kornia.color.linear_rgb_to_rgb
self.assert_close(ops(img), fcn(img))
+
+
+class TestLinearRgb(BaseTester):
+ def test_smoke(self, device, dtype):
+ C, H, W = 3, 4, 5
+ img = torch.rand(C, H, W, device=device, dtype=dtype)
+ assert isinstance(kornia.color.rgb_to_linear_rgb(img), torch.Tensor)
+ assert isinstance(kornia.color.linear_rgb_to_rgb(img), torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ assert kornia.color.rgb_to_linear_rgb(img).shape == shape
+ assert kornia.color.linear_rgb_to_rgb(img).shape == shape
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError):
+ assert kornia.color.rgb_to_linear_rgb([0.0])
+
+ with pytest.raises(ValueError):
+ img = torch.ones(1, 1, device=device, dtype=dtype)
+ assert kornia.color.rgb_to_linear_rgb(img)
+
+ with pytest.raises(ValueError):
+ img = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ assert kornia.color.rgb_to_linear_rgb(img)
+
+ with pytest.raises(TypeError):
+ assert kornia.color.linear_rgb_to_rgb([0.0])
+
+ with pytest.raises(ValueError):
+ img = torch.ones(1, 1, device=device, dtype=dtype)
+ assert kornia.color.linear_rgb_to_rgb(img)
+
+ with pytest.raises(ValueError):
+ img = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ assert kornia.color.linear_rgb_to_rgb(img)
+
+ def test_back_and_forth(self, device, dtype):
+ data_bgr = torch.rand(1, 3, 3, 2, device=device, dtype=dtype)
+ data_rgb = kornia.color.rgb_to_linear_rgb(data_bgr)
+ data_bgr_new = kornia.color.linear_rgb_to_rgb(data_rgb)
+ self.assert_close(data_bgr, data_bgr_new)
+
+ def test_unit(self, device, dtype):
+ data = torch.tensor(
+ [[[1.0, 0.0], [0.5, 0.1]], [[1.0, 0.0], [0.5, 0.2]], [[1.0, 0.0], [0.5, 0.3]]], device=device, dtype=dtype
+ ) # 3x2x2
+
+ expected = torch.tensor(
+ [
+ [[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]],
+ ],
+ device=device,
+ dtype=dtype,
+ ) # 3x2x2
+
+ f = kornia.color.rgb_to_linear_rgb
+ self.assert_close(f(data), expected)
+
+ def test_unit_linear(self, device, dtype):
+ data = torch.tensor(
+ [
+ [[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]],
+ ],
+ device=device,
+ dtype=dtype,
+ ) # 3x2x2
+
+ expected = torch.tensor(
+ [[[1.0, 0.0], [0.5, 0.1]], [[1.0, 0.0], [0.5, 0.2]], [[1.0, 0.0], [0.5, 0.3]]], device=device, dtype=dtype
+ ) # 3x2x2
+
+ f = kornia.color.linear_rgb_to_rgb
+ self.assert_close(f(data), expected)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.rgb_to_linear_rgb, (img,), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.color.linear_rgb_to_rgb, (img,), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_linear_rgb
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img), op_jit(img))
+
+ @pytest.mark.jit()
+ def test_jit_linear(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ op = kornia.color.linear_rgb_to_rgb
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img), op_jit(img))
+
+ def test_module(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ ops = kornia.color.RgbToLinearRgb().to(device, dtype)
+ fcn = kornia.color.rgb_to_linear_rgb
+ self.assert_close(ops(img), fcn(img))
+
+ def test_module_linear(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ ops = kornia.color.LinearRgbToRgb().to(device, dtype)
+ fcn = kornia.color.linear_rgb_to_rgb
+ self.assert_close(ops(img), fcn(img))
+
+
+class TestRgb255Normals(BaseTester):
+ # Smoke tests: check if the functions execute and return a tensor
+ def test_smoke(self, device, dtype):
+ C, H, W = 3, 4, 5
+ img = torch.rand(C, H, W, device=device, dtype=dtype)
+ assert isinstance(kornia.color.normals_to_rgb255(img), torch.Tensor)
+ assert isinstance(kornia.color.rgb_to_rgb255(img), torch.Tensor)
+ assert isinstance(kornia.color.rgb255_to_rgb(img), torch.Tensor)
+ assert isinstance(kornia.color.rgb255_to_normals(img), torch.Tensor)
+
+ # Cardinality tests: ensure the output shape is correct
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ assert kornia.color.normals_to_rgb255(img).shape == shape
+ assert kornia.color.rgb_to_rgb255(img).shape == shape
+ assert kornia.color.rgb255_to_rgb(img).shape == shape
+ assert kornia.color.rgb255_to_normals(img).shape == shape
+
+ # Back and forth tests: ensure round-trip conversions preserve data
+ def test_back_and_forth(self, device, dtype):
+ data_rgb = torch.rand(1, 3, 3, 2, device=device, dtype=dtype)
+ rgb255 = kornia.color.rgb_to_rgb255(data_rgb)
+ rgb_restored = kornia.color.rgb255_to_rgb(rgb255)
+ torch.testing.assert_close(data_rgb, rgb_restored, atol=1e-4, rtol=1e-4)
+
+ data_normals = torch.nn.functional.normalize(torch.rand(1, 3, 3, 2, device=device, dtype=dtype), p=2, dim=1)
+ rgb255_normals = kornia.color.normals_to_rgb255(data_normals)
+ normals_restored = kornia.color.rgb255_to_normals(rgb255_normals)
+ torch.testing.assert_close(data_normals, normals_restored, atol=1e-4, rtol=1e-4)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.full((B, C, H, W), 0.5, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.rgb_to_rgb255, (img,), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.color.rgb255_to_rgb, (img,), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.color.normals_to_rgb255, (img,), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.color.rgb255_to_normals, (img,), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ for op in [kornia.color.normals_to_rgb255, kornia.color.rgb_to_rgb255, kornia.color.rgb255_to_rgb, kornia.color.rgb255_to_normals]:
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img), op_jit(img))
+
+ def test_module(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+
+ for (fcn, Mod) in [(kornia.color.normals_to_rgb255, kornia.color.NormalsToRgb255()),
+ (kornia.color.rgb255_to_rgb, kornia.color.Rgb255ToRgb()),
+ (kornia.color.rgb_to_rgb255, kornia.color.RgbToRgb255()),
+ (kornia.color.rgb255_to_normals,kornia.color.Rgb255ToNormals())]:
+ self.assert_close(fcn(img), Mod(img))
\ No newline at end of file