Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:lady_beetle: Fix rgb_to_hsv for onnx (#1329)

Edgar Ribaafe3873739d5
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index aef941ef3..a9c41a17e 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -1,10 +1,28 @@
import math
+from typing import Tuple
import torch
import torch.nn as nn
-
-def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
+from kornia.utils._compat import torch_version
+from packaging import version
+
+# TODO: remove once pytorch 1.6 is deprecated and keep first branch
+if version.parse(torch_version()) > version.parse("1.6.0"):
+ def _compute_max_argmax(img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ max_rgb, argmax_rgb = img.max(-3)
+ return max_rgb, argmax_rgb
+else:
+ def _compute_max_argmax(img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ # The first or last occurrence is not guaranteed before 1.6.0
+ # https://github.com/pytorch/pytorch/issues/20414
+ max_rgb, _ = img.max(-3)
+ max_mask = img == max_rgb.unsqueeze(-3)
+ _, argmax_rgb = ((max_mask.cumsum(-3) == 1) & max_mask).max(-3)
+ return max_rgb, argmax_rgb
+
+
+def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert an image from RGB to HSV.
.. image:: _static/img/rgb_to_hsv.png
@@ -33,37 +51,27 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- # The first or last occurrence is not guaranteed before 1.6.0
- # https://github.com/pytorch/pytorch/issues/20414
- maxc, _ = image.max(-3)
- maxc_mask = image == maxc.unsqueeze(-3)
- _, max_indices = ((maxc_mask.cumsum(-3) == 1) & maxc_mask).max(-3)
- minc: torch.Tensor = image.min(-3)[0]
-
- v: torch.Tensor = maxc # brightness
-
- deltac: torch.Tensor = maxc - minc
- s: torch.Tensor = deltac / (v + eps)
+ # TODO: remove if/else statement once pytorch 1.6 is deprecated and keep first branch
+ max_rgb, argmax_rgb = _compute_max_argmax(image)
+ min_rgb, argmin_rgb = image.min(-3)
+ deltac = max_rgb - min_rgb
- # avoid division by zero
- deltac = torch.where(deltac == 0, torch.ones_like(deltac, device=deltac.device, dtype=deltac.dtype), deltac)
+ v = max_rgb
+ s = deltac / (max_rgb + eps)
- maxc_tmp = maxc.unsqueeze(-3) - image
- rc: torch.Tensor = maxc_tmp[..., 0, :, :]
- gc: torch.Tensor = maxc_tmp[..., 1, :, :]
- bc: torch.Tensor = maxc_tmp[..., 2, :, :]
+ deltac = torch.where(deltac == 0, torch.ones_like(deltac), deltac)
+ rc, gc, bc = torch.unbind((max_rgb.unsqueeze(-3) - image), dim=-3)
- h = torch.stack([bc - gc, 2.0 * deltac + rc - bc, 4.0 * deltac + gc - rc], dim=-3)
-
- h = torch.gather(h, dim=-3, index=max_indices[..., None, :, :])
- h = h.squeeze(-3)
- h = h / deltac
+ h1 = (bc - gc)
+ h2 = (rc - bc) + 2.0 * deltac
+ h3 = (gc - rc) + 4.0 * deltac
+ h = torch.stack((h1, h2, h3), dim=-3) / deltac.unsqueeze(-3)
+ h = torch.gather(h, dim=-3, index=argmax_rgb.unsqueeze(-3)).squeeze(-3)
h = (h / 6.0) % 1.0
+ h = 2. * math.pi * h # we return 0/2pi output
- h = 2 * math.pi * h
-
- return torch.stack([h, s, v], dim=-3)
+ return torch.stack((h, s, v), dim=-3)
def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
@@ -93,7 +101,7 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
hi: torch.Tensor = torch.floor(h * 6) % 6
f: torch.Tensor = ((h * 6) % 6) - hi
- one: torch.Tensor = torch.tensor(1.0).to(image.device)
+ one: torch.Tensor = torch.tensor(1.0, device=image.device, dtype=image.dtype)
p: torch.Tensor = v * (one - s)
q: torch.Tensor = v * (one - f * s)
t: torch.Tensor = v * (one - (one - f) * s)
diff --git a/test/color/test_hsv.py b/test/color/test_hsv.py
index 01d4a6be6..27c621357 100644
--- a/test/color/test_hsv.py
+++ b/test/color/test_hsv.py
@@ -92,9 +92,7 @@ class TestRgbToHsv(BaseTester):
assert_close(kornia.color.rgb_to_hsv(data), expected)
def test_nan_rgb_to_hsv(self, device, dtype):
- data = torch.zeros(1, 5, 5, device=device, dtype=dtype) # 3x5x5
- data = data.repeat(3, 1, 1) # 2x3x5x5
-
+ data = torch.zeros(3, 5, 5, device=device, dtype=dtype) # 3x5x5
expected = torch.zeros_like(data) # 3x5x5
assert_close(kornia.color.rgb_to_hsv(data), expected)