Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

reorganize color module

edgarribab1f1234f24c0
diff --git a/.gitconfig b/.gitconfig
new file mode 100644
index 000000000..81dfd4321
--- /dev/null
+++ b/.gitconfig
@@ -0,0 +1,19 @@
+[diff]
+
+ tool = meld
+
+[difftool]
+
+ prompt = false
+
+[difftool "meld"]
+
+ cmd = meld "$LOCAL" "$REMOTE"
+
+[merge]
+
+ tool = meld
+
+[mergetool "meld"]
+
+ cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
new file mode 100644
index 000000000..5ebb95021
--- /dev/null
+++ b/test/color/test_gray.py
@@ -0,0 +1,36 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+from common import device_type
+
+import torchgeometry as K
+import torchgeometry.color as color
+import utils
+
+
+class TestRgbToGrayscale:
+ def test_rgb_to_grayscale(self):
+ channels, height, width = 3, 4, 5
+ img = torch.ones(channels, height, width)
+ assert K.rgb_to_grayscale(img).shape == (1, height, width)
+ #assert color.RgbToGrayscale()(img).shape == (1, height, width)
+
+ def test_rgb_to_grayscale_batch(self):
+ batch_size, channels, height, width = 2, 3, 4, 5
+ img = torch.ones(batch_size, channels, height, width)
+ assert color.RgbToGrayscale()(img).shape == \
+ (batch_size, 1, height, width)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 2, 3, 4, 5
+ img = torch.ones(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(color.rgb_to_grayscale, (img,), raise_exception=True)
+
+ def test_jit(self):
+ batch_size, channels, height, width = 2, 3, 64, 64
+ img = torch.ones(batch_size, channels, height, width)
+ gray = color.RgbToGrayscale()
+ gray_traced = torch.jit.trace(color.RgbToGrayscale(), img)
+ assert_allclose(gray(img), gray_traced(img))
diff --git a/test/color/test_hsv.py b/test/color/test_hsv.py
new file mode 100644
index 000000000..16654abe8
--- /dev/null
+++ b/test/color/test_hsv.py
@@ -0,0 +1,160 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+from common import device_type
+
+import torchgeometry.color as color
+import utils
+
+
+class TestRgbToHsv:
+
+ def test_rgb_to_hsv(self):
+
+ data = torch.tensor([[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]])
+
+ expected = torch.tensor([[[0.0641, 0.0714],
+ [0.0714, 0.0714]],
+
+ [[0.6190, 0.6364],
+ [0.6364, 0.6364]],
+
+ [[21.0000 / 255, 22.0000 / 255],
+ [22.0000 / 255, 22.0000 / 255]]])
+
+ f = color.RgbToHsv()
+ assert_allclose(f(data / 255), expected, atol=1e-4, rtol=1e-5)
+
+ def test_batch_rgb_to_hsv(self):
+
+ data = torch.tensor([[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]]) # 3x2x2
+
+ expected = torch.tensor([[[0.0641, 0.0714],
+ [0.0714, 0.0714]],
+
+ [[0.6190, 0.6364],
+ [0.6364, 0.6364]],
+
+ [[21.0000 / 255, 22.0000 / 255],
+ [22.0000 / 255, 22.0000 / 255]]]) # 3x2x2
+ f = color.RgbToHsv()
+ data = data.repeat(2, 1, 1, 1) # 2x3x2x2
+ expected = expected.repeat(2, 1, 1, 1) # 2x3x2x2
+ assert_allclose(f(data / 255), expected, atol=1e-4, rtol=1e-5)
+
+ def test_gradcheck(self):
+
+ data = torch.tensor([[[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]]]) # 3x2x2
+
+ data = utils.tensor_to_gradcheck_var(data) # to var
+
+ assert gradcheck(color.RgbToHsv(), (data,),
+ raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(data: torch.Tensor) -> torch.Tensor:
+
+ return color.rgb_to_hsv(data)
+ data = torch.tensor([[[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]]]) # 3x2x2
+
+ actual = op_script(data)
+ expected = color.rgb_to_hsv(data)
+ assert_allclose(actual, expected)
+
+class TestHsvToRgb:
+
+ def test_hsv_to_rgb(self):
+
+ expected = torch.tensor([[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]])
+
+ data = torch.tensor([[[0.0641, 0.0714],
+ [0.0714, 0.0714]],
+
+ [[0.6190, 0.6364],
+ [0.6364, 0.6364]],
+
+ [[21.0000 / 255, 22.0000 / 255],
+ [22.0000 / 255, 22.0000 / 255]]])
+
+ f = color.HsvToRgb()
+ assert_allclose(f(data), expected / 255, atol=1e-3, rtol=1e-3)
+
+ def test_batch_hsv_to_rgb(self):
+
+ expected = torch.tensor([[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]]) # 3x2x2
+
+ data = torch.tensor([[[0.0641, 0.0714],
+ [0.0714, 0.0714]],
+
+ [[0.6190, 0.6364],
+ [0.6364, 0.6364]],
+
+ [[21.0000 / 255, 22.0000 / 255],
+ [22.0000 / 255, 22.0000 / 255]]]) # 3x2x2
+
+ f = color.HsvToRgb()
+ data = data.repeat(2, 1, 1, 1) # 2x3x2x2
+ expected = expected.repeat(2, 1, 1, 1) # 2x3x2x2
+ assert_allclose(f(data), expected / 255, atol=1e-3, rtol=1e-3)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(data: torch.Tensor) -> torch.Tensor:
+ return color.hsv_to_rgb(data)
+
+ data = torch.tensor([[[[21., 22.],
+ [22., 22.]],
+
+ [[13., 14.],
+ [14., 14.]],
+
+ [[8., 8.],
+ [8., 8.]]]]) # 3x2x2
+
+ actual = op_script(data)
+ expected = color.hsv_to_rgb(data)
+ assert_allclose(actual, expected)
diff --git a/test/color/test_normalize.py b/test/color/test_normalize.py
new file mode 100644
index 000000000..4abe62bfc
--- /dev/null
+++ b/test/color/test_normalize.py
@@ -0,0 +1,89 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+from common import device_type
+
+import torchgeometry.color as color
+import utils
+
+
+class TestNormalize:
+ def test_smoke(self):
+ mean = [0.5]
+ std = [0.1]
+ repr = 'Normalize(mean=[0.5], std=[0.1])'
+ assert str(color.Normalize(mean, std)) == repr
+
+ def test_normalize(self):
+
+ # prepare input data
+ data = torch.ones(1, 2, 2)
+ mean = torch.tensor([0.5])
+ std = torch.tensor([2.0])
+
+ # expected output
+ expected = torch.tensor([0.25]).repeat(1, 2, 2).view_as(data)
+
+ f = color.Normalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ def test_broadcast_normalize(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ mean = torch.tensor([0.5, 1.0, 2.0])
+ std = torch.tensor([2.0, 2.0, 2.0])
+
+ # expected output
+ expected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)
+
+ f = color.Normalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ def test_batch_normalize(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
+
+ # expected output
+ expected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)
+
+ f = color.Normalize(mean, std)
+ assert_allclose(f(data), expected)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(data: torch.Tensor, mean: torch.Tensor,
+ std: torch.Tensor) -> torch.Tensor:
+
+ return color.normalize(data, mean, std)
+
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+
+ mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
+
+ actual = op_script(data, mean, std)
+ expected = image.normalize(data, mean, std)
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self):
+
+ # prepare input data
+ data = torch.ones(2, 3, 1, 1)
+ data += 2
+ mean = torch.tensor([0.5, 1.0, 2.0]).double()
+ std = torch.tensor([2., 2., 2.]).double()
+
+ data = utils.tensor_to_gradcheck_var(data) # to var
+
+ assert gradcheck(color.Normalize(mean, std), (data,),
+ raise_exception=True)
diff --git a/test/test_color.py b/test/color/test_rgb.py
similarity index 50%
rename from test/test_color.py
rename to test/color/test_rgb.py
index cdc236b94..08868831d 100644
--- a/test/test_color.py
+++ b/test/color/test_rgb.py
@@ -8,171 +8,6 @@ import torchgeometry.color as color
import utils
-class TestNormalize:
- def test_smoke(self):
- mean = [0.5]
- std = [0.1]
- repr = 'Normalize(mean=[0.5], std=[0.1])'
- assert str(color.Normalize(mean, std)) == repr
-
- def test_normalize(self):
-
- # prepare input data
- data = torch.ones(1, 2, 2)
- mean = torch.tensor([0.5])
- std = torch.tensor([2.0])
-
- # expected output
- expected = torch.tensor([0.25]).repeat(1, 2, 2).view_as(data)
-
- f = color.Normalize(mean, std)
- assert_allclose(f(data), expected)
-
- def test_broadcast_normalize(self):
-
- # prepare input data
- data = torch.ones(2, 3, 1, 1)
- data += 2
-
- mean = torch.tensor([0.5, 1.0, 2.0])
- std = torch.tensor([2.0, 2.0, 2.0])
-
- # expected output
- expected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)
-
- f = color.Normalize(mean, std)
- assert_allclose(f(data), expected)
-
- def test_batch_normalize(self):
-
- # prepare input data
- data = torch.ones(2, 3, 1, 1)
- data += 2
-
- mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
-
- # expected output
- expected = torch.tensor([1.25, 1, 0.5]).repeat(2, 1, 1).view_as(data)
-
- f = color.Normalize(mean, std)
- assert_allclose(f(data), expected)
-
- def test_jit(self):
- @torch.jit.script
- def op_script(data: torch.Tensor, mean: torch.Tensor,
- std: torch.Tensor) -> torch.Tensor:
-
- return color.normalize(data, mean, std)
-
- data = torch.ones(2, 3, 1, 1)
- data += 2
-
- mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
-
- actual = op_script(data, mean, std)
- expected = image.normalize(data, mean, std)
- assert_allclose(actual, expected)
-
- def test_gradcheck(self):
-
- # prepare input data
- data = torch.ones(2, 3, 1, 1)
- data += 2
- mean = torch.tensor([0.5, 1.0, 2.0]).double()
- std = torch.tensor([2., 2., 2.]).double()
-
- data = utils.tensor_to_gradcheck_var(data) # to var
-
- assert gradcheck(color.Normalize(mean, std), (data,),
- raise_exception=True)
-
-
-class TestRgbToHsv:
-
- def test_rgb_to_hsv(self):
-
- data = torch.tensor([[[21., 22.],
- [22., 22.]],
-
- [[13., 14.],
- [14., 14.]],
-
- [[8., 8.],
- [8., 8.]]])
-
- expected = torch.tensor([[[0.0641, 0.0714],
- [0.0714, 0.0714]],
-
- [[0.6190, 0.6364],
- [0.6364, 0.6364]],
-
- [[21.0000 / 255, 22.0000 / 255],
- [22.0000 / 255, 22.0000 / 255]]])
-
- f = color.RgbToHsv()
- assert_allclose(f(data / 255), expected, atol=1e-4, rtol=1e-5)
-
- def test_batch_rgb_to_hsv(self):
-
- data = torch.tensor([[[21., 22.],
- [22., 22.]],
-
- [[13., 14.],
- [14., 14.]],
-
- [[8., 8.],
- [8., 8.]]]) # 3x2x2
-
- expected = torch.tensor([[[0.0641, 0.0714],
- [0.0714, 0.0714]],
-
- [[0.6190, 0.6364],
- [0.6364, 0.6364]],
-
- [[21.0000 / 255, 22.0000 / 255],
- [22.0000 / 255, 22.0000 / 255]]]) # 3x2x2
- f = color.RgbToHsv()
- data = data.repeat(2, 1, 1, 1) # 2x3x2x2
- expected = expected.repeat(2, 1, 1, 1) # 2x3x2x2
- assert_allclose(f(data / 255), expected, atol=1e-4, rtol=1e-5)
-
- def test_gradcheck(self):
-
- data = torch.tensor([[[[21., 22.],
- [22., 22.]],
-
- [[13., 14.],
- [14., 14.]],
-
- [[8., 8.],
- [8., 8.]]]]) # 3x2x2
-
- data = utils.tensor_to_gradcheck_var(data) # to var
-
- assert gradcheck(color.RgbToHsv(), (data,),
- raise_exception=True)
-
- def test_jit(self):
- @torch.jit.script
- def op_script(data: torch.Tensor) -> torch.Tensor:
-
- return color.rgb_to_hsv(data)
- data = torch.tensor([[[[21., 22.],
- [22., 22.]],
-
- [[13., 14.],
- [14., 14.]],
-
- [[8., 8.],
- [8., 8.]]]]) # 3x2x2
-
- actual = op_script(data)
- expected = color.rgb_to_hsv(data)
- assert_allclose(actual, expected)
-
-
class TestBgrToRgb:
def test_bgr_to_rgb(self):
@@ -383,29 +218,3 @@ class TestRgbToBgr:
f = color.RgbToBgr()
out = f(data)
assert_allclose(out, expected)
-
-
-class TestRgbToGrayscale:
- def test_rgb_to_grayscale(self):
- channels, height, width = 3, 4, 5
- img = torch.ones(channels, height, width)
- assert color.RgbToGrayscale()(img).shape == (1, height, width)
-
- def test_rgb_to_grayscale_batch(self):
- batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width)
- assert color.RgbToGrayscale()(img).shape == \
- (batch_size, 1, height, width)
-
- def test_gradcheck(self):
- batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(color.rgb_to_grayscale, (img,), raise_exception=True)
-
- def test_jit(self):
- batch_size, channels, height, width = 2, 3, 64, 64
- img = torch.ones(batch_size, channels, height, width)
- gray = color.RgbToGrayscale()
- gray_traced = torch.jit.trace(color.RgbToGrayscale(), img)
- assert_allclose(gray(img), gray_traced(img))
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index e08129b69..46f7eb667 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -6,14 +6,19 @@ if sys.version_info < (3, 6, 0):
from .version import __version__
-from torchgeometry import geometry
from torchgeometry import color
+from torchgeometry import contrib
from torchgeometry import feature
from torchgeometry import filters
+from torchgeometry import geometry
from torchgeometry import losses
-from torchgeometry import contrib
from torchgeometry import metrics
from torchgeometry import utils
-# Exposes ``torchgeometry.geometry`` package to top level
+# Exposes package functional to top level
+
+from torchgeometry.color import (
+ rgb_to_grayscale, bgr_to_rgb, rgb_to_bgr, rgb_to_hsv, hsv_to_rgb, normalize
+)
+
from torchgeometry.geometry import *
diff --git a/torchgeometry/color/__init__.py b/torchgeometry/color/__init__.py
index f47cab985..4821361f0 100644
--- a/torchgeometry/color/__init__.py
+++ b/torchgeometry/color/__init__.py
@@ -1,18 +1,22 @@
-from ._color import rgb_to_grayscale, RgbToGrayscale
-from ._color import BgrToRgb, bgr_to_rgb
-from ._color import RgbToBgr, rgb_to_bgr
-from ._color import RgbToHsv, rgb_to_hsv
-from ._color import Normalize, normalize
+from .gray import rgb_to_grayscale, RgbToGrayscale
+from .rgb import BgrToRgb, bgr_to_rgb
+from .rgb import RgbToBgr, rgb_to_bgr
+from .hsv import RgbToHsv, rgb_to_hsv
+from .hsv import HsvToRgb, hsv_to_rgb
+from .normalize import Normalize, normalize
__all__ = [
"rgb_to_grayscale",
+ "bgr_to_rgb",
+ "rgb_to_bgr",
+ "rgb_to_hsv",
+ "hsv_to_rgb",
+ "normalize"
"RgbToGrayscale",
"BgrToRgb",
- "bgr_to_rgb",
"RgbToBgr",
- "rgb_to_bgr",
"RgbToHsv",
- "rgb_to_hsv",
+ "HsvToRgb",
"Normalize",
- "normalize"
+
]
diff --git a/torchgeometry/color/_color.py b/torchgeometry/color/_color.py
deleted file mode 100644
index 8c1a590b2..000000000
--- a/torchgeometry/color/_color.py
+++ /dev/null
@@ -1,345 +0,0 @@
-import torch
-import torch.nn as nn
-
-
-class HsvToRgb(nn.Module):
- r"""Convert image from HSV to Rgb
- 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(HsvToRgb, self).__init__()
-
- def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
- return hsv_to_rgb(image)
-
-
-def hsv_to_rgb(image):
- r"""Convert an HSV image to RGB
- The image data is assumed to be in the range of (0, 1).
-
- Args:
- input (torch.Tensor): RGB Image to be converted to HSV.
-
-
- Returns:
- 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))
-
- h: torch.Tensor = image[..., 0, :, :]
- s: torch.Tensor = image[..., 1, :, :]
- v: torch.Tensor = image[..., 2, :, :]
-
- hi: torch.Tensor = torch.floor(h * 6)
- f: torch.Tensor = h * 6 - hi
- p: torch.Tensor = v * (1 - s)
- q: torch.Tensor = v * (1 - f * s)
- t: torch.Tensor = v * (1 - (1 - f) * s)
-
- out: torch.Tensor = torch.stack([hi, hi, hi], dim=-3) % 6
-
- out[out == 0]: torch.Tensor = torch.stack((v, t, p), dim=-3)[out == 0]
- out[out == 1]: torch.Tensor = torch.stack((q, v, p), dim=-3)[out == 1]
- out[out == 2]: torch.Tensor = torch.stack((p, v, t), dim=-3)[out == 2]
- out[out == 3]: torch.Tensor = torch.stack((p, q, v), dim=-3)[out == 3]
- out[out == 4]: torch.Tensor = torch.stack((t, p, v), dim=-3)[out == 4]
- out[out == 5]: torch.Tensor = torch.stack((v, p, q), dim=-3)[out == 5]
-
- return out
-
-
-class RgbToHsv(nn.Module):
- r"""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):
- r"""Convert an RGB image to HSV.
-
- Args:
- input (torch.Tensor): RGB Image to be converted to HSV.
-
- Returns:
- 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))
-
- r: torch.Tensor = image[..., 0, :, :]
- g: torch.Tensor = image[..., 1, :, :]
- b: torch.Tensor = image[..., 2, :, :]
-
- maxc: torch.Tensor = image.max(-3)[0]
- minc: torch.Tensor = image.min(-3)[0]
-
- v: torch.Tensor = maxc # brightness
-
- deltac: torch.Tensor = maxc - minc
- s: torch.Tensor = deltac / v # saturation
-
- # avoid division by zero
- deltac: torch.Tensor = torch.where(
- deltac == 0, torch.ones_like(deltac), deltac)
-
- rc: torch.Tensor = (maxc - r) / deltac
- gc: torch.Tensor = (maxc - g) / deltac
- bc: torch.Tensor = (maxc - b) / deltac
-
- maxg: torch.Tensor = g == maxc
- maxr: torch.Tensor = r == maxc
-
- h: torch.Tensor = 4.0 + gc - rc
- h[maxg]: torch.Tensor = 2.0 + rc[maxg] - bc[maxg]
- h[maxr]: torch.Tensor = bc[maxr] - gc[maxr]
- h[minc == maxc]: torch.Tensor = 0.0
-
- h: torch.Tensor = (h / 6.0) % 1.0
-
- return torch.stack([h, s, v], dim=-3)
-
-
-class RgbToBgr(nn.Module):
-
- """Convert image from RGB to BGR.
- The image data is assumed to be in the range of (0, 1).
-
- args:
- image (torch.Tensor): RGB image to be converted to BGR
-
- returns:
- torch.tensor: BGR version of the image.
-
- shape:
- - image: :math:`(*, 3, H, W)`
- - output: :math:`(*, 3, H, W)`
-
- """
-
- def __init__(self) -> None:
- super(RgbToBgr, self).__init__()
-
- def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
- return rgb_to_bgr(image)
-
-
-def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
- r"""Convert a RGB image to BGR.
-
- Args:
- input (torch.Tensor): RGB Image to be converted to BGR.
-
- Returns:
- torch.Tensor: BGR version of the image.
- """
-
- return bgr_to_rgb(image)
-
-
-class BgrToRgb(nn.Module):
- r"""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:
- r"""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))
-
- # flip image channels
- out: torch.Tensor = 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)`
-
- Examples::
-
- >>> input = torch.rand(2, 3, 4, 5)
- >>> gray = tgm.image.RgbToGrayscale()
- >>> output = gray(input) # 2x1x4x5
- """
-
- def __init__(self) -> None:
- super(RgbToGrayscale, self).__init__()
-
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return rgb_to_grayscale(input)
-
-
-def rgb_to_grayscale(input: torch.Tensor) -> torch.Tensor:
- r"""Convert an RGB image to grayscale.
-
- See :class:`~torchgeometry.color.RgbToGrayscale` for details.
-
- Args:
- input (torch.Tensor): Image to be converted to grayscale.
-
- Returns:
- torch.Tensor: Grayscale version of the image.
- """
- if not torch.is_tensor(input):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(input)))
-
- if len(input.shape) < 3 and input.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(input.shape))
-
- # https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html
- r, g, b = torch.chunk(input, chunks=3, dim=-3)
- gray: torch.Tensor = 0.299 * r + 0.587 * g + 0.110 * b
- return gray
-
-
-class Normalize(nn.Module):
- r"""Normalize a tensor image or a batch of tensor images
- with mean and standard deviation. Input must be a tensor of shape (C, H, W)
- or a batch of tensors (*, C, H, W).
- Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
- this transform will normalize each channel of the input ``torch.*Tensor``
- i.e. ``input[channel] = (input[channel] - mean[channel]) / std[channel]``
-
- Args:
- mean (torch.Tensor): Mean for each channel.
- std (torch.Tensor): Standard deviation for each channel.
- """
-
- def __init__(self, mean: torch.Tensor, std: torch.Tensor) -> None:
-
- super(Normalize, self).__init__()
-
- self.mean: torch.Tensor = mean
- self.std: torch.Tensor = std
-
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return normalize(input, self.mean, self.std)
-
- def __repr__(self):
- repr = '(mean={0}, std={1})'.format(self.mean, self.std)
- return self.__class__.__name__ + repr
-
-
-def normalize(data: torch.Tensor, mean: torch.Tensor,
- std: torch.Tensor) -> torch.Tensor:
- r"""Normalise the image with channel-wise mean and standard deviation.
-
- Args:
- data (torch.Tensor): The image tensor to be normalised.
- mean (torch.Tensor): Mean for each channel.
- std (torch.Tensor): Standard deviations for each channel.
-
- Returns:
- Tensor: The normalised image tensor.
- """
-
- if not torch.is_tensor(data):
- raise TypeError('data should be a tensor. Got {}'.format(type(data)))
-
- if not torch.is_tensor(mean):
- raise TypeError('mean should be a tensor. Got {}'.format(type(mean)))
-
- if not torch.is_tensor(std):
- raise TypeError('std should be a tensor. Got {}'.format(type(std)))
-
- if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:
- raise ValueError('mean lenght and number of channels do not match')
-
- 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')
-
- mean = mean[..., :, None, None].to(data.device)
- std = std[..., :, None, None].to(data.device)
-
- out: torch.Tensor = (data - mean) / std
-
- return out
diff --git a/torchgeometry/color/gray.py b/torchgeometry/color/gray.py
new file mode 100644
index 000000000..82c15f615
--- /dev/null
+++ b/torchgeometry/color/gray.py
@@ -0,0 +1,56 @@
+import torch
+import torch.nn as nn
+
+
+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)`
+
+ Examples::
+
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> gray = tgm.image.RgbToGrayscale()
+ >>> output = gray(input) # 2x1x4x5
+ """
+
+ def __init__(self) -> None:
+ super(RgbToGrayscale, self).__init__()
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ return rgb_to_grayscale(input)
+
+
+def rgb_to_grayscale(input: torch.Tensor) -> torch.Tensor:
+ r"""Convert an RGB image to grayscale.
+
+ See :class:`~torchgeometry.color.RgbToGrayscale` for details.
+
+ Args:
+ input (torch.Tensor): Image to be converted to grayscale.
+
+ Returns:
+ torch.Tensor: Grayscale version of the image.
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(input)))
+
+ if len(input.shape) < 3 and input.shape[-3] != 3:
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
+ .format(input.shape))
+
+ # https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html
+ r, g, b = torch.chunk(input, chunks=3, dim=-3)
+ gray: torch.Tensor = 0.299 * r + 0.587 * g + 0.110 * b
+ return gray
diff --git a/torchgeometry/color/hsv.py b/torchgeometry/color/hsv.py
new file mode 100644
index 000000000..0c8aaa6e9
--- /dev/null
+++ b/torchgeometry/color/hsv.py
@@ -0,0 +1,142 @@
+import torch
+import torch.nn as nn
+
+
+class HsvToRgb(nn.Module):
+ r"""Convert image from HSV to Rgb
+ 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(HsvToRgb, self).__init__()
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ return hsv_to_rgb(image)
+
+
+def hsv_to_rgb(image):
+ r"""Convert an HSV image to RGB
+ The image data is assumed to be in the range of (0, 1).
+
+ Args:
+ input (torch.Tensor): RGB Image to be converted to HSV.
+
+
+ Returns:
+ 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))
+
+ h: torch.Tensor = image[..., 0, :, :]
+ s: torch.Tensor = image[..., 1, :, :]
+ v: torch.Tensor = image[..., 2, :, :]
+
+ hi: torch.Tensor = torch.floor(h * 6)
+ f: torch.Tensor = h * 6 - hi
+ p: torch.Tensor = v * (1 - s)
+ q: torch.Tensor = v * (1 - f * s)
+ t: torch.Tensor = v * (1 - (1 - f) * s)
+
+ out: torch.Tensor = torch.stack([hi, hi, hi], dim=-3) % 6
+
+ out[out == 0]: torch.Tensor = torch.stack((v, t, p), dim=-3)[out == 0]
+ out[out == 1]: torch.Tensor = torch.stack((q, v, p), dim=-3)[out == 1]
+ out[out == 2]: torch.Tensor = torch.stack((p, v, t), dim=-3)[out == 2]
+ out[out == 3]: torch.Tensor = torch.stack((p, q, v), dim=-3)[out == 3]
+ out[out == 4]: torch.Tensor = torch.stack((t, p, v), dim=-3)[out == 4]
+ out[out == 5]: torch.Tensor = torch.stack((v, p, q), dim=-3)[out == 5]
+
+ return out
+
+
+class RgbToHsv(nn.Module):
+ r"""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):
+ r"""Convert an RGB image to HSV.
+
+ Args:
+ input (torch.Tensor): RGB Image to be converted to HSV.
+
+ Returns:
+ 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))
+
+ r: torch.Tensor = image[..., 0, :, :]
+ g: torch.Tensor = image[..., 1, :, :]
+ b: torch.Tensor = image[..., 2, :, :]
+
+ maxc: torch.Tensor = image.max(-3)[0]
+ minc: torch.Tensor = image.min(-3)[0]
+
+ v: torch.Tensor = maxc # brightness
+
+ deltac: torch.Tensor = maxc - minc
+ s: torch.Tensor = deltac / v # saturation
+
+ # avoid division by zero
+ deltac: torch.Tensor = torch.where(
+ deltac == 0, torch.ones_like(deltac), deltac)
+
+ rc: torch.Tensor = (maxc - r) / deltac
+ gc: torch.Tensor = (maxc - g) / deltac
+ bc: torch.Tensor = (maxc - b) / deltac
+
+ maxg: torch.Tensor = g == maxc
+ maxr: torch.Tensor = r == maxc
+
+ h: torch.Tensor = 4.0 + gc - rc
+ h[maxg]: torch.Tensor = 2.0 + rc[maxg] - bc[maxg]
+ h[maxr]: torch.Tensor = bc[maxr] - gc[maxr]
+ h[minc == maxc]: torch.Tensor = 0.0
+
+ h: torch.Tensor = (h / 6.0) % 1.0
+
+ return torch.stack([h, s, v], dim=-3)
diff --git a/torchgeometry/color/normalize.py b/torchgeometry/color/normalize.py
new file mode 100644
index 000000000..24999fbb2
--- /dev/null
+++ b/torchgeometry/color/normalize.py
@@ -0,0 +1,69 @@
+import torch
+import torch.nn as nn
+
+
+class Normalize(nn.Module):
+ r"""Normalize a tensor image or a batch of tensor images
+ with mean and standard deviation. Input must be a tensor of shape (C, H, W)
+ or a batch of tensors (*, C, H, W).
+
+ Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
+ this transform will normalize each channel of the input ``torch.*Tensor``
+ i.e. ``input[channel] = (input[channel] - mean[channel]) / std[channel]``
+
+ Args:
+ mean (torch.Tensor): Mean for each channel.
+ std (torch.Tensor): Standard deviation for each channel.
+ """
+
+ def __init__(self, mean: torch.Tensor, std: torch.Tensor) -> None:
+
+ super(Normalize, self).__init__()
+
+ self.mean: torch.Tensor = mean
+ self.std: torch.Tensor = std
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ return normalize(input, self.mean, self.std)
+
+ def __repr__(self):
+ repr = '(mean={0}, std={1})'.format(self.mean, self.std)
+ return self.__class__.__name__ + repr
+
+
+def normalize(data: torch.Tensor, mean: torch.Tensor,
+ std: torch.Tensor) -> torch.Tensor:
+ r"""Normalise the image with channel-wise mean and standard deviation.
+
+ See :class:`~torchgeometry.color.Normalize` for details.
+
+ Args:
+ data (torch.Tensor): The image tensor to be normalised.
+ mean (torch.Tensor): Mean for each channel.
+ std (torch.Tensor): Standard deviations for each channel.
+
+ Returns:
+ Tensor: The normalised image tensor.
+ """
+
+ if not torch.is_tensor(data):
+ raise TypeError('data should be a tensor. Got {}'.format(type(data)))
+
+ if not torch.is_tensor(mean):
+ raise TypeError('mean should be a tensor. Got {}'.format(type(mean)))
+
+ if not torch.is_tensor(std):
+ raise TypeError('std should be a tensor. Got {}'.format(type(std)))
+
+ if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:
+ raise ValueError('mean lenght and number of channels do not match')
+
+ 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')
+
+ mean = mean[..., :, None, None].to(data.device)
+ std = std[..., :, None, None].to(data.device)
+
+ out: torch.Tensor = (data - mean) / std
+
+ return out
diff --git a/torchgeometry/color/rgb.py b/torchgeometry/color/rgb.py
new file mode 100644
index 000000000..7898f07f4
--- /dev/null
+++ b/torchgeometry/color/rgb.py
@@ -0,0 +1,91 @@
+import torch
+import torch.nn as nn
+
+
+class RgbToBgr(nn.Module):
+ r"""Convert image from RGB to BGR.
+
+ The image data is assumed to be in the range of (0, 1).
+
+ args:
+ image (torch.Tensor): RGB image to be converted to BGR
+
+ returns:
+ torch.Tensor: BGR version of the image.
+
+ shape:
+ - image: :math:`(*, 3, H, W)`
+ - output: :math:`(*, 3, H, W)`
+
+ """
+
+ def __init__(self) -> None:
+ super(RgbToBgr, self).__init__()
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ return rgb_to_bgr(image)
+
+
+def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
+ r"""Convert a RGB image to BGR.
+
+ See :class:`~torchgeometry.color.RgbToBgr` for details.
+
+ Args:
+ input (torch.Tensor): RGB Image to be converted to BGR.
+
+ Returns:
+ torch.Tensor: BGR version of the image.
+ """
+
+ return bgr_to_rgb(image)
+
+
+class BgrToRgb(nn.Module):
+ r"""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:
+ r"""Convert a BGR image to RGB.
+
+ See :class:`~torchgeometry.color.BgrToRgb` for details.
+
+ 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))
+
+ # flip image channels
+ out: torch.Tensor = image.flip(-3)
+
+ return out