π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add tensor_to_image, image_to_tensor
edgarribaf17de571cbe3
diff --git a/test/test_utils.py b/test/test_utils.pynew file mode 100644index 000000000..878de3977--- /dev/null+++ b/test/test_utils.py@@ -0,0 +1,26 @@+import unittest+import numpy as np++import torch+import torchgeometry as dgm+++class Tester(unittest.TestCase):++ def test_tensor_to_image(self):+ tensor = torch.ones(3, 4, 4)+ image = dgm.utils.tensor_to_image(tensor)++ self.assertTrue(image.shape == (4, 4, 3))+ self.assertIsInstance(image, np.ndarray)++ def test_image_to_tensor(self):+ image = np.ones((4, 4, 3))+ tensor = dgm.utils.image_to_tensor(image)++ self.assertTrue(tensor.shape == (3, 4, 4))+ self.assertIsInstance(tensor, torch.Tensor)+++if __name__ == '__main__':+ unittest.main()diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.pyindex c6c3a6bc7..bf8158500 100644--- a/torchgeometry/__init__.py+++ b/torchgeometry/__init__.py@@ -1,5 +1,7 @@--__version__ = '0.0.1' # the current version of the lib-from .functional import *from .homography_warper import HomographyWarper++from torchgeometry import utils+++__version__ = '0.0.1' # the current version of the libdiff --git a/torchgeometry/utils/__init__.py b/torchgeometry/utils/__init__.pynew file mode 100644index 000000000..cccce87ac--- /dev/null+++ b/torchgeometry/utils/__init__.py@@ -0,0 +1,6 @@+from .functional import tensor_to_image, image_to_tensor++__all__ = [+ 'tensor_to_image',+ 'image_to_tensor',+]diff --git a/torchgeometry/utils/functional.py b/torchgeometry/utils/functional.pynew file mode 100644index 000000000..352d4c0e3--- /dev/null+++ b/torchgeometry/utils/functional.py@@ -0,0 +1,22 @@+import torch+++def image_to_tensor(image):+ """Converts a numpy image to a torch.Tensor image.+ """+ # TODO: add asserts and type checkings+ tensor = torch.from_numpy(image)+ if len(tensor.shape) == 2:+ tensor = torch.unsqueeze(tensor, dim=0)+ return tensor.permute(2, 0, 1) # CxHxW+++def tensor_to_image(tensor):+ """Converts a torch.Tensor image to a numpy image. In case the tensor is+ in the GPU, it will be copied back to CPU.+ """+ # TODO: add asserts and type checkings+ if len(tensor.shape) == 2:+ tensor = torch.unsqueeze(tensor, dim=0)+ tensor = tensor.permute(1, 2, 0).contiguous()+ return torch.squeeze(tensor).cpu().numpy()