π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add cuda tests for inverse_depth_smoothness_loss
edgarriba8bd94250fc04
diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex 871814e89..b4b9a1c78 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -6,6 +6,71 @@ import torch.nn.functional as F# https://github.com/tensorflow/models/blob/master/research/struct2depth/model.py#L625-L641+def _gradient_x(img: torch.Tensor) -> torch.Tensor:+ assert len(img.shape) == 4, img.shape+ return img[:, :, :, :-1] - img[:, :, :, 1:]+++def _gradient_y(img: torch.Tensor) -> torch.Tensor:+ assert len(img.shape) == 4, img.shape+ return img[:, :, :-1, :] - img[:, :, 1:, :]+++def inverse_depth_smoothness_loss(+ idepth: torch.Tensor,+ image: torch.Tensor) -> torch.Tensor:+ r"""Computes image-aware inverse depth smoothness loss.++ See :class:`~kornia.losses.InvDepthSmoothnessLoss` for details.+ """+ if not torch.is_tensor(idepth):+ raise TypeError("Input idepth type is not a torch.Tensor. Got {}"+ .format(type(idepth)))++ if not torch.is_tensor(image):+ raise TypeError("Input image type is not a torch.Tensor. Got {}"+ .format(type(image)))++ if not len(idepth.shape) == 4:+ raise ValueError("Invalid idepth shape, we expect BxCxHxW. Got: {}"+ .format(idepth.shape))++ if not len(image.shape) == 4:+ raise ValueError("Invalid image shape, we expect BxCxHxW. Got: {}"+ .format(image.shape))++ if not idepth.shape[-2:] == image.shape[-2:]:+ raise ValueError("idepth and image shapes must be the same. Got: {}"+ .format(idepth.shape, image.shape))++ if not idepth.device == image.device:+ raise ValueError(+ "idepth and image must be in the same device. Got: {}" .format(+ idepth.device, image.device))++ if not idepth.dtype == image.dtype:+ raise ValueError(+ "idepth and image must be in the same dtype. Got: {}" .format(+ idepth.dtype, image.dtype))++ # compute the gradients+ idepth_dx: torch.Tensor = _gradient_x(idepth)+ idepth_dy: torch.Tensor = _gradient_y(idepth)+ image_dx: torch.Tensor = _gradient_x(image)+ image_dy: torch.Tensor = _gradient_y(image)++ # compute image weights+ weights_x: torch.Tensor = torch.exp(+ -torch.mean(torch.abs(image_dx), dim=1, keepdim=True))+ weights_y: torch.Tensor = torch.exp(+ -torch.mean(torch.abs(image_dy), dim=1, keepdim=True))++ # apply image weights to depth+ smoothness_x: torch.Tensor = torch.abs(idepth_dx * weights_x)+ smoothness_y: torch.Tensor = torch.abs(idepth_dy * weights_y)+ return torch.mean(smoothness_x) + torch.mean(smoothness_y)++class InverseDepthSmoothnessLoss(nn.Module):r"""Criterion that computes image-aware inverse depth smoothness loss.@@ -32,71 +97,5 @@ class InverseDepthSmoothnessLoss(nn.Module):def __init__(self) -> None:super(InverseDepthSmoothnessLoss, self).__init__()- @staticmethod- def gradient_x(img: torch.Tensor) -> torch.Tensor:- assert len(img.shape) == 4, img.shape- return img[:, :, :, :-1] - img[:, :, :, 1:]-- @staticmethod- def gradient_y(img: torch.Tensor) -> torch.Tensor:- assert len(img.shape) == 4, img.shape- return img[:, :, :-1, :] - img[:, :, 1:, :]-- def forward( # type: ignore- self,- idepth: torch.Tensor,- image: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(idepth):- raise TypeError("Input idepth type is not a torch.Tensor. Got {}"- .format(type(idepth)))- if not torch.is_tensor(image):- raise TypeError("Input image type is not a torch.Tensor. Got {}"- .format(type(image)))- if not len(idepth.shape) == 4:- raise ValueError("Invalid idepth shape, we expect BxCxHxW. Got: {}"- .format(idepth.shape))- if not len(image.shape) == 4:- raise ValueError("Invalid image shape, we expect BxCxHxW. Got: {}"- .format(image.shape))- if not idepth.shape[-2:] == image.shape[-2:]:- raise ValueError("idepth and image shapes must be the same. Got: {}"- .format(idepth.shape, image.shape))- if not idepth.device == image.device:- raise ValueError(- "idepth and image must be in the same device. Got: {}" .format(- idepth.device, image.device))- if not idepth.dtype == image.dtype:- raise ValueError(- "idepth and image must be in the same dtype. Got: {}" .format(- idepth.dtype, image.dtype))- # compute the gradients- idepth_dx: torch.Tensor = self.gradient_x(idepth)- idepth_dy: torch.Tensor = self.gradient_y(idepth)- image_dx: torch.Tensor = self.gradient_x(image)- image_dy: torch.Tensor = self.gradient_y(image)-- # compute image weights- weights_x: torch.Tensor = torch.exp(- -torch.mean(torch.abs(image_dx), dim=1, keepdim=True))- weights_y: torch.Tensor = torch.exp(- -torch.mean(torch.abs(image_dy), dim=1, keepdim=True))-- # apply image weights to depth- smoothness_x: torch.Tensor = torch.abs(idepth_dx * weights_x)- smoothness_y: torch.Tensor = torch.abs(idepth_dy * weights_y)- return torch.mean(smoothness_x) + torch.mean(smoothness_y)---######################-# functional interface-######################---def inverse_depth_smoothness_loss(- idepth: torch.Tensor,- image: torch.Tensor) -> torch.Tensor:- r"""Computes image-aware inverse depth smoothness loss.-- See :class:`~kornia.losses.InvDepthSmoothnessLoss` for details.- """- return InverseDepthSmoothnessLoss()(idepth, image)+ def forward(self, idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor: # type:ignore+ return inverse_depth_smoothness_loss(idepth, image)diff --git a/test/test_losses.py b/test/test_losses.pyindex 5db15a795..f03e1edd6 100644--- a/test/test_losses.py+++ b/test/test_losses.py@@ -144,24 +144,25 @@ class TestDiceLoss:class TestDepthSmoothnessLoss:- def _test_smoke(self):- image = self.image.clone()- depth = self.depth.clone()+ @pytest.mark.parametrize("data_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])+ def test_smoke(self, device, data_shape):+ image = torch.rand(data_shape).to(device)+ depth = torch.rand(data_shape).to(device)criterion = kornia.losses.InverseDepthSmoothnessLoss()loss = criterion(depth, image)# TODO: implement me- def _test_1(self):+ def test_1(self, device):pass# TODO: implement me- def _test_jit(self):+ def test_jit(self, device):pass- def _test_gradcheck(self):- image = self.image.clone()- depth = self.depth.clone()+ def test_gradcheck(self, device):+ image = torch.rand(1, 1, 10, 16).to(device)+ depth = torch.rand(1, 1, 10, 16).to(device)depth = utils.tensor_to_gradcheck_var(depth) # to varimage = utils.tensor_to_gradcheck_var(image) # to varassert gradcheck(@@ -170,14 +171,6 @@ class TestDepthSmoothnessLoss:raise_exception=True,)- @pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])- def test_run_all(self, batch_shape):- self.image = torch.rand(batch_shape)- self.depth = torch.rand(batch_shape)-- self._test_smoke()- self._test_gradcheck()-@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("reduction_type", ["none", "mean", "sum"])