π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat/equalize3d (#639)
Vinicius Ribeiro7f65905cd699
diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex 4bfc46eec..0479c282f 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -24,7 +24,7 @@ from .adjust import ()from .adjust import (adjust_brightness, adjust_contrast, adjust_gamma, adjust_hue, adjust_saturation,- adjust_hue_raw, adjust_saturation_raw, solarize, equalize, posterize, sharpness+ adjust_hue_raw, adjust_saturation_raw, solarize, equalize, equalize3d, posterize, sharpness)@@ -45,6 +45,7 @@ __all__ = ["adjust_saturation_raw","solarize","equalize",+ "equalize3d","posterize","sharpness","add_weighted",diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 938542f70..35d1718d3 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -4,6 +4,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.augmentation.utils import _transform_input3dfrom kornia.color.hsv import rgb_to_hsv, hsv_to_rgbfrom kornia.utils.image import _to_bchwfrom kornia.constants import pi@@ -428,60 +429,85 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.return torch.stack([_blend_one(input[i], result[i], factor[i]) for i in range(len(factor))])-def equalize(input: torch.Tensor) -> torch.Tensor:- """ Apply equalize on the input tensor.+# Code taken from: https://github.com/pytorch/vision/pull/796+def _scale_channel(im):+ """Scale the data in the channel to implement equalize."""+ im = im * 255++ # Compute the histogram of the image channel.+ histo = torch.histc(im, bins=256, min=0, max=255)+ # For the purposes of computing the step, filter out the nonzeros.+ nonzero_histo = torch.reshape(histo[histo != 0], [-1])+ step = (torch.sum(nonzero_histo) - nonzero_histo[-1]) // 255++ def build_lut(histo, step):+ # Compute the cumulative sum, shifting by step // 2+ # and then normalization by step.+ lut = (torch.cumsum(histo, 0) + (step // 2)) // step+ # Shift lut, prepending with 0.+ lut = torch.cat([torch.zeros(1), lut[:-1]])+ # Clip the counts to be in range. This is done+ # in the C code for image.point.+ return torch.clamp(lut, 0, 255)++ # If step is zero, return the original image. Otherwise, build+ # lut from the full histogram and step and then index from it.+ if step == 0:+ result = im+ else:+ # can't index using 2d index. Have to flatten and then reshape+ result = torch.gather(build_lut(histo, step), 0, im.flatten().long())+ result = result.reshape_as(im)++ return result / 255.++def equalize(input: torch.Tensor) -> torch.Tensor:+ r"""Apply equalize on the input tensor.Implements Equalize function from PIL using PyTorch ops based on uint8 format:https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352Args:- input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to equalize.+ input (torch.Tensor): image tensor with shapes like :math:(C, H, W) or :math:(B, C, H, W) to equalize.Returns:torch.Tensor: Sharpened image or images."""- input = _to_bchw(input) * 255-- # Code taken from: https://github.com/pytorch/vision/pull/796- def scale_channel(im, c):- """Scale the data in the channel to implement equalize."""- im = im[c, :, :]- # Compute the histogram of the image channel.- histo = torch.histc(im, bins=256, min=0, max=255)- # For the purposes of computing the step, filter out the nonzeros.- nonzero_histo = torch.reshape(histo[histo != 0], [-1])- step = (torch.sum(nonzero_histo) - nonzero_histo[-1]) // 255-- def build_lut(histo, step):- # Compute the cumulative sum, shifting by step // 2- # and then normalization by step.- lut = (torch.cumsum(histo, 0) + (step // 2)) // step- # Shift lut, prepending with 0.- lut = torch.cat([torch.zeros(1), lut[:-1]])- # Clip the counts to be in range. This is done- # in the C code for image.point.- return torch.clamp(lut, 0, 255)-- # If step is zero, return the original image. Otherwise, build- # lut from the full histogram and step and then index from it.- if step == 0:- result = im- else:- # can't index using 2d index. Have to flatten and then reshape- result = torch.gather(build_lut(histo, step), 0, im.flatten().long())- result = result.reshape_as(im)-- return result / 255.+ input = _to_bchw(input)res = []for image in input:# Assumes RGB for now. Scales each channel independently# and then stacks the result.- scaled_image = torch.stack([scale_channel(image, i) for i in range(len(image))])+ scaled_image = torch.stack([_scale_channel(image[i, :, :]) for i in range(len(image))])res.append(scaled_image)return torch.stack(res)+def equalize3d(input: torch.Tensor) -> torch.Tensor:+ r"""Equalizes the values for a 3D volumetric tensor.++ Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:+ https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352++ Args:+ input (torch.Tensor): image tensor with shapes like :math:(C, D, H, W) or :math:(B, C, D, H, W) to equalize.++ Returns:+ torch.Tensor: Sharpened image or images with same shape as the input.+ """+ input = _transform_input3d(input)++ res = []+ for volume in input:+ # Assumes RGB for now. Scales each channel independently+ # and then stacks the result.+ scaled_input = torch.stack([_scale_channel(volume[i, :, :, :]) for i in range(len(volume))])+ res.append(scaled_input)++ return torch.stack(res)++class AdjustSaturation(nn.Module):r"""Adjust color saturation of an image.diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex 908ebc807..56ae43e74 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -599,3 +599,146 @@ class TestAdjustBrightness:img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_brightness, (img, 2.),raise_exception=True)+++class TestEqualize:+ def test_shape_equalize(self, device, dtype):+ bs, channels, height, width = 1, 3, 4, 5++ inputs = torch.ones(channels, height, width, device=device, dtype=dtype)+ f = kornia.enhance.equalize++ assert f(inputs).shape == torch.Size([bs, channels, height, width])++ def test_shape_equalize_batch(self, device, dtype):+ bs, channels, height, width = 2, 3, 4, 5++ inputs = torch.ones(bs, channels, height, width, device=device, dtype=dtype)+ f = kornia.enhance.equalize++ assert f(inputs).shape == torch.Size([bs, channels, height, width])++ def test_equalize(self, device):+ bs, channels, height, width = 1, 3, 20, 20++ inputs = self.build_input(channels, height, width).squeeze(dim=0)+ inputs = inputs.to(device)++ row_expected = torch.tensor([+ 0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,+ 0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,+ 1.0000, 1.0000+ ])+ expected = self.build_input(channels, height, width, bs=1, row=row_expected)+ expected = expected.to(device)++ f = kornia.enhance.equalize++ assert_allclose(f(inputs), expected)++ def test_equalize_batch(self, device):+ bs, channels, height, width = 2, 3, 20, 20++ inputs = self.build_input(channels, height, width, bs)+ inputs = inputs.to(device)++ row_expected = torch.tensor([+ 0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,+ 0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,+ 1.0000, 1.0000+ ])+ expected = self.build_input(channels, height, width, bs, row=row_expected)+ expected = expected.to(device)++ f = kornia.enhance.equalize++ assert_allclose(f(inputs), expected)++ def test_gradcheck(self, device):+ bs, channels, height, width = 2, 3, 4, 5+ inputs = torch.ones(bs, channels, height, width)+ inputs = inputs.to(device)+ inputs = utils.tensor_to_gradcheck_var(inputs)+ assert gradcheck(kornia.enhance.equalize, (inputs,),+ raise_exception=True)++ @staticmethod+ def build_input(channels, height, width, bs=1, row=None):+ if row is None:+ row = torch.arange(width) / float(width)++ channel = torch.stack([row] * height)+ image = torch.stack([channel] * channels)+ batch = torch.stack([image] * bs)++ return batch+++class TestEqualize3D:+ def test_shape_equalize3d(self, device, dtype):+ bs, channels, depth, height, width = 1, 3, 6, 10, 10++ inputs3d = torch.ones(channels, depth, height, width, device=device, dtype=dtype)+ f = kornia.enhance.equalize3d++ assert f(inputs3d).shape == torch.Size([bs, channels, depth, height, width])++ def test_shape_equalize3d_batch(self, device, dtype):+ bs, channels, depth, height, width = 2, 3, 6, 10, 10++ inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=dtype)+ f = kornia.enhance.equalize3d++ assert f(inputs3d).shape == torch.Size([bs, channels, depth, height, width])++ def test_equalize3d(self, device):+ bs, channels, depth, height, width = 1, 3, 6, 10, 10++ inputs3d = self.build_input(channels, depth, height, width).squeeze(dim=0)+ inputs3d.to(device)++ row_expected = torch.tensor([+ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000+ ])+ expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected)+ expected = expected.to(device)++ f = kornia.enhance.equalize3d++ assert_allclose(f(inputs3d), expected)++ def test_equalize3d_batch(self, device):+ bs, channels, depth, height, width = 2, 3, 6, 10, 10++ inputs3d = self.build_input(channels, depth, height, width, bs)+ inputs3d = inputs3d.to(device)++ row_expected = torch.tensor([+ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000+ ])+ expected = self.build_input(channels, depth, height, width, bs, row=row_expected)+ expected = expected.to(device)++ f = kornia.enhance.equalize3d++ assert_allclose(f(inputs3d), expected)++ def test_gradcheck(self, device):+ bs, channels, depth, height, width = 2, 3, 6, 4, 5+ inputs3d = torch.ones(bs, channels, depth, height, width)+ inputs3d = inputs3d.to(device)+ inputs3d = utils.tensor_to_gradcheck_var(inputs3d)+ assert gradcheck(kornia.enhance.equalize3d, (inputs3d,),+ raise_exception=True)++ @staticmethod+ def build_input(channels, depth, height, width, bs=1, row=None):+ if row is None:+ row = torch.arange(width) / float(width)++ channel = torch.stack([row] * height)+ image = torch.stack([channel] * channels)+ image3d = torch.stack([image] * depth).transpose(0, 1)+ batch = torch.stack([image3d] * bs)++ return batch