Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

moved one_hot and metrics to utils

edgarribaca2e8e874f93
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 191f86f1a..2451be781 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -26,7 +26,6 @@ TGM focuses on Image and tensor warping functions such as:
filters
geometry
losses
- metrics
utils
.. toctree::
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index cdba74861..1ff8d066e 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -3,7 +3,6 @@ torchgeometry.losses
.. currentmodule:: torchgeometry.losses
-.. autofunction:: one_hot
.. autofunction:: dice_loss
.. autofunction:: tversky_loss
.. autofunction:: focal_loss
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rst
index d6ce9f0a0..9ff8e95f9 100644
--- a/docs/source/metrics.rst
+++ b/docs/source/metrics.rst
@@ -1,7 +1,7 @@
-torchgeometry.metrics
-=====================
+torchgeometry.utils.metrics
+===========================
-.. currentmodule:: torchgeometry.metrics
+.. currentmodule:: torchgeometry.utils.metrics
.. autofunction:: confusion_matrix
.. autofunction:: mean_iou
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
index 4de93b3fe..ec94f0b97 100644
--- a/docs/source/utils.rst
+++ b/docs/source/utils.rst
@@ -6,3 +6,9 @@ torchgeometry.utils
.. autofunction:: tensor_to_image
.. autofunction:: image_to_tensor
.. autofunction:: create_meshgrid
+.. autofunction:: one_hot
+
+.. toctree::
+ :maxdepth: 2
+
+ metrics
diff --git a/mypy_files.txt b/mypy_files.txt
index b79614cd7..a5b0202b6 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -7,6 +7,11 @@ torchgeometry/contrib/extract_patches.py
torchgeometry/contrib/max_blur_pool.py
torchgeometry/feature/harris.py
torchgeometry/feature/nms.py
+torchgeometry/filters/blur.py
+torchgeometry/filters/gaussian.py
+torchgeometry/filters/laplacian.py
+torchgeometry/filters/median.py
+torchgeometry/filters/sobel.py
torchgeometry/geometry/homography_warper.py
torchgeometry/geometry/depth_warper.py
torchgeometry/geometry/pinhole.py
@@ -14,15 +19,13 @@ torchgeometry/geometry/imgwarp.py
torchgeometry/geometry/crop.py
torchgeometry/geometry/affine_warp.py
torchgeometry/geometry/pyramid.py
-torchgeometry/filters/gaussian.py
-torchgeometry/filters/laplacian.py
-torchgeometry/filters/sobel.py
-torchgeometry/filters/blur.py
-torchgeometry/filters/median.py
torchgeometry/losses/ssim.py
torchgeometry/losses/dice.py
torchgeometry/losses/focal.py
torchgeometry/losses/tversky.py
torchgeometry/losses/depth_smooth.py
-torchgeometry/metrics/confusion_matrix.py
-torchgeometry/metrics/mean_iou.py
+torchgeometry/utils/grid.py
+torchgeometry/utils/image.py
+torchgeometry/utils/one_hot.py
+torchgeometry/utils/metrics/confusion_matrix.py
+torchgeometry/utils/metrics/mean_iou.py
diff --git a/test/test_losses.py b/test/test_losses.py
index cfbfe46f1..2644bf445 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -116,24 +116,6 @@ class TestTverskyLoss:
self._test_gradcheck()
-class TestOneHot:
- def test_smoke(self):
- num_classes = 4
- labels = torch.zeros(2, 2, 1, dtype=torch.int64)
- labels[0, 0, 0] = 0
- labels[0, 1, 0] = 1
- labels[1, 0, 0] = 2
- labels[1, 1, 0] = 3
-
- # convert labels to one hot tensor
- one_hot = tgm.losses.one_hot(labels, num_classes)
-
- assert pytest.approx(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)
- assert pytest.approx(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)
- assert pytest.approx(one_hot[1, labels[1, 0, 0], 0, 0].item(), 1.0)
- assert pytest.approx(one_hot[1, labels[1, 1, 0], 1, 0].item(), 1.0)
-
-
class TestDiceLoss:
def _test_smoke(self):
num_classes = 3
diff --git a/test/test_utils.py b/test/utils/test_grid.py
similarity index 68%
rename from test/test_utils.py
rename to test/utils/test_grid.py
index f486fbfa7..bfe62c0de 100644
--- a/test/test_utils.py
+++ b/test/utils/test_grid.py
@@ -1,5 +1,4 @@
import pytest
-import numpy as np
import torch
import torchgeometry as tgm
@@ -7,24 +6,6 @@ import torchgeometry as tgm
import utils # test utils
[email protected]("batch_shape",
- [(4, 4), (1, 4, 4), (3, 4, 4), ])
-def test_tensor_to_image(batch_shape):
- tensor = torch.ones(batch_shape)
- image = tgm.utils.tensor_to_image(tensor)
- assert image.shape[:2] == batch_shape[-2:]
- assert isinstance(image, np.ndarray)
-
-
[email protected]("batch_shape",
- [(4, 4), (4, 4, 1), (4, 4, 3), ])
-def test_image_to_tensor(batch_shape):
- image = np.ones(batch_shape)
- tensor = tgm.utils.image_to_tensor(image)
- assert tensor.shape[-2:] == batch_shape[:2]
- assert isinstance(tensor, torch.Tensor)
-
-
def test_create_meshgrid():
height, width = 4, 6
normalized_coordinates = False
diff --git a/test/utils/test_image.py b/test/utils/test_image.py
new file mode 100644
index 000000000..da735bc26
--- /dev/null
+++ b/test/utils/test_image.py
@@ -0,0 +1,25 @@
+import pytest
+import numpy as np
+
+import torch
+import torchgeometry as tgm
+
+import utils # test utils
+
+
[email protected]("batch_shape",
+ [(4, 4), (1, 4, 4), (3, 4, 4), ])
+def test_tensor_to_image(batch_shape):
+ tensor = torch.ones(batch_shape)
+ image = tgm.utils.tensor_to_image(tensor)
+ assert image.shape[:2] == batch_shape[-2:]
+ assert isinstance(image, np.ndarray)
+
+
[email protected]("batch_shape",
+ [(4, 4), (4, 4, 1), (4, 4, 3), ])
+def test_image_to_tensor(batch_shape):
+ image = np.ones(batch_shape)
+ tensor = tgm.utils.image_to_tensor(image)
+ assert tensor.shape[-2:] == batch_shape[:2]
+ assert isinstance(tensor, torch.Tensor)
diff --git a/test/test_metrics.py b/test/utils/test_metrics.py
similarity index 86%
rename from test/test_metrics.py
rename to test/utils/test_metrics.py
index bea753b60..00bbeb9e8 100644
--- a/test/test_metrics.py
+++ b/test/utils/test_metrics.py
@@ -16,7 +16,7 @@ class TestMeanIoU:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 0]])
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
[[1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
@@ -30,7 +30,7 @@ class TestMeanIoU:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
[[1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
@@ -44,8 +44,8 @@ class TestMeanIoU:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 1]])
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
[[0.75, 0.80]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
@@ -65,7 +65,7 @@ class TestMeanIoU:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
[[1.0, 1.0, 1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
@@ -85,7 +85,7 @@ class TestMeanIoU:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
+ mean_iou = tgm.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
[[0.0, 1.0, 0.5, 0.5]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
@@ -100,7 +100,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 1]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[3, 1],
[0, 4]]], dtype=torch.float32)
@@ -114,7 +114,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 1]]).repeat(batch_size, 1)
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[3, 1],
[0, 4]]], dtype=torch.float32)
@@ -127,7 +127,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[4, 1, 2],
[3, 0, 2],
@@ -141,7 +141,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[0, 0, 0, 0],
[0, 4, 1, 2],
@@ -157,7 +157,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
- conf_mat = tgm.metrics.confusion_matrix(
+ conf_mat = tgm.utils.metrics.confusion_matrix(
predicted, actual, num_classes, normalized)
conf_mat_real = torch.tensor(
@@ -179,7 +179,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[4, 0, 0, 0],
[0, 4, 0, 0],
@@ -200,7 +200,7 @@ class TestConfusionMatrix:
[2, 2, 1, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[3, 0, 0, 1],
[1, 3, 0, 0],
@@ -221,7 +221,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[0, 0, 0, 4],
[0, 4, 0, 0],
@@ -242,7 +242,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat = tgm.utils.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[0, 0, 4, 4],
[0, 0, 0, 0],
diff --git a/test/utils/test_one_hot.py b/test/utils/test_one_hot.py
new file mode 100644
index 000000000..52d53d009
--- /dev/null
+++ b/test/utils/test_one_hot.py
@@ -0,0 +1,24 @@
+import pytest
+
+import torch
+import torchgeometry as tgm
+
+import utils # test utils
+
+
+class TestOneHot:
+ def test_smoke(self):
+ num_classes = 4
+ labels = torch.zeros(2, 2, 1, dtype=torch.int64)
+ labels[0, 0, 0] = 0
+ labels[0, 1, 0] = 1
+ labels[1, 0, 0] = 2
+ labels[1, 1, 0] = 3
+
+ # convert labels to one hot tensor
+ one_hot = tgm.utils.one_hot(labels, num_classes)
+
+ assert pytest.approx(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)
+ assert pytest.approx(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)
+ assert pytest.approx(one_hot[1, labels[1, 0, 0], 0, 0].item(), 1.0)
+ assert pytest.approx(one_hot[1, labels[1, 1, 0], 1, 0].item(), 1.0)
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index 2472940d0..5db1f45e6 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -12,19 +12,49 @@ from torchgeometry import feature
from torchgeometry import filters
from torchgeometry import geometry
from torchgeometry import losses
-from torchgeometry import metrics
from torchgeometry import utils
# Exposes package functional to top level
from torchgeometry.color import (
- rgb_to_grayscale, bgr_to_rgb, rgb_to_bgr, rgb_to_hsv, hsv_to_rgb, normalize
+ rgb_to_grayscale,
+ bgr_to_rgb,
+ rgb_to_bgr,
+ rgb_to_hsv,
+ hsv_to_rgb,
+ normalize,
)
from torchgeometry.contrib import (
- spatial_soft_argmax2d, extract_tensor_patches, max_blur_pool2d,
+ spatial_soft_argmax2d,
+ extract_tensor_patches,
+ max_blur_pool2d,
)
from torchgeometry.feature import (
- non_maxima_suppression2d, corner_harris,
+ non_maxima_suppression2d,
+ corner_harris,
+)
+from torchgeometry.filters import (
+ get_gaussian_kernel,
+ get_gaussian_kernel2d,
+ get_laplacian_kernel,
+ get_laplacian_kernel2d,
+ gaussian_blur,
+ laplacian,
+ sobel,
+ spatial_gradient,
+ box_blur,
+ median_blur,
+)
+from torchgeometry.losses import (
+ ssim,
+ dice_loss,
+ tversky_loss,
+ inverse_depth_smoothness_loss,
+)
+from torchgeometry.utils import (
+ one_hot,
+ create_meshgrid,
+ tensor_to_image,
+ image_to_tensor,
)
-
from torchgeometry.geometry import *
diff --git a/torchgeometry/losses/__init__.py b/torchgeometry/losses/__init__.py
index 42d53ba5c..2443c3188 100644
--- a/torchgeometry/losses/__init__.py
+++ b/torchgeometry/losses/__init__.py
@@ -1,7 +1,7 @@
-from .one_hot import one_hot
from .ssim import SSIM, ssim
from .dice import DiceLoss, dice_loss
from .tversky import TverskyLoss, tversky_loss
from .focal import FocalLoss, focal_loss
-from .depth_smooth import InverseDepthSmoothnessLoss
-from .depth_smooth import inverse_depth_smoothness_loss
+from .depth_smooth import (
+ InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
+)
diff --git a/torchgeometry/losses/dice.py b/torchgeometry/losses/dice.py
index 2684ef6c9..df8c9c742 100644
--- a/torchgeometry/losses/dice.py
+++ b/torchgeometry/losses/dice.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from .one_hot import one_hot
+from torchgeometry.utils import one_hot
# based on:
diff --git a/torchgeometry/losses/focal.py b/torchgeometry/losses/focal.py
index 41a0be828..19a522082 100644
--- a/torchgeometry/losses/focal.py
+++ b/torchgeometry/losses/focal.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from .one_hot import one_hot
+from torchgeometry.utils import one_hot
# based on:
diff --git a/torchgeometry/losses/ssim.py b/torchgeometry/losses/ssim.py
index ea4c10463..5ee006977 100644
--- a/torchgeometry/losses/ssim.py
+++ b/torchgeometry/losses/ssim.py
@@ -155,6 +155,6 @@ def ssim(
r"""Function that measures the Structural Similarity (SSIM) index between
each element in the input `x` and target `y`.
- See :class:`torchgeometry.losses.SSIM` for details.
+ See :class:`~torchgeometry.losses.SSIM` for details.
"""
return SSIM(window_size, reduction, max_val)(img1, img2)
diff --git a/torchgeometry/losses/tversky.py b/torchgeometry/losses/tversky.py
index b40a2e98b..f0de47618 100644
--- a/torchgeometry/losses/tversky.py
+++ b/torchgeometry/losses/tversky.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from .one_hot import one_hot
+from torchgeometry.utils import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
diff --git a/torchgeometry/utils.py b/torchgeometry/utils.py
deleted file mode 100644
index 3cfbaebaa..000000000
--- a/torchgeometry/utils.py
+++ /dev/null
@@ -1,119 +0,0 @@
-from typing import Optional
-
-import numpy as np
-import torch
-
-
-__all__ = [
- "tensor_to_image",
- "image_to_tensor",
- "create_meshgrid",
-]
-
-
-def create_meshgrid(
- height: int,
- width: int,
- normalized_coordinates: Optional[bool] = True):
- """Generates a coordinate grid for an image.
-
- When the flag `normalized_coordinates` is set to True, the grid is
- normalized to be in the range [-1,1] to be consistent with the pytorch
- function grid_sample.
- http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample
-
- Args:
- height (int): the image height (rows).
- width (int): the image width (cols).
- normalized_coordinates (Optional[bool]): wether to normalize
- coordinates in the range [-1, 1] in order to be consistent with the
- PyTorch function grid_sample.
-
- Return:
- torch.Tensor: returns a grid tensor with shape :math:`(1, H, W, 2)`.
- """
- # generate coordinates
- xs: Optional[torch.Tensor] = None
- ys: Optional[torch.Tensor] = None
- if normalized_coordinates:
- xs = torch.linspace(-1, 1, width)
- ys = torch.linspace(-1, 1, height)
- else:
- xs = torch.linspace(0, width - 1, width)
- ys = torch.linspace(0, height - 1, height)
- # generate grid by stacking coordinates
- base_grid: torch.Tensor = torch.stack(
- torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
- return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxWx2
-
-
-def image_to_tensor(image):
- """Converts a numpy image to a PyTorch tensor image.
-
- Args:
- image (numpy.ndarray): image of the form :math:`(H, W, C)`.
-
- Returns:
- torch.Tensor: tensor of the form :math:`(C, H, W)`.
-
- """
- if not type(image) == np.ndarray:
- raise TypeError("Input type is not a numpy.ndarray. Got {}".format(
- type(image)))
-
- if len(image.shape) > 3 or len(image.shape) < 2:
- raise ValueError("Input size must be a two or three dimensional array")
-
- tensor = torch.from_numpy(image)
-
- if len(tensor.shape) == 2:
- tensor = torch.unsqueeze(tensor, dim=-1)
-
- return tensor.permute(2, 0, 1).squeeze_() # CxHxW
-
-
-def tensor_to_image(tensor):
- """Converts a PyTorch tensor image to a numpy image. In case the tensor is
- in the GPU, it will be copied back to CPU.
-
- Args:
- tensor (torch.Tensor): image of the form :math:`(C, H, W)`.
-
- Returns:
- numpy.ndarray: image of the form :math:`(H, W, C)`.
-
- """
- if not torch.is_tensor(tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
-
- if len(tensor.shape) > 3 or len(tensor.shape) < 2:
- raise ValueError(
- "Input size must be a two or three dimensional tensor")
-
- input_shape = tensor.shape
- if len(input_shape) == 2:
- tensor = torch.unsqueeze(tensor, dim=0)
-
- tensor = tensor.permute(1, 2, 0)
-
- if len(input_shape) == 2:
- tensor = torch.squeeze(tensor, dim=-1)
-
- return tensor.contiguous().cpu().detach().numpy()
-
-
-# TODO: evaluate wether to include it to the main API.
-'''
-def create_pinhole(intrinsic, extrinsic, height, width):
- pinhole = torch.zeros(12)
- pinhole[0] = intrinsic[0, 0] # fx
- pinhole[1] = intrinsic[1, 1] # fy
- pinhole[2] = intrinsic[0, 2] # cx
- pinhole[3] = intrinsic[1, 2] # cy
- pinhole[4] = height
- pinhole[5] = width
- pinhole[6:9] = tgm.rotation_matrix_to_angle_axis(
- torch.tensor(extrinsic))
- pinhole[9:12] = torch.tensor(extrinsic[:, 3])
- return pinhole.view(1, -1)'''
diff --git a/torchgeometry/utils/__init__.py b/torchgeometry/utils/__init__.py
new file mode 100644
index 000000000..909f82355
--- /dev/null
+++ b/torchgeometry/utils/__init__.py
@@ -0,0 +1,12 @@
+from .one_hot import one_hot
+from .grid import create_meshgrid
+from .image import tensor_to_image, image_to_tensor
+
+import torchgeometry.utils.metrics as metrics
+
+__all__ = [
+ "one_hot",
+ "create_meshgrid",
+ "tensor_to_image",
+ "image_to_tensor",
+]
diff --git a/torchgeometry/utils/grid.py b/torchgeometry/utils/grid.py
new file mode 100644
index 000000000..c2c32c04d
--- /dev/null
+++ b/torchgeometry/utils/grid.py
@@ -0,0 +1,39 @@
+from typing import Optional
+
+import torch
+
+
+def create_meshgrid(
+ height: int,
+ width: int,
+ normalized_coordinates: Optional[bool] = True) -> torch.Tensor:
+ """Generates a coordinate grid for an image.
+
+ When the flag `normalized_coordinates` is set to True, the grid is
+ normalized to be in the range [-1,1] to be consistent with the pytorch
+ function grid_sample.
+ http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample
+
+ Args:
+ height (int): the image height (rows).
+ width (int): the image width (cols).
+ normalized_coordinates (Optional[bool]): wether to normalize
+ coordinates in the range [-1, 1] in order to be consistent with the
+ PyTorch function grid_sample.
+
+ Return:
+ torch.Tensor: returns a grid tensor with shape :math:`(1, H, W, 2)`.
+ """
+ # generate coordinates
+ xs: Optional[torch.Tensor] = None
+ ys: Optional[torch.Tensor] = None
+ if normalized_coordinates:
+ xs = torch.linspace(-1, 1, width)
+ ys = torch.linspace(-1, 1, height)
+ else:
+ xs = torch.linspace(0, width - 1, width)
+ ys = torch.linspace(0, height - 1, height)
+ # generate grid by stacking coordinates
+ base_grid: torch.Tensor = torch.stack(
+ torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
+ return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxWx2
diff --git a/torchgeometry/utils/image.py b/torchgeometry/utils/image.py
new file mode 100644
index 000000000..b6a09b758
--- /dev/null
+++ b/torchgeometry/utils/image.py
@@ -0,0 +1,60 @@
+from typing import Optional
+
+import numpy as np
+import torch
+
+
+def image_to_tensor(image: np.array) -> torch.Tensor:
+ """Converts a numpy image to a PyTorch tensor image.
+
+ Args:
+ image (numpy.ndarray): image of the form :math:`(H, W, C)`.
+
+ Returns:
+ torch.Tensor: tensor of the form :math:`(C, H, W)`.
+
+ """
+ if not type(image) == np.ndarray:
+ raise TypeError("Input type is not a numpy.ndarray. Got {}".format(
+ type(image)))
+
+ if len(image.shape) > 3 or len(image.shape) < 2:
+ raise ValueError("Input size must be a two or three dimensional array")
+
+ tensor: torch.Tensor = torch.from_numpy(image)
+
+ if len(tensor.shape) == 2:
+ tensor = torch.unsqueeze(tensor, dim=-1)
+
+ return tensor.permute(2, 0, 1).squeeze_() # CxHxW
+
+
+def tensor_to_image(tensor: torch.Tensor) -> np.array:
+ """Converts a PyTorch tensor image to a numpy image. In case the tensor is
+ in the GPU, it will be copied back to CPU.
+
+ Args:
+ tensor (torch.Tensor): image of the form :math:`(C, H, W)`.
+
+ Returns:
+ numpy.ndarray: image of the form :math:`(H, W, C)`.
+
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(tensor)))
+
+ if len(tensor.shape) > 3 or len(tensor.shape) < 2:
+ raise ValueError(
+ "Input size must be a two or three dimensional tensor")
+
+ input_shape = tensor.shape
+ if len(input_shape) == 2:
+ tensor = torch.unsqueeze(tensor, dim=0)
+
+ tensor = tensor.permute(1, 2, 0)
+
+ if len(input_shape) == 2:
+ tensor = torch.squeeze(tensor, dim=-1)
+
+ return tensor.contiguous().cpu().detach().numpy()
diff --git a/torchgeometry/metrics/__init__.py b/torchgeometry/utils/metrics/__init__.py
similarity index 58%
rename from torchgeometry/metrics/__init__.py
rename to torchgeometry/utils/metrics/__init__.py
index c4bbe4727..c8c223086 100644
--- a/torchgeometry/metrics/__init__.py
+++ b/torchgeometry/utils/metrics/__init__.py
@@ -1,2 +1,7 @@
from .confusion_matrix import confusion_matrix
from .mean_iou import mean_iou
+
+__all__ = [
+ "confusion_matrix",
+ "mean_iou",
+]
diff --git a/torchgeometry/metrics/confusion_matrix.py b/torchgeometry/utils/metrics/confusion_matrix.py
similarity index 100%
rename from torchgeometry/metrics/confusion_matrix.py
rename to torchgeometry/utils/metrics/confusion_matrix.py
diff --git a/torchgeometry/metrics/mean_iou.py b/torchgeometry/utils/metrics/mean_iou.py
similarity index 97%
rename from torchgeometry/metrics/mean_iou.py
rename to torchgeometry/utils/metrics/mean_iou.py
index 131961287..54f26cd43 100644
--- a/torchgeometry/metrics/mean_iou.py
+++ b/torchgeometry/utils/metrics/mean_iou.py
@@ -1,7 +1,7 @@
from typing import Optional
import torch
-from torchgeometry.metrics import confusion_matrix
+from torchgeometry.utils.metrics import confusion_matrix
def mean_iou(
diff --git a/torchgeometry/losses/one_hot.py b/torchgeometry/utils/one_hot.py
similarity index 100%
rename from torchgeometry/losses/one_hot.py
rename to torchgeometry/utils/one_hot.py