π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
types everywhere
diegovd0296207caa19a130
diff --git a/docs/source/color.rst b/docs/source/color.rstindex 030f066bc..9cab3db4e 100644--- a/docs/source/color.rst+++ b/docs/source/color.rst@@ -7,3 +7,12 @@ The functions in this section perform various color space conversions... autoclass:: RgbToGrayscale.. autofunction:: rgb_to_grayscale+.. autoclass:: RgbToHsv+.. autofunction:: rgb_to_hsv+.. autoclass:: RgbToBgr+.. autofunction:: rgb_to_bgr+.. autoclass:: BgrToRgb+.. autofunction:: bgr_to_rgb++.. autoclass:: Normalize+.. autofunction:: normalizediff --git a/test/test_image.py b/test/test_image.pyindex 02e239e47..9f681e7a9 100644--- a/test/test_image.py+++ b/test/test_image.py@@ -1,12 +1,11 @@import pytest-import torch-import torchgeometry.image as imagefrom torch.autograd import gradcheckfrom torch.testing import assert_allclose+from common import device_type+import torchgeometry.image as imageimport utils-from common import device_type@pytest.mark.parametrize("window_size", [5, 11])@@ -51,12 +50,16 @@ class TestGaussianBlur:raise_exception=True)def test_jit(self):+ @torch.jit.script+ def op_script(img):++ return image.gaussian_blur(img, (5, 5), (1.2, 1.2))+batch_size, channels, height, width = 2, 3, 64, 64img = torch.ones(batch_size, channels, height, width)- gauss = image.GaussianBlur((5, 5), (1.2, 1.2))- gauss_traced = torch.jit.trace(- image.GaussianBlur((5, 5), (1.2, 1.2)), img)- assert_allclose(gauss(img), gauss_traced(img))+ expected = image.GaussianBlur((5, 5), (1.2, 1.2))(img)+ actual = op_script(img)+ assert_allclose(actual, expected)class TestNormalize:@@ -122,7 +125,7 @@ class TestNormalize: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)+ actual = op_script(data, mean, std)expected = image.normalize(data, mean, std)assert_allclose(actual, expected)@@ -206,7 +209,7 @@ class TestRgbToHsv:[[21.0000, 22.0000],[22.0000, 22.0000]]])- f = image.RgbToHsV()+ f = image.RgbToHsv()assert_allclose(f(data), expected, atol=1e-4, rtol=1e-5)def test_batch_rgb_to_hsv(self):@@ -228,7 +231,7 @@ class TestRgbToHsv:[[21.0000, 22.0000],[22.0000, 22.0000]]]) # 3x2x2- f = image.RgbToHsV()+ f = image.RgbToHsv()data = data.repeat(2, 1, 1, 1) # 2x3x2x2print(data.shape)expected = expected.repeat(2, 1, 1, 1) # 2x3x2x2@@ -249,7 +252,7 @@ class TestRgbToHsv:data = utils.tensor_to_gradcheck_var(data) # to var- assert gradcheck(image.RgbToHsV(), (data,),+ assert gradcheck(image.RgbToHsv(), (data,),raise_exception=True)def test_jit(self):@@ -266,12 +269,12 @@ class TestRgbToHsv:[[8., 8.],[8., 8.]]]]) # 3x2x2- actual = op.script(data)+ actual = op_script(data)expected = image.rgb_to_hsv(data)assert_allclose(actual, expected)-class TestBgRToRgb:+class TestBgrToRgb:def test_bgr_to_rgb(self):@@ -372,11 +375,117 @@ class TestBgRToRgb:[[3., 3.],[3., 3.]]]) # 3x2x2- actual = op.script(data)+ actual = op_script(data)expected = image.bgr_to_rgb(data)assert_allclose(actual, expected)+class TestRgbToBgr:++ def test_rgb_to_bgr(self):++ # prepare input data+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[2., 2.],+ [2., 2.]],++ [[3., 3.],+ [3., 3.]]]) # 3x2x2++ expected = torch.tensor([[[3., 3.],+ [3., 3.]],++ [[2., 2.],+ [2., 2.]],++ [[1., 1.],+ [1., 1.]]]) # 3x2x2++ f = image.RgbToBgr()+ assert_allclose(f(data), expected)++ def test_gradcheck(self):++ # prepare input data+ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[2., 2.],+ [2., 2.]],++ [[3., 3.],+ [3., 3.]]]) # 3x2x2++ data = utils.tensor_to_gradcheck_var(data) # to var++ assert gradcheck(image.RgbToBgr(), (data,),+ raise_exception=True)++ def test_jit(self):+ @torch.jit.script+ def op_script(data: torch.Tensor) -> torch.Tensor:++ return image.rgb_to_bgr(data)++ data = torch.tensor([[[1., 1.],+ [1., 1.]],++ [[2., 2.],+ [2., 2.]],++ [[3., 3.],+ [3., 3.]]]) # 3x2x2++ actual = op_script(data)+ expected = image.rgb_to_bgr(data)+ assert_allclose(actual, expected)++ def test_batch_rgb_to_bgr(self):++ # prepare input data+ data = torch.tensor([[[[1., 1.],+ [1., 1.]],++ [[2., 2.],+ [2., 2.]],++ [[3., 3.],+ [3., 3.]]],++ [[[1., 1.],+ [1., 1.]],++ [[2., 2.],+ [2., 2.]],++ [[3., 3.],+ [3., 3.]]]]) # 2x3x2x2++ expected = torch.tensor([[[[3., 3.],+ [3., 3.]],++ [[2., 2.],+ [2., 2.]],++ [[1., 1.],+ [1., 1.]]],++ [[[3., 3.],+ [3., 3.]],++ [[2., 2.],+ [2., 2.]],++ [[1., 1.],+ [1., 1.]]]]) # 2x3x2x2++ f = image.RgbToBgr()+ out = f(data)+ assert_allclose(out, expected)++class TestRgbToGrayscale:def test_rgb_to_grayscale(self):channels, height, width = 3, 4, 5diff --git a/torchgeometry/image/__init__.py b/torchgeometry/image/__init__.pyindex 7cf5a2fbf..2dd1f2e9c 100644--- a/torchgeometry/image/__init__.py+++ b/torchgeometry/image/__init__.py@@ -1,11 +1,11 @@from .gaussian import get_gaussian_kernel, get_gaussian_kernel2dfrom .gaussian import GaussianBlur, gaussian_blur-from .normalization import Normalize, normalizefrom .laplacian import get_laplacian_kernel, get_laplacian_kernel2dfrom .laplacian import Laplacian, laplacianfrom .color import rgb_to_grayscale, RgbToGrayscalefrom .color import BgrToRgb, bgr_to_rgbfrom .color import RgbToBgr, rgb_to_bgr-from .color import RgbToHsV, rgb_to_hsv+from .color import RgbToHsv, rgb_to_hsv+from .color import Normalize, normalizefrom .pyramid import pyrdown, pyrup, PyrDown, PyrUpfrom .sobel import SobelEdges, Sobel, sobel, sobel_edgesdiff --git a/torchgeometry/image/color.py b/torchgeometry/image/color.pyindex 4cb0cca2d..c3d8586bd 100644--- a/torchgeometry/image/color.py+++ b/torchgeometry/image/color.py@@ -1,35 +1,33 @@import torchimport torch.nn as nn-import numpy as np-class RgbToHsV(nn.Module):+class RgbToHsv(nn.Module):- """convert image from RGB to HSV.+ """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.+ 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)`+ - image: :math:`(*, 3, H, W)`+ - output: :math:`(*, 3, H, W)`"""def __init__(self) -> None:- super(RgbToHsV, self).__init__()+ super(RgbToHsv, self).__init__()def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignorereturn rgb_to_hsv(image)def rgb_to_hsv(image):-- """Convert an RGB image to HSV+ """Convert an RGB image to HSV.Args:input (torch.Tensor): RGB Image to be converted to HSV.@@ -46,49 +44,53 @@ def rgb_to_hsv(image):raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))- r = image[..., 0, :, :]- g = image[..., 1, :, :]- b = image[..., 2, :, :]+ r: torch.Tensor = image[..., 0, :, :]+ g: torch.Tensor = image[..., 1, :, :]+ b: torch.Tensor = image[..., 2, :, :]- maxc = image.max(-3)[0]- minc = image.min(-3)[0]+ maxc: torch.Tensor = image.max(-3)[0]+ minc: torch.Tensor = image.min(-3)[0]- v = maxc # brightness+ v: torch.Tensor = maxc # brightness- deltac = maxc - minc- s = deltac / v # saturation+ deltac: torch.Tensor = maxc - minc+ s: torch.Tensor = deltac / v # saturation# avoid division by zero- deltac = torch.where(deltac == 0, torch.ones_like(deltac), deltac)+ 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- rc = (maxc - r) / deltac- gc = (maxc - g) / deltac- bc = (maxc - b) / deltac+ maxg: torch.Tensor = g == maxc+ maxr: torch.Tensor = r == maxc- h = 4.0 + gc - rc- h[g == maxc] = 2.0 + rc[g == maxc] - bc[g == maxc]- h[r == maxc] = bc[r == maxc] - gc[r == maxc]- h[minc == maxc] = 0.0+ 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 = (h / 6.0) % 1.0+ h: torch.Tensor = (h / 6.0) % 1.0return torch.stack([h, s, v], dim=-3)class RgbToBgr(nn.Module):- """convert image from RGB to BGR+ """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+ image (torch.Tensor): RGB image to be converted to BGRreturns:torch.tensor: BGR version of the image.shape:- - image: :math:`(*, 3, h, w)`- - output: :math:`(*, 3, h, w)`+ - image: :math:`(*, 3, H, W)`+ - output: :math:`(*, 3, H, W)`"""@@ -118,14 +120,14 @@ class BgrToRgb(nn.Module):The image data is assumed to be in the range of (0, 1).args:- image (torch.tensor): BGR image to be converted to RGB.+ 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)`+ - image: :math:`(*, 3, H, W)`+ - output: :math:`(*, 3, H, W)`"""@@ -154,7 +156,8 @@ def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}".format(image.shape))- out = image.flip(-3)+ # flip image channels+ out: torch.Tensor = image.flip(-3)return out@@ -165,14 +168,14 @@ class RgbToGrayscale(nn.Module):the image data is assumed to be in the range of (0, 1).args:- input (torch.tensor): image to be converted to grayscale.+ input (torch.Tensor): image to be converted to grayscale.returns:- torch.tensor: grayscale version of the image.+ torch.Tensor: grayscale version of the image.shape:- - input: :math:`(*, 3, h, w)`- - output: :math:`(*, 1, h, w)`+ - input: :math:`(*, 3, H, W)`+ - output: :math:`(*, 1, H, W)`Examples::@@ -211,3 +214,68 @@ def rgb_to_grayscale(input: torch.Tensor) -> torch.Tensor:r, g, b = torch.chunk(input, chunks=3, dim=-3)gray: torch.Tensor = 0.299 * r + 0.587 * g + 0.110 * breturn gray+++class Normalize(nn.Module):++ """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:+ """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: torch.Tensor = mean[..., :, None, None].to(data.device)+ std: torch.Tensor = std[..., :, None, None].to(data.device)++ out: torch.Tensor = (data - mean) / std++ return outdiff --git a/torchgeometry/image/normalization.py b/torchgeometry/image/normalization.pydeleted file mode 100644index 712f59fe7..000000000--- a/torchgeometry/image/normalization.py+++ /dev/null@@ -1,68 +0,0 @@-import torch-import torch.nn as nn-from typing import Optional---class Normalize(nn.Module):-- """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 = mean- self.std = 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:- """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 = (data - mean) / std-- return outdiff --git a/torchgeometry/utils.py b/torchgeometry/utils.pyindex 2d7c91a59..3cfbaebaa 100644--- a/torchgeometry/utils.py+++ b/torchgeometry/utils.py@@ -1,10 +1,7 @@from typing import Optional-import torch-import torch.nn as nn-import torchgeometry as tgm-import numpy as np+import torch__all__ = [