Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

optimized version of hls_to_rgb() and rgb_to_hls() (#1154)

lferrazf8e25a08c709
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index f99db454b..109177500 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -4,15 +4,18 @@ import torch
import torch.nn as nn
-def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
+def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert a RGB image to HLS.
.. image:: _static/img/rgb_to_hls.png
The image data is assumed to be in the range of (0, 1).
+ NOTE: this method cannot be compiled with JIT in pytohrch < 1.7.0
+
Args:
image: RGB image to be converted to HLS with shape :math:`(*, 3, H, W)`.
+ eps: epsilon value to avoid div by zero.
Returns:
HLS version of the image with shape :math:`(*, 3, H, W)`.
@@ -22,44 +25,73 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_hls(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
-
- r: torch.Tensor = image[..., 0, :, :]
- g: torch.Tensor = image[..., 1, :, :]
- b: torch.Tensor = image[..., 2, :, :]
-
- maxc: torch.Tensor = image.max(-3)[0]
+ raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
+
+ if not torch.jit.is_scripting():
+ # weird way to use globals compiling with JIT even in the code not used by JIT...
+ # __setattr__ can be removed if pytorch version is > 1.6.0 and then use:
+ # rgb_to_hls.RGB2HSL_IDX = hls_to_rgb.RGB2HSL_IDX.to(image.device)
+ rgb_to_hls.__setattr__('RGB2HSL_IDX', rgb_to_hls.RGB2HSL_IDX.to(image)) # type: ignore
+ _RGB2HSL_IDX: torch.Tensor = rgb_to_hls.RGB2HSL_IDX # type: ignore
+ else:
+ _RGB2HSL_IDX = torch.tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+
+ # maxc: torch.Tensor # not supported by JIT
+ # imax: torch.Tensor # not supported by JIT
+ maxc, imax = image.max(-3)
minc: torch.Tensor = image.min(-3)[0]
- imax: torch.Tensor = image.max(-3)[1]
-
- l: torch.Tensor = (maxc + minc) / 2 # luminance
-
- deltac: torch.Tensor = maxc - minc
-
- s: torch.Tensor = torch.where(
- l < 0.5, deltac / (maxc + minc), deltac / (torch.tensor(2.0) - (maxc + minc))
- ) # saturation
-
- hi: torch.Tensor = torch.zeros_like(deltac)
-
- hi[imax == 0] = (((g - b) / deltac) % 6)[imax == 0]
- hi[imax == 1] = (((b - r) / deltac) + 2)[imax == 1]
- hi[imax == 2] = (((r - g) / deltac) + 4)[imax == 2]
-
- h: torch.Tensor = 2.0 * math.pi * (60.0 * hi) / 360.0 # hue [0, 2*pi]
-
- image_hls: torch.Tensor = torch.stack([h, l, s], dim=-3)
-
- # JIT indexing is not supported before 1.6.0 https://github.com/pytorch/pytorch/issues/38962
- # image_hls[torch.isnan(image_hls)] = 0.
- image_hls = torch.where(
- torch.isnan(image_hls), torch.tensor(0.0, device=image_hls.device, dtype=image_hls.dtype), image_hls
- )
-
+ # h: torch.Tensor # not supported by JIT
+ # l: torch.Tensor # not supported by JIT
+ # s: torch.Tensor # not supported by JIT
+ # image_hls: torch.Tensor # not supported by JIT
+ if image.requires_grad:
+ l = maxc + minc
+ s = maxc - minc
+ # weird behaviour with undefined vars in JIT...
+ # scripting requires image_hls be defined even if it is not used :S
+ h = l # assign to any tensor...
+ image_hls = l # assign to any tensor...
+ else:
+ # define the resulting image to avoid the torch.stack([h, l, s])
+ # so, h, l and s require inplace operations
+ # NOTE: stack() increases in a 10% the cost in colab
+ image_hls = torch.empty_like(image)
+ h = torch.select(image_hls, -3, 0)
+ l = torch.select(image_hls, -3, 1)
+ s = torch.select(image_hls, -3, 2)
+ torch.add(maxc, minc, out=l) # l = max + min
+ torch.sub(maxc, minc, out=s) # s = max - min
+
+ # precompute image / (max - min)
+ im: torch.Tensor = image / (s + eps).unsqueeze(-3)
+
+ # epsilon cannot be inside the torch.where to avoid precision issues
+ s /= torch.where(l < 1.0, l, 2.0 - l) + eps # saturation
+ l /= 2 # luminance
+
+ # note that r,g and b were previously div by (max - min)
+ r: torch.Tensor = torch.select(im, -3, 0)
+ g: torch.Tensor = torch.select(im, -3, 1)
+ b: torch.Tensor = torch.select(im, -3, 2)
+ # h[imax == 0] = (((g - b) / (max - min)) % 6)[imax == 0]
+ # h[imax == 1] = (((b - r) / (max - min)) + 2)[imax == 1]
+ # h[imax == 2] = (((r - g) / (max - min)) + 4)[imax == 2]
+ cond: torch.Tensor = imax.unsqueeze(-3) == _RGB2HSL_IDX
+ if image.requires_grad:
+ h = torch.mul((g - b) % 6, torch.select(cond, -3, 0))
+ else:
+ torch.mul((g - b).remainder(6), torch.select(cond, -3, 0), out=h)
+ h += torch.add(b - r, 2) * torch.select(cond, -3, 1)
+ h += torch.add(r - g, 4) * torch.select(cond, -3, 2)
+ # h = 2.0 * math.pi * (60.0 * h) / 360.0
+ h *= math.pi / 3.0 # hue [0, 2*pi]
+
+ if image.requires_grad:
+ return torch.stack([h, l, s], dim=-3)
return image_hls
@@ -79,35 +111,41 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = hls_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
-
- h: torch.Tensor = image[..., 0, :, :] * 360 / (2 * math.pi)
- l: torch.Tensor = image[..., 1, :, :]
- s: torch.Tensor = image[..., 2, :, :]
-
- kr = (0 + h / 30) % 12
- kg = (8 + h / 30) % 12
- kb = (4 + h / 30) % 12
- a = s * torch.min(l, torch.tensor(1.0) - l)
-
- ones_k = torch.ones_like(kr)
-
- fr: torch.Tensor = l - a * torch.max(
- torch.min(torch.min(kr - torch.tensor(3.0), torch.tensor(9.0) - kr), ones_k), -1 * ones_k
- )
- fg: torch.Tensor = l - a * torch.max(
- torch.min(torch.min(kg - torch.tensor(3.0), torch.tensor(9.0) - kg), ones_k), -1 * ones_k
- )
- fb: torch.Tensor = l - a * torch.max(
- torch.min(torch.min(kb - torch.tensor(3.0), torch.tensor(9.0) - kb), ones_k), -1 * ones_k
- )
-
- out: torch.Tensor = torch.stack([fr, fg, fb], dim=-3)
-
- return out
+ raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
+
+ if not torch.jit.is_scripting():
+ # weird way to use globals compiling with JIT even in the code not used by JIT...
+ # __setattr__ can be removed if pytorch version is > 1.6.0 and then use:
+ # hls_to_rgb.HLS2RGB = hls_to_rgb.HLS2RGB.to(image.device)
+ hls_to_rgb.__setattr__('HLS2RGB', hls_to_rgb.HLS2RGB.to(image)) # type: ignore
+ _HLS2RGB: torch.Tensor = hls_to_rgb.HLS2RGB # type: ignore
+ else:
+ _HLS2RGB = torch.tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+
+ im: torch.Tensor = image.unsqueeze(-4)
+ h: torch.Tensor = torch.select(im, -3, 0)
+ l: torch.Tensor = torch.select(im, -3, 1)
+ s: torch.Tensor = torch.select(im, -3, 2)
+ h = h * (6 / math.pi) # h * 360 / (2 * math.pi) / 30
+ a = s * torch.min(l, 1.0 - l)
+
+ # kr = (0 + h) % 12
+ # kg = (8 + h) % 12
+ # kb = (4 + h) % 12
+ k: torch.Tensor = (h + _HLS2RGB) % 12
+
+ # l - a * max(min(min(k - 3.0, 9.0 - k), 1), -1)
+ mink = torch.min(k - 3.0, 9.0 - k)
+ return torch.addcmul(l, a, mink.clamp_(min=-1.0, max=1.0), value=-1)
+
+
+# tricks to speed up a little bit the conversions by presetting small tensors
+# (in the functions they are moved to the proper device)
+hls_to_rgb.__setattr__('HLS2RGB', torch.tensor([[[0.0]], [[8.0]], [[4.0]]])) # 3x1x1
+rgb_to_hls.__setattr__('RGB2HSL_IDX', torch.tensor([[[0.0]], [[1.0]], [[2.0]]])) # 3x1x1
class RgbToHls(nn.Module):
diff --git a/test/color/test_hls.py b/test/color/test_hls.py
index 6de9acd50..736ea57d3 100644
--- a/test/color/test_hls.py
+++ b/test/color/test_hls.py
@@ -1,4 +1,5 @@
import math
+import warnings
import pytest
import torch
@@ -6,6 +7,7 @@ from torch.autograd import gradcheck
import kornia
from kornia.testing import assert_close, BaseTester
+from packaging import version
class TestRgbToHls(BaseTester):
@@ -92,6 +94,15 @@ class TestRgbToHls(BaseTester):
assert_close(kornia.color.rgb_to_hls(data), expected)
def test_nan_rgb_to_hls(self, device, dtype):
+ if device != torch.device('cpu') and version.parse(torch.__version__) < version.parse('1.7.0'):
+ warnings.warn(
+ "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
+ "support pytorch 1.6.0. `torch.max()` have a problem in pytorch < 1.7.0 then we cannot get the correct "
+ "result. https://github.com/pytorch/pytorch/issues/41781",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return
data = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
# OpenCV
@@ -103,9 +114,13 @@ class TestRgbToHls(BaseTester):
],
dim=1,
)
-
assert_close(kornia.color.rgb_to_hls(data), expected)
+ def test_nan_random_extreme_values(self, device, dtype):
+ # generate extreme colors randomly
+ ext_rand_slice = (torch.rand((1, 3, 32, 32), dtype=dtype, device=device) >= 0.5).float()
+ assert not kornia.color.rgb_to_hls(ext_rand_slice).isnan().any()
+
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
@@ -114,6 +129,14 @@ class TestRgbToHls(BaseTester):
@pytest.mark.jit
def test_jit(self, device, dtype):
+ if version.parse(torch.__version__) < version.parse('1.7.0'):
+ warnings.warn(
+ "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
+ "support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.rgb_to_hls
@@ -233,6 +256,14 @@ class TestHlsToRgb(BaseTester):
@pytest.mark.jit
def test_jit(self, device, dtype):
+ if version.parse(torch.__version__) < version.parse('1.7.0'):
+ warnings.warn(
+ "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
+ "support pytorch 1.6.0. `hls_to_rgb()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.hls_to_rgb