Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add missing tests (losses, io, connected components) (#2565)

João Gustavo A. Amorimabc642b5cdb3
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index 6dbdb833f..99c1d95eb 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -1,8 +1,10 @@
import torch
import torch.nn.functional as F
+from kornia.core import Tensor
-def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torch.Tensor:
+
+def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor:
r"""Computes the Connected-component labelling (CCL) algorithm.
.. image:: https://github.com/kornia/data/raw/main/cells_segmented.png
@@ -29,8 +31,8 @@ def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torc
>>> img = torch.rand(2, 1, 4, 5)
>>> img_labels = connected_components(img, num_iterations=100)
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input imagetype is not a torch.Tensor. Got: {type(image)}")
+ if not isinstance(image, Tensor):
+ raise TypeError(f"Input imagetype is not a Tensor. Got: {type(image)}")
if not isinstance(num_iterations, int) or num_iterations < 1:
raise TypeError("Input num_iterations must be a positive integer.")
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 207e50f01..cced7f16c 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -2,7 +2,7 @@ from __future__ import annotations
try:
import kornia_rs
-except ImportError:
+except ImportError: # pragma: no cover
kornia_rs = None
import os
@@ -66,7 +66,7 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
Return:
Image tensor with shape :math:`(3,H,W)`.
"""
- if kornia_rs is None:
+ if kornia_rs is None: # pragma: no cover
raise ModuleNotFoundError("The io API is not available: `pip install kornia_rs` in a Linux system.")
if isinstance(path_file, Path):
@@ -86,16 +86,19 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
elif image.shape[0] == 4 and image.dtype == torch.uint8:
gray32 = rgb_to_grayscale(rgba_to_rgb(to_float32(image)))
return to_uint8(gray32)
+
elif desired_type == ImageLoadType.RGB8:
if image.shape[0] == 3 and image.dtype == torch.uint8:
return image
elif image.shape[0] == 1 and image.dtype == torch.uint8:
rgb8 = grayscale_to_rgb(image)
return rgb8
+
elif desired_type == ImageLoadType.RGBA8:
if image.shape[0] == 3 and image.dtype == torch.uint8:
rgba32 = rgb_to_rgba(to_float32(image), 0.0)
return to_uint8(rgba32)
+
elif desired_type == ImageLoadType.GRAY32:
if image.shape[0] == 1 and image.dtype == torch.uint8:
return to_float32(image)
@@ -105,15 +108,15 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
elif image.shape[0] == 4 and image.dtype == torch.uint8:
gray32 = rgb_to_grayscale(rgba_to_rgb(to_float32(image)))
return gray32
+
elif desired_type == ImageLoadType.RGB32:
if image.shape[0] == 3 and image.dtype == torch.uint8:
return to_float32(image)
elif image.shape[0] == 1 and image.dtype == torch.uint8:
rgb32 = grayscale_to_rgb(to_float32(image))
return rgb32
- else:
- raise NotImplementedError(f"Unknown type: {desired_type}")
- return Tensor([])
+
+ raise NotImplementedError(f"Unknown type: {desired_type}")
def write_image(path_file: str | Path, image: Tensor) -> None:
@@ -128,7 +131,7 @@ def write_image(path_file: str | Path, image: Tensor) -> None:
Return:
None.
"""
- if kornia_rs is None:
+ if kornia_rs is None: # pragma: no cover
raise ModuleNotFoundError("The io API is not available: `pip install kornia_rs` in a Linux system.")
if isinstance(path_file, Path):
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index f75dec42f..a44194cdc 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -49,7 +49,9 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
KORNIA_CHECK_SAME_DEVICE(img1, img2)
- KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")
+ KORNIA_CHECK(
+ reduction in ("mean", "sum", "none", None), f"Given type of reduction is not supported. Got: {reduction}"
+ )
# compute loss
loss = (0.5 * (img1 - img2) ** 2 + 1.0).log()
@@ -59,8 +61,11 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
- elif reduction == "none":
+ elif reduction == "none" or reduction is None:
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 8b2a3ce10..80e7e4f70 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -55,7 +55,9 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
KORNIA_CHECK_SAME_DEVICE(img1, img2)
- KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")
+ KORNIA_CHECK(
+ reduction in ("mean", "sum", "none", None), f"Given type of reduction is not supported. Got: {reduction}"
+ )
# compute loss
loss = ((img1 - img2) ** 2 + 1.0).sqrt() - 1.0
@@ -65,8 +67,11 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
- elif reduction == "none":
+ elif reduction == "none" or reduction is None:
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index a0b1090dc..5beaed5b0 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -49,7 +49,9 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
KORNIA_CHECK_SAME_DEVICE(img1, img2)
- KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")
+ KORNIA_CHECK(
+ reduction in ("mean", "sum", "none", None), f"Given type of reduction is not supported. Got: {reduction}"
+ )
# compute loss
loss = 2.0 * (img1 - img2) ** 2 / ((img1 - img2) ** 2 + 4.0)
@@ -59,8 +61,11 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
- elif reduction == "none":
+ elif reduction == "none" or reduction is None:
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index b8101d451..7f34ba779 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -56,9 +56,6 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
KORNIA_CHECK_SHAPE(target, ["B", "H", "W"])
- if not pred.shape[1] == 1:
- raise ValueError(f"Invalid pred shape, we expect Bx1xHxW. Got: {pred.shape}")
-
if not pred.shape[-2:] == target.shape[-2:]:
raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 6bf36705a..18d13f719 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -58,6 +58,9 @@ def ssim_loss(
loss = torch.sum(loss)
elif reduction == "none":
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index 366be12da..e74f2fdfc 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -56,6 +56,9 @@ def ssim3d_loss(
loss = loss.sum()
elif reduction == "none":
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 93ea4d3bb..96d0c55a6 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -54,6 +54,8 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
elif reduction == "sum":
res1 = res1.sum(dim=reduce_axes)
res2 = res2.sum(dim=reduce_axes)
+ else:
+ raise NotImplementedError('Invalid reduction option.')
return res1 + res2
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index dc4f2e766..11bf1584a 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -62,6 +62,9 @@ def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
loss = loss.sum()
elif reduction == "none":
pass
+ else:
+ raise NotImplementedError('Invalid reduction option.')
+
return loss
diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.py
index f3a3c6b3a..513aea20a 100644
--- a/test/contrib/test_contrib.py
+++ b/test/contrib/test_contrib.py
@@ -112,15 +112,22 @@ class TestConnectedComponents:
def test_exception(self, device, dtype):
img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components(img, 1.0)
+ assert 'Input num_iterations must be a positive integer.' in str(errinf)
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError) as errinf:
+ assert kornia.contrib.connected_components('not a tensor', 0)
+ assert 'Input imagetype is not a Tensor. Got:' in str(errinf)
+
+ with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components(img, 0)
+ assert 'Input num_iterations must be a positive integer.' in str(errinf)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError) as errinf:
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
assert kornia.contrib.connected_components(img, 2)
+ assert 'Input image shape must be (*,1,H,W). Got:' in str(errinf)
def test_value(self, device, dtype):
img = torch.tensor(
diff --git a/test/io/test_io_image.py b/test/io/test_io_image.py
index 50fa981f4..a2cc6cccd 100644
--- a/test/io/test_io_image.py
+++ b/test/io/test_io_image.py
@@ -24,8 +24,8 @@ def create_random_img8(height: int, width: int, channels: int) -> np.ndarray:
return (np.random.rand(height, width, channels) * 255).astype(np.uint8) # noqa: NPY002
-def create_random_img8_torch(height: int, width: int, channels: int) -> Tensor:
- return (torch.rand(channels, height, width) * 255).to(torch.uint8)
+def create_random_img8_torch(height: int, width: int, channels: int, device=None) -> Tensor:
+ return (torch.rand(channels, height, width, device=device) * 255).to(torch.uint8)
@pytest.mark.skipif(not available_package(), reason="kornia_rs only supports python >=3.7 and pt >= 1.10.0")
@@ -35,11 +35,11 @@ class TestIoImage:
img_th: Tensor = create_random_img8_torch(height, width, 3)
file_path = tmp_path / "image.jpg"
- write_image(file_path, img_th)
+ write_image(str(file_path), img_th)
assert file_path.is_file()
- img_load: Tensor = load_image(file_path, ImageLoadType.UNCHANGED)
+ img_load: Tensor = load_image(str(file_path), ImageLoadType.UNCHANGED)
assert img_th.shape == img_load.shape
assert img_th.shape[1:] == (height, width)
@@ -58,61 +58,43 @@ class TestIoImage:
assert str(img_th.device) == str(device)
@pytest.mark.parametrize("ext", ["png", "jpg"])
- def test_types_color(self, tmp_path: Path, ext) -> None:
+ @pytest.mark.parametrize(
+ "channels,load_type,expected_type,expected_channels",
+ [
+ # NOTE: these tests which should write and load images with channel size != 3, didn't do it
+ # (1, ImageLoadType.GRAY8, torch.uint8, 1),
+ (3, ImageLoadType.GRAY8, torch.uint8, 1),
+ # (4, ImageLoadType.GRAY8, torch.uint8, 1),
+ # (1, ImageLoadType.GRAY32, torch.float32, 1),
+ (3, ImageLoadType.GRAY32, torch.float32, 1),
+ # (4, ImageLoadType.GRAY32, torch.float32, 1),
+ (3, ImageLoadType.RGB8, torch.uint8, 3),
+ # (1, ImageLoadType.RGB8, torch.uint8, 3),
+ (3, ImageLoadType.RGBA8, torch.uint8, 4),
+ # (1, ImageLoadType.RGB32, torch.float32, 3),
+ (3, ImageLoadType.RGB32, torch.float32, 3),
+ ],
+ )
+ def test_load_image(self, tmp_path: Path, ext, channels, load_type, expected_type, expected_channels):
height, width = 4, 5
- img_np: np.ndarray = create_random_img8(height, width, 3)
+ img_np: np.ndarray = create_random_img8(height, width, channels)
file_path = tmp_path / f"image.{ext}"
cv2.imwrite(str(file_path), img_np)
assert file_path.is_file()
- img = load_image(file_path, ImageLoadType.GRAY8)
- assert img.shape[0] == 1
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.GRAY32)
- assert img.shape[0] == 1
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGB8)
- assert img.shape[0] == 3
- assert img.dtype == torch.uint8
+ img = load_image(file_path, load_type)
+ assert img.shape[0] == expected_channels
+ assert img.dtype == expected_type
- img = load_image(file_path, ImageLoadType.RGB32)
- assert img.shape[0] == 3
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGBA8)
- assert img.shape[0] == 4
- assert img.dtype == torch.uint8
-
- @pytest.mark.parametrize("ext", ["png", "jpg"])
- def test_types_gray(self, tmp_path: Path, ext) -> None:
+ @pytest.mark.parametrize("ext", ["jpg"])
+ @pytest.mark.parametrize("channels", [3])
+ def test_write_image(self, device, tmp_path, ext, channels):
height, width = 4, 5
- img_np: np.ndarray = create_random_img8(height, width, 1)
+ img_th: Tensor = create_random_img8_torch(height, width, channels, device)
file_path = tmp_path / f"image.{ext}"
- cv2.imwrite(str(file_path), img_np)
+ write_image(file_path, img_th)
assert file_path.is_file()
-
- img = load_image(file_path, ImageLoadType.GRAY8)
- assert img.shape[0] == 1
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.GRAY32)
- assert img.shape[0] == 1
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGB8)
- assert img.shape[0] == 3
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.RGB32)
- assert img.shape[0] == 3
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGBA8)
- assert img.shape[0] == 4
- assert img.dtype == torch.uint8
diff --git a/test/losses/test_hd.py b/test/losses/test_hd.py
index 7b1e66f65..a44f7825b 100644
--- a/test/losses/test_hd.py
+++ b/test/losses/test_hd.py
@@ -114,6 +114,32 @@ class TestHausdorffLoss:
loss(logits, labels)
+ def test_exception_2d(self):
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.HausdorffERLoss()((torch.rand(1, 2, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
+ assert 'Only 2D images supported. Got ' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.HausdorffERLoss()(
+ (torch.rand(1, 2, 1, 1) > 0.5) * 1, torch.tensor([[[[1]]]], dtype=torch.float32)
+ )
+ assert 'Expect long type target value in range' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.HausdorffERLoss()((torch.rand(1, 2, 1, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
+ assert 'Prediction and target need to be of same size, and target should not be one-hot.' in str(errinf)
+
+ def test_exception_3d(self):
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.HausdorffERLoss3D()((torch.rand(1, 2, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
+ assert 'Only 3D images supported. Got ' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.HausdorffERLoss3D()(
+ (torch.rand(1, 2, 1, 1, 1) > 0.5) * 1, torch.tensor([[[[[5]]]]], dtype=torch.float32)
+ )
+ assert 'Invalid target value' in str(errinf)
+
@pytest.mark.parametrize(
"hd,shape", [[kornia.losses.HausdorffERLoss, (50, 50)], [kornia.losses.HausdorffERLoss3D, (50, 50, 50)]]
)
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index 241391e55..9005fa39c 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -184,6 +184,25 @@ class TestTverskyLoss:
criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
assert criterion(logits, labels) is not None
+ def test_exception(self):
+ criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
+
+ with pytest.raises(TypeError) as errinfo:
+ criterion('not a tensor', torch.rand(1))
+ assert 'Input type is not a torch.Tensor. Got' in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1), torch.rand(1))
+ assert 'Invalid input shape, we expect BxNxHxW. Got:' in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
+ assert 'input and target shapes must be the same. Got:' in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
+ assert 'input and target must be in the same device. Got:' in str(errinfo)
+
def test_all_zeros(self, device, dtype):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)
@@ -259,6 +278,19 @@ class TestDiceLoss:
loss = criterion(logits, labels)
assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ def test_exception(self):
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.DiceLoss()(torch.rand(1, 1, 1), torch.rand(1, 1, 1))
+ assert 'Invalid input shape, we expect BxNxHxW. Got:' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
+ assert 'input and target shapes must be the same. Got: ' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
+ assert 'input and target must be in the same device. Got:' in str(errinf)
+
def test_averaging_micro(self, device, dtype):
num_classes = 2
eps = 1e-8
@@ -353,6 +385,37 @@ class TestDepthSmoothnessLoss:
criterion = kornia.losses.InverseDepthSmoothnessLoss()
assert criterion(depth, image) is not None
+ def test_exception(self):
+ with pytest.raises(TypeError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(1, 1)
+ assert 'Input idepth type is not a torch.Tensor. Got' in str(errinf)
+
+ with pytest.raises(TypeError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1), 1)
+ assert 'Input image type is not a torch.Tensor. Got' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1), torch.rand(1, 1, 1, 1))
+ assert 'Invalid idepth shape, we expect BxCxHxW. Got' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1))
+ assert 'Invalid image shape, we expect BxCxHxW. Got:' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
+ assert 'idepth and image shapes must be the same. Got' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
+ assert 'idepth and image must be in the same device. Got:' in str(errinf)
+
+ with pytest.raises(ValueError) as errinf:
+ kornia.losses.InverseDepthSmoothnessLoss()(
+ torch.rand(1, 1, 1, 1, dtype=torch.float32), torch.rand(1, 1, 1, 1, dtype=torch.float64)
+ )
+ assert 'idepth and image must be in the same dtype. Got:' in str(errinf)
+
def test_dynamo(self, device, dtype, torch_optimizer):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -503,6 +566,18 @@ class TestTotalVariation:
actual = kornia.losses.total_variation(input.to(device, dtype))
assert_close(actual, expected.to(device, dtype))
+ # Total variation of constant vectors is 0
+ @pytest.mark.parametrize(
+ "input, expected",
+ [
+ (torch.ones(3, 4, 5), torch.tensor([0.0, 0.0, 0.0])),
+ (2 * torch.ones(2, 3, 4, 5), torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])),
+ ],
+ )
+ def test_tv_on_constant_int(self, device, input, expected):
+ actual = kornia.losses.total_variation(input.to(device, dtype=torch.int32), reduction='mean')
+ assert_close(actual, expected.to(device))
+
# Total variation for 3D tensors
@pytest.mark.parametrize(
"input, expected",
@@ -688,13 +763,24 @@ class TestPSNRLoss:
class TestLovaszHingeLoss:
def test_smoke(self, device, dtype):
num_classes = 1
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
+ logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
+ labels = torch.rand(2, 1, 1) * num_classes
labels = labels.to(device).long()
criterion = kornia.losses.LovaszHingeLoss()
assert criterion(logits, labels) is not None
+ def test_exception(self):
+ criterion = kornia.losses.LovaszHingeLoss()
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 2), torch.rand(1, 1, 1))
+ assert 'pred and target shapes must be the same. Got:' in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, device='meta'))
+ assert 'pred and target must be in the same device. Got:' in str(errinfo)
+
def test_multi_class(self, device, dtype):
num_classes = 5
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -749,13 +835,36 @@ class TestLovaszHingeLoss:
class TestLovaszSoftmaxLoss:
def test_smoke(self, device, dtype):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
+ logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
+ labels = torch.rand(2, 1, 1) * num_classes
labels = labels.to(device).long()
criterion = kornia.losses.LovaszSoftmaxLoss()
assert criterion(logits, labels) is not None
+ def test_exception(self):
+ criterion = kornia.losses.LovaszSoftmaxLoss()
+
+ with pytest.raises(TypeError) as errinfo:
+ criterion(torch.rand(1), torch.rand(1))
+ assert "shape must be [['B', 'N', 'H', 'W']]. Got" in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1))
+ assert "shape must be [['B', 'H', 'W']]. Got" in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1))
+ assert "Invalid pred shape, we expect BxNxHxW, with N > 1." in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 2, 1, 1), torch.rand(1, 1, 2))
+ assert "pred and target shapes must be the same. Got:" in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1, 2, 1, 1), torch.rand(1, 1, 1, device='meta'))
+ assert "pred and target must be in the same device. Got:" in str(errinfo)
+
def test_binary(self, device, dtype):
num_classes = 1
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -903,7 +1012,7 @@ class TestWelschLoss(BaseTester):
class TestCauchyLoss(BaseTester):
- @pytest.mark.parametrize("reduction", ["mean", "sum", "none"])
+ @pytest.mark.parametrize("reduction", ["mean", "sum", "none", None])
@pytest.mark.parametrize("shape", [(1, 2, 9, 9), (2, 4, 3, 6)])
def test_smoke(self, device, dtype, reduction, shape):
img1 = torch.rand(shape, device=device, dtype=dtype)
@@ -997,7 +1106,7 @@ class TestCauchyLoss(BaseTester):
class TestGemanMcclureLossLoss(BaseTester):
- @pytest.mark.parametrize("reduction", ["mean", "sum", "none"])
+ @pytest.mark.parametrize("reduction", ["mean", "sum", "none", None])
@pytest.mark.parametrize("shape", [(1, 2, 9, 9), (2, 4, 3, 6)])
def test_smoke(self, device, dtype, reduction, shape):
img1 = torch.rand(shape, device=device, dtype=dtype)
@@ -1091,7 +1200,7 @@ class TestGemanMcclureLossLoss(BaseTester):
class TestCharbonnierLoss(BaseTester):
- @pytest.mark.parametrize("reduction", ["mean", "sum", "none"])
+ @pytest.mark.parametrize("reduction", ["mean", "sum", "none", None])
@pytest.mark.parametrize("shape", [(1, 2, 9, 9), (2, 4, 3, 6)])
def test_smoke(self, device, dtype, reduction, shape):
img1 = torch.rand(shape, device=device, dtype=dtype)
diff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.py
index 657dd174e..aa6c323a2 100644
--- a/test/losses/test_ssim.py
+++ b/test/losses/test_ssim.py
@@ -21,7 +21,7 @@ class TestSSIMLoss:
assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)
@pytest.mark.parametrize("window_size", [5, 11])
- @pytest.mark.parametrize("reduction_type", ["mean", "sum"])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
@pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):
if device.type == 'xla':
@@ -33,7 +33,12 @@ class TestSSIMLoss:
loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
+ if reduction_type == 'none':
+ expected = torch.zeros_like(img)
+ else:
+ expected = torch.tensor(0.0, device=device, dtype=dtype)
+
+ assert_close(loss, expected, rtol=tol_val, atol=tol_val)
def test_module(self, device, dtype):
img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -75,8 +80,23 @@ class TestMS_SSIMLoss:
assert_close(msssim1.item(), 0.0)
assert_close(msssim2.item(), 0.0)
+ def test_exception(self):
+ criterion = kornia.losses.MS_SSIMLoss()
+
+ with pytest.raises(TypeError) as errinfo:
+ criterion(1, 2)
+ assert 'Input type is not a torch.Tensor. Got' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ criterion(torch.rand(1), 2)
+ assert 'Output type is not a torch.Tensor. Got' in str(errinfo)
+
+ with pytest.raises(ValueError) as errinfo:
+ criterion(torch.rand(1), torch.rand(1, 2))
+ assert 'Input shapes should be same. Got' in str(errinfo)
+
# TODO: implement for single channel image
- @pytest.mark.parametrize("reduction_type", ["mean", "sum"])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
@pytest.mark.parametrize("batch_shape", [(2, 1, 2, 3), (1, 3, 10, 16)])
def test_msssim(self, device, dtype, batch_shape, reduction_type):
img = torch.rand(batch_shape, device=device, dtype=dtype)
@@ -84,7 +104,7 @@ class TestMS_SSIMLoss:
msssiml1 = kornia.losses.MS_SSIMLoss(reduction=reduction_type).to(device, dtype)
loss = msssiml1(img, img)
- assert_close(loss.item(), 0.0)
+ assert_close(loss.sum().item(), 0.0)
def test_gradcheck(self, device):
# input data
@@ -125,7 +145,7 @@ class TestSSIM3DLoss(BaseTester):
self.assert_close(ssim2, torch.zeros_like(img2))
@pytest.mark.parametrize("window_size", [5, 11])
- @pytest.mark.parametrize("reduction_type", ["mean", "sum"])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
@pytest.mark.parametrize("shape", [(1, 1, 2, 16, 16), (2, 4, 2, 15, 20)])
def test_ssim(self, device, dtype, shape, window_size, reduction_type):
if device.type == 'xla':
@@ -134,7 +154,11 @@ class TestSSIM3DLoss(BaseTester):
# Sanity test
img = torch.rand(shape, device=device, dtype=dtype)
actual = kornia.losses.ssim3d_loss(img, img, window_size, reduction=reduction_type)
- expected = torch.tensor(0.0, device=device, dtype=dtype)
+ if reduction_type == 'none':
+ expected = torch.zeros_like(img)
+ else:
+ expected = torch.tensor(0.0, device=device, dtype=dtype)
+
self.assert_close(actual, expected)
# Check loss computation
@@ -147,6 +171,8 @@ class TestSSIM3DLoss(BaseTester):
expected = torch.tensor(0.9999, device=device, dtype=dtype)
elif reduction_type == 'sum':
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.9999).sum()
+ elif reduction_type == 'none':
+ expected = torch.ones_like(img1, device=device, dtype=dtype) * 0.9999
self.assert_close(actual, expected)