Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implemented Bgr to Rgb

diegovd02968a7fbfd4622c
diff --git a/test/test_image.py b/test/test_image.py
index 15477fc97..e004a2726 100644
--- a/test/test_image.py
+++ b/test/test_image.py
@@ -167,6 +167,39 @@ class TestLaplacian:
raise_exception=True)
+class TestBgRToRgb:
+
+ def test_bgr_to_rgb(self):
+
+ # prepare input data
+ data = torch.ones(3, 2, 2)
+
+ f = image.BgrToRgb()
+ assert_allclose(f(data)[0], data[-1])
+ assert_allclose(f(data)[-1], data[0])
+
+ def test_batch_bgr_to_rgb(self):
+
+ # prepare input data
+ data = torch.ones(5, 3, 2, 2)
+
+ f = image.BgrToRgb()
+ out = f(data)
+ for i in range(out.shape[0]):
+ assert_allclose(out[i][0], data[i][-1])
+ assert_allclose(out[i][-1], out[i][0])
+
+ def test_gradcheck(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+
+ data = utils.tensor_to_gradcheck_var(data) # to var
+
+ assert gradcheck(image.BgrToRgb(), (data,),
+ raise_exception=True)
+
+
class TestRgbToGrayscale:
def test_rgb_to_grayscale(self):
channels, height, width = 3, 4, 5
diff --git a/torchgeometry/image/__init__.py b/torchgeometry/image/__init__.py
index 9d0486c4f..70c9b3096 100644
--- a/torchgeometry/image/__init__.py
+++ b/torchgeometry/image/__init__.py
@@ -3,4 +3,5 @@ from .gaussian import GaussianBlur, gaussian_blur
from .normalization import Normalize, normalize
from .laplacian import get_laplacian_kernel, get_laplacian_kernel2d
from .laplacian import Laplacian, laplacian
-from .color import rgb_to_grayscale, RgbToGrayscale
+from .color import rgb_to_grayscale, RgbToGrayscale, BgrToRgb, bgr_to_rgb
+from .color import RgbToHsV, rgb_to_hsv
diff --git a/torchgeometry/image/color.py b/torchgeometry/image/color.py
index adf197276..eb5547b41 100644
--- a/torchgeometry/image/color.py
+++ b/torchgeometry/image/color.py
@@ -2,20 +2,150 @@ import torch
import torch.nn as nn
-class RgbToGrayscale(nn.Module):
- r"""Convert image to grayscale version of image.
+class RgbToHsV(nn.Module):
+ """convert image from RGB to HSV.
The image data is assumed to be in the range of (0, 1).
+ args:
+ image (torch.tensor): RGB image to be converted to HSV.
+
+ returns:
+ torch.tensor: HSV version of the image.
+
+ shape:
+ - image: :math:`(*, 3, h, w)`
+ - output: :math:`(*, 3, h, w)`
+
+ """
+
+ def __init__(self) -> None:
+ super(RgbToHsV, self).__init__()
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ return rgb_to_hsv(image)
+
+
+def rgb_to_hsv(image):
+
+ """Convert an RGB image to HSV
+
Args:
- input (torch.Tensor): Image to be converted to grayscale.
+ input (torch.Tensor): RGB Image to be converted to HSV.
Returns:
- torch.Tensor: Grayscale version of the image.
+ torch.Tensor: HSV version of the image.
+ """
+
+ if not torch.is_tensor(image):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ 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))
+
+ out = torch.empty_like(image)
+ maxc = image.max(0)[0]
+ minc = image.min(0)[0]
+
+ delta = torch.tensor(image.numpy().ptp(0))
+
+ r = image[..., 0, :, :]
+ g = image[..., 1, :, :]
+ b = image[..., 2, :, :]
+
+ # brightness
+ v = maxc
+
+ # saturation
+ s = delta / v
+ s[delta == 0.] = 0.
+
+ # red is max
+ idx = r == maxc
+ out[..., 0, idx] = (g[idx] - b[idx]) / delta[idx]
+
+ # green is max
+ idx = g == maxc
+ out[..., 0, idx] = 2.0 + (b[idx] - r[idx]) / delta[idx]
+
+ # blue is max
+ idx = b == maxc
+ out[..., 0, idx] = 4.0 + (r[idx] - g[idx]) / delta[idx]
+
+ # hue
+ h = (out[..., 0, :, :] / 6) % 1.
+ h[delta == 0.] = 0.
+
+ out[..., 0, :, :] = h
+ out[..., 1, :, :] = s
+ out[..., 2, :, :] = v
+
+ return out
+
+
+class BgrToRgb(nn.Module):
+
+ """convert image from BGR to RGB.
+ The image data is assumed to be in the range of (0, 1).
+
+ args:
+ image (torch.tensor): BGR image to be converted to RGB.
+
+ returns:
+ torch.tensor: RGB version of the image.
+
+ shape:
+ - image: :math:`(*, 3, h, w)`
+ - output: :math:`(*, 3, h, w)`
+
+ """
+
+ def __init__(self) -> None:
+ super(BgrToRgb, self).__init__()
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ return bgr_to_rgb(image)
+
+
+def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:
+ """Convert a BGR image to RGB.
+
+ Args:
+ input (torch.Tensor): BGR Image to be converted to RGB.
+
+ Returns:
+ torch.Tensor: RGB version of the image.
+ """
+
+ if not torch.is_tensor(image):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ 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))
+
+ out = image.flip(-3)
+
+ return out
+
+
+class RgbToGrayscale(nn.Module):
+ r"""convert image to grayscale version of image.
+
+ the image data is assumed to be in the range of (0, 1).
+
+ args:
+ input (torch.tensor): image to be converted to grayscale.
+
+ returns:
+ torch.tensor: grayscale version of the image.
- Shape:
- - Input: :math:`(*, 3, H, W)`
- - Output: :math:`(*, 1, H, W)`
+ shape:
+ - input: :math:`(*, 3, h, w)`
+ - output: :math:`(*, 1, h, w)`
Examples::
diff --git a/torchgeometry/image/normalization.py b/torchgeometry/image/normalization.py
index b8f173b32..ca49f3c08 100644
--- a/torchgeometry/image/normalization.py
+++ b/torchgeometry/image/normalization.py
@@ -61,9 +61,6 @@ def normalize(data: torch.Tensor, mean: torch.Tensor,
if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:
raise ValueError('std lenght and number of channels do not match')
- if std.shape != mean.shape:
- raise ValueError('std and mean must have the same shape')
-
mean = mean[..., :, None, None].to(data.device)
std = std[..., :, None, None].to(data.device)