π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Initial commit
ananyamukh64d65be603922
diff --git a/docs/source/color.rst b/docs/source/color.rstindex 6241ed322..743ebb04b 100644--- a/docs/source/color.rst+++ b/docs/source/color.rst@@ -13,6 +13,8 @@ The functions in this section perform various color space conversions... autofunction:: hls_to_rgb.. autofunction:: rgb_to_bgr.. autofunction:: bgr_to_rgb+.. autofunction:: rgb_to_yuv+.. autofunction:: yuv_to_rgb.. autofunction:: normalize.. autofunction:: denormalize.. autofunction:: adjust_brightness@@ -31,6 +33,8 @@ The functions in this section perform various color space conversions... autoclass:: HlsToRgb.. autoclass:: RgbToBgr.. autoclass:: BgrToRgb+.. autoclass:: RgbToYuv+.. autoclass:: YuvToRgb.. autoclass:: Normalize.. autoclass:: Denormalize.. autoclass:: AdjustBrightnessdiff --git a/kornia/__init__.py b/kornia/__init__.pyindex 1f6ddf0e6..ecbbc0450 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -25,6 +25,8 @@ from kornia.color import (rgb_to_hsv,hsv_to_rgb,rgb_to_hls,+ rgb_to_yuv,+ yuv_to_rgb,hls_to_rgb,normalize,denormalize,diff --git a/kornia/color/__init__.py b/kornia/color/__init__.pyindex d26278f8b..ffd232fe8 100644--- a/kornia/color/__init__.py+++ b/kornia/color/__init__.py@@ -6,6 +6,7 @@ from .hsv import RgbToHsv, rgb_to_hsvfrom .hsv import HsvToRgb, hsv_to_rgbfrom .hls import RgbToHls, rgb_to_hlsfrom .hls import HlsToRgb, hls_to_rgb+from .yuv import RgbToYuv, YuvToRgb, rgb_to_yuv, yuv_to_rgbfrom .normalize import Normalize, normalize, Denormalize, denormalizefrom .core import add_weighted, AddWeightedfrom .adjust import (@@ -24,6 +25,8 @@ __all__ = ["hsv_to_rgb","rgb_to_hls","hls_to_rgb",+ "rgb_to_yuv",+ "yuv_to_rgb","normalize","denormalize","adjust_brightness",@@ -41,6 +44,8 @@ __all__ = ["HsvToRgb","RgbToHls","HlsToRgb",+ "RgbToYuv",+ "YuvToRgb","Normalize","Denormalize","AdjustBrightness",diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pynew file mode 100644index 000000000..5122c83cb9f--- /dev/null+++ b/kornia/color/yuv.py@@ -0,0 +1,105 @@++import torch+import torch.nn as nn+import torch.nn.functional as F+from typing import Tuple+++class RgbToYuv(nn.Module):+ r"""Convert image from RGB to YUV+ The image data is assumed to be in the range of (0, 1).+ args:+ image (torch.Tensor): RGB image to be converted to YUV.+ returns:+ torch.tensor: YUV version of the image.+ shape:+ - image: :math:`(*, 3, H, W)`+ - output: :math:`(*, 3, H, W)`+ Examples::+ >>> input = torch.rand(2, 3, 4, 5)+ >>> yuv = kornia.color.RgbToYuv()+ >>> output = yuv(input) # 2x3x4x5+ Reference::+ [1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV+ """++ def __init__(self) -> None:+ super(RgbToYuv, self).__init__()++ def forward( # type: ignore+ self, input: torch.Tensor) -> torch.Tensor:+ return rgb_to_yuv(input)+++def rgb_to_yuv(input: torch.Tensor) -> torch.Tensor:+ r"""Convert an RGB image to YUV+ The image data is assumed to be in the range of (0, 1).+ Args:+ input (torch.Tensor): RGB Image to be converted to YUV.+ Returns:+ torch.Tensor: YUV version of the image.+ See :class:`~kornia.color.RgbToYuv` for details."""+ if not torch.is_tensor(input):+ raise TypeError("Input type is not a torch.Tensor. Got {type(input)}")++ if not(len(input.shape) == 3 or len(input.shape) == 4):+ raise ValueError(f"Input size must have a shape of (*, 3, H, W) or (3, H, W). Got {input.shape}")++ if input.shape[-3] != 3:+ raise ValueError(f"Expected input to have 3 channels, got {input.shape[-3]}")++ r, g, b = torch.chunk(input, chunks=3, dim=-3)+ y: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b+ u: torch.Tensor = -0.147 * r - 0.289 * g + 0.436 * b+ v: torch.Tensor = 0.615 * r - 0.515 * g - 0.100 * b+ yuv_img: torch.Tensor = torch.cat((y, u, v), -3)+ return yuv_img+++class YuvToRgb(nn.Module):+ r"""Convert image from YUV to RGB+ The image data is assumed to be in the range of (0, 1).+ args:+ image (torch.Tensor): YUV 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)`+ Examples::+ >>> input = torch.rand(2, 3, 4, 5)+ >>> rgb = kornia.color.YuvToRgb()+ >>> output = rgb(input) # 2x3x4x5+ """++ def __init__(self) -> None:+ super(YuvToRgb, self).__init__()++ def forward( # type: ignore+ self, input: torch.Tensor) -> torch.Tensor:+ return yuv_to_rgb(input)+++def yuv_to_rgb(input: torch.Tensor) -> torch.Tensor:+ r"""Convert an YUV image to RGB+ The image data is assumed to be in the range of (0, 1).+ Args:+ input (torch.Tensor): YUV Image to be converted to RGB.+ Returns:+ torch.Tensor: RGB version of the image.+ See :class:`~kornia.color.YuvToRgb` for details."""+ if not torch.is_tensor(input):+ raise TypeError("Input type is not a torch.Tensor. Got {type(input)}")++ if not(len(input.shape) == 3 or len(input.shape) == 4):+ raise ValueError(f"Input size must have a shape of (*, 3, H, W) or (3, H, W). Got {input.shape}")++ if input.shape[-3] != 3:+ raise ValueError(f"Expected input to have 3 channels, got {input.shape[-3]}")++ y, u, v = torch.chunk(input, chunks=3, dim=-3)+ r: torch.Tensor = y + 1.14 * v # coefficient for g is 0+ g: torch.Tensor = y + -0.396 * u - 0.581 * v+ b: torch.Tensor = y + 2.029 * u # coefficient for b is 0+ rgb_img: torch.Tensor = torch.cat((r, g, b), -3)+ return rgb_imgdiff --git a/test/color/test_yuv.py b/test/color/test_yuv.pynew file mode 100644index 000000000..dc832f90c--- /dev/null+++ b/test/color/test_yuv.py@@ -0,0 +1,83 @@+import pytest++import kornia+import kornia.testing as utils # test utils+from test.common import device_type++import torch+from torch.autograd import gradcheck+from torch.testing import assert_allclose+++class TestRgbYuvConversion:+ # Parameterize for CHW and NCHW shapes+ @pytest.mark.parametrize('shape', ((3, 4, 5), (2, 3, 4, 5)))+ # RGB to YUV and YUV to RGB should be inverse operations+ def test_inverse_operations(self, shape):+ input = torch.rand(*shape)+ yuv_to_rgb_converter = kornia.color.YuvToRgb()+ rgb_to_yuv_converter = kornia.color.RgbToYuv()++ assert_allclose(input, yuv_to_rgb_converter(rgb_to_yuv_converter(input)), rtol=0.005, atol=0.005)+ assert_allclose(input, rgb_to_yuv_converter(yuv_to_rgb_converter(input)), rtol=0.005, atol=0.005)++ def test_gradcheck(self):++ # prepare input data+ data = torch.tensor([[[0.1, 0.2],+ [0.1, 0.1]],++ [[0.2, 0.5],+ [0.4, 0.2]],++ [[0.3, 0.3],+ [0.5, 0.5]]]) # 3x2x2++ data = utils.tensor_to_gradcheck_var(data) # to var++ assert gradcheck(kornia.color.YuvToRgb(), (data,),+ raise_exception=True)+ assert gradcheck(kornia.color.RgbToYuv(), (data,),+ raise_exception=True)++ def test_rgb_to_yuv_shape(self):+ channels, height, width = 3, 4, 5+ img = torch.ones(channels, height, width)+ assert kornia.rgb_to_yuv(img).shape == (channels, height, width)++ def test_rgb_to_yuv_batch_shape(self):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.ones(batch_size, channels, height, width)+ assert kornia.rgb_to_yuv(img).shape == \+ (batch_size, channels, height, width)++ def test_yuv_to_rgb_shape(self):+ channels, height, width = 3, 4, 5+ img = torch.ones(channels, height, width)+ assert kornia.yuv_to_rgb(img).shape == (channels, height, width)++ def test_yuv_to_rgb_batch_shape(self):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.ones(batch_size, channels, height, width)+ assert kornia.yuv_to_rgb(img).shape == \+ (batch_size, channels, height, width)++ def test_rgb_to_yuv_type(self):+ with pytest.raises(TypeError):+ out = kornia.rgb_to_yuv(1)++ def test_yuv_to_rbg_type(self):+ with pytest.raises(TypeError):+ out = kornia.yuv_to_rgb(1)++ @pytest.mark.parametrize("bad_input_shapes", [([2,2],), ([3,3,3,3,3],), ([2,2,2],), ([2,2,2,2],)])+ def test_rgb_to_yuv_shape(self, bad_input_shapes):+ with pytest.raises(ValueError):+ out = kornia.rgb_to_yuv(torch.ones(*bad_input_shapes))++ @pytest.mark.parametrize("bad_input_shapes", [([2,2],), ([3,3,3,3,3],), ([2,2,2],), ([2,2,2,2],)])+ def test_yuv_to_rbg_shape(self, bad_input_shapes):+ with pytest.raises(ValueError):+ out = kornia.yuv_to_rgb(torch.ones(*bad_input_shapes))++ # TODO add cv2 comparision test