dkatz2391 commited on
Commit
2f5e0ac
·
verified ·
1 Parent(s): 0594ad4

Upload 104 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. utils3d/.gitattributes +2 -0
  2. utils3d/.gitignore +118 -0
  3. utils3d/LICENSE +21 -0
  4. utils3d/README.md +46 -0
  5. utils3d/gen_unified_interface.py +106 -0
  6. utils3d/pyproject.toml +35 -0
  7. utils3d/test/io_/write_ply.py +22 -0
  8. utils3d/test/numpy_/mesh/compute_face_angle.py +46 -0
  9. utils3d/test/numpy_/mesh/compute_face_normal.py +41 -0
  10. utils3d/test/numpy_/mesh/compute_vertex_normal.py +43 -0
  11. utils3d/test/numpy_/mesh/compute_vertex_normal_weighted.py +45 -0
  12. utils3d/test/numpy_/mesh/merge_duplicate_vertices.py +39 -0
  13. utils3d/test/numpy_/mesh/remove_corrupted_faces.py +30 -0
  14. utils3d/test/numpy_/mesh/triangulate.py +33 -0
  15. utils3d/test/numpy_/rasterization/warp_image_by_depth.py +30 -0
  16. utils3d/test/numpy_/transforms/crop_intrinsic.py +53 -0
  17. utils3d/test/numpy_/transforms/extrinsic_look_at.py +39 -0
  18. utils3d/test/numpy_/transforms/extrinsic_to_view.py +32 -0
  19. utils3d/test/numpy_/transforms/intrinsic.py +37 -0
  20. utils3d/test/numpy_/transforms/intrinsic_from_fov.py +38 -0
  21. utils3d/test/numpy_/transforms/intrinsic_from_fov_xy.py +36 -0
  22. utils3d/test/numpy_/transforms/intrinsic_to_perspective.py +38 -0
  23. utils3d/test/numpy_/transforms/linearize_depth.py +34 -0
  24. utils3d/test/numpy_/transforms/normalize_intrinsic.py +32 -0
  25. utils3d/test/numpy_/transforms/perspective.py +36 -0
  26. utils3d/test/numpy_/transforms/perspective_from_fov.py +40 -0
  27. utils3d/test/numpy_/transforms/perspective_from_fov_xy.py +37 -0
  28. utils3d/test/numpy_/transforms/perspective_to_intrinsic.py +36 -0
  29. utils3d/test/numpy_/transforms/pixel_to_ndc.py +32 -0
  30. utils3d/test/numpy_/transforms/pixel_to_uv.py +32 -0
  31. utils3d/test/numpy_/transforms/project_cv.py +57 -0
  32. utils3d/test/numpy_/transforms/project_depth.py +32 -0
  33. utils3d/test/numpy_/transforms/project_gl.py +58 -0
  34. utils3d/test/numpy_/transforms/project_gl_cv.py +52 -0
  35. utils3d/test/numpy_/transforms/unproject_cv.py +49 -0
  36. utils3d/test/numpy_/transforms/unproject_gl.py +50 -0
  37. utils3d/test/numpy_/transforms/view_look_at.py +39 -0
  38. utils3d/test/numpy_/transforms/view_to_extrinsic.py +32 -0
  39. utils3d/test/numpy_/utils/image_mesh.py +32 -0
  40. utils3d/test/rasterization_/gl/basic.py +70 -0
  41. utils3d/test/rasterization_/gl/rasterize_uv.py +42 -0
  42. utils3d/test/test.py +50 -0
  43. utils3d/test/torch_/mesh/compute_face_angle.py +39 -0
  44. utils3d/test/torch_/mesh/compute_face_normal.py +39 -0
  45. utils3d/test/torch_/mesh/compute_vertex_normal.py +39 -0
  46. utils3d/test/torch_/mesh/compute_vertex_normal_weighted.py +39 -0
  47. utils3d/test/torch_/mesh/merge_duplicate_vertices.py +44 -0
  48. utils3d/test/torch_/mesh/remove_corrupted_faces.py +33 -0
  49. utils3d/test/torch_/mesh/triangulate.py +36 -0
  50. utils3d/test/torch_/rasterization/warp_image_by_depth.py +30 -0
utils3d/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
utils3d/.gitignore ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+ MANIFEST
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .nox/
42
+ .coverage
43
+ .coverage.*
44
+ .cache
45
+ nosetests.xml
46
+ coverage.xml
47
+ *.cover
48
+ .hypothesis/
49
+ .pytest_cache/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Django stuff:
56
+ *.log
57
+ local_settings.py
58
+ db.sqlite3
59
+
60
+ # Flask stuff:
61
+ instance/
62
+ .webassets-cache
63
+
64
+ # Scrapy stuff:
65
+ .scrapy
66
+
67
+ # Sphinx documentation
68
+ docs/_build/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+
76
+ # IPython
77
+ profile_default/
78
+ ipython_config.py
79
+
80
+ # pyenv
81
+ .python-version
82
+
83
+ # celery beat schedule file
84
+ celerybeat-schedule
85
+
86
+ # SageMath parsed files
87
+ *.sage.py
88
+
89
+ # Environments
90
+ .env
91
+ .venv
92
+ env/
93
+ venv/
94
+ ENV/
95
+ env.bak/
96
+ venv.bak/
97
+
98
+ # Spyder project settings
99
+ .spyderproject
100
+ .spyproject
101
+
102
+ # Rope project settings
103
+ .ropeproject
104
+
105
+ # mkdocs documentation
106
+ /site
107
+
108
+ # mypy
109
+ .mypy_cache/
110
+ .dmypy.json
111
+ dmypy.json
112
+
113
+ # Pyre type checker
114
+ .pyre/
115
+
116
+ .vscode
117
+ test/results_to_check
118
+ timetest.py
utils3d/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 EasternJournalist
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
utils3d/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils3d
2
+ Easy 3D python utilities for computer vision and graphics researchers.
3
+
4
+ Supports:
5
+ * Transformation between OpenCV and OpenGL coordinate systems, **no more confusion**
6
+ * Easy rasterization, **no worries about OpenGL objects and buffers**
7
+ * Some mesh processing utilities, **all vectorized for effciency; some differentiable**
8
+ * Projection, unprojection, depth-based image warping, flow-based image warping...
9
+ * Easy Reading and writing .obj, .ply files
10
+ * Reading and writing Colmap format camera parameters
11
+ * NeRF/MipNeRF utilities
12
+
13
+ For most functions, there are both numpy (indifferentiable) and pytorch implementations (differentiable).
14
+
15
+ Pytorch is not required for using this package, but if you want to use the differentiable functions, you will need to install pytorch (and nvdiffrast if you want to use the pytorch rasterization functions).
16
+
17
+ ## Install
18
+
19
+ Install by git
20
+
21
+ ```bash
22
+ pip install git+https://github.com/EasternJournalist/utils3d.git#egg=utils3d
23
+ ```
24
+
25
+ or clone the repo and install with `-e` option for convenient updating and modifying.
26
+
27
+ ```bash
28
+ git clone https://github.com/EasternJournalist/utils3d.git
29
+ pip install -e ./utils3d
30
+ ```
31
+
32
+ ## Topics (TODO)
33
+
34
+ ### Camera
35
+
36
+ ### Rotations
37
+
38
+ ### Mesh
39
+
40
+ ### Rendering
41
+
42
+ ### Projection
43
+
44
+ ### Image warping
45
+
46
+ ### NeRF
utils3d/gen_unified_interface.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import textwrap
3
+ import re
4
+ import itertools
5
+ import numbers
6
+ import importlib
7
+ import sys
8
+ import functools
9
+ from pathlib import Path
10
+
11
+ from utils3d._helpers import suppress_traceback
12
+
13
+
14
+ def _contains_tensor(obj):
15
+ if isinstance(obj, (list, tuple)):
16
+ return any(_contains_tensor(item) for item in obj)
17
+ elif isinstance(obj, dict):
18
+ return any(_contains_tensor(value) for value in obj.values())
19
+ else:
20
+ import torch
21
+ return isinstance(obj, torch.Tensor)
22
+
23
+ @suppress_traceback
24
+ def _call_based_on_args(fname, args, kwargs):
25
+ if 'torch' in sys.modules:
26
+ if any(_contains_tensor(arg) for arg in args) or any(_contains_tensor(v) for v in kwargs.values()):
27
+ fn = getattr(utils3d.torch, fname, None)
28
+ if fn is None:
29
+ raise NotImplementedError(f"Function {fname} has no torch implementation.")
30
+ return fn(*args, **kwargs)
31
+ fn = getattr(utils3d.numpy, fname, None)
32
+ if fn is None:
33
+ raise NotImplementedError(f"Function {fname} has no numpy implementation.")
34
+ return fn(*args, **kwargs)
35
+
36
+
37
+ def extract_signature(fn):
38
+ signature = inspect.signature(fn)
39
+
40
+ signature_str = str(signature)
41
+
42
+ signature_str = re.sub(r"<class '.*'>", lambda m: m.group(0).split('\'')[1], signature_str)
43
+ signature_str = re.sub(r"(?<!\.)numpy\.", "numpy_.", signature_str)
44
+ signature_str = re.sub(r"(?<!\.)torch\.", "torch_.", signature_str)
45
+
46
+ return signature_str
47
+
48
+
49
+
50
+ if __name__ == "__main__":
51
+ import utils3d.numpy, utils3d.torch
52
+ numpy_impl = utils3d.numpy
53
+ torch_impl = utils3d.torch
54
+ numpy_funcs = {name: getattr(numpy_impl, name) for name in numpy_impl.__all__}
55
+ torch_funcs = {name: getattr(torch_impl, name) for name in torch_impl.__all__}
56
+
57
+ all = {**numpy_funcs, **torch_funcs}
58
+
59
+ Path("utils3d/_unified").mkdir(exist_ok=True)
60
+
61
+ with open("utils3d/_unified/__init__.pyi", "w", encoding="utf-8") as f:
62
+ f.write(inspect.cleandoc(
63
+ f"""
64
+ # Auto-generated interface file
65
+ from typing import List, Tuple, Dict, Union, Optional, Any, overload, Literal, Callable
66
+ import numpy as numpy_
67
+ import torch as torch_
68
+ import nvdiffrast.torch
69
+ import numbers
70
+ from . import numpy, torch
71
+ import utils3d.numpy, utils3d.torch
72
+ """
73
+ ))
74
+ f.write("\n\n")
75
+ f.write(f"__all__ = [{', \n'.join('\"' + s + '\"' for s in all.keys())}]\n\n")
76
+
77
+ for fname, fn in itertools.chain(numpy_funcs.items(), torch_funcs.items()):
78
+ sig, doc = extract_signature(fn), inspect.getdoc(fn)
79
+
80
+ f.write(f"@overload\n")
81
+ f.write(f"def {fname}{sig}:\n")
82
+ f.write(f" \"\"\"{doc}\"\"\"\n" if doc else "")
83
+ f.write(f" {fn.__module__}.{fn.__qualname__}\n\n")
84
+
85
+ with open("utils3d/_unified/__init__.py", "w", encoding="utf-8") as f:
86
+ f.write(inspect.cleandoc(
87
+ f"""
88
+ # Auto-generated implementation redirecting to numpy/torch implementations
89
+ import sys
90
+ from typing import TYPE_CHECKING
91
+ import utils3d
92
+ from .._helpers import suppress_traceback
93
+ """
94
+ ))
95
+ f.write("\n\n")
96
+ f.write(f"__all__ = [{', \n'.join('\"' + s + '\"' for s in all.keys())}]\n\n")
97
+ f.write(inspect.getsource(_contains_tensor) + "\n\n")
98
+ f.write(inspect.getsource(_call_based_on_args) + "\n\n")
99
+
100
+ for fname in {**numpy_funcs, **torch_funcs}:
101
+ f.write(f'@suppress_traceback\n')
102
+ f.write(f"def {fname}(*args, **kwargs):\n")
103
+ f.write(f" if TYPE_CHECKING: # redirected to:\n")
104
+ f.write(f" {'utils3d.numpy.' + fname if fname in numpy_funcs else 'None'}, {'utils3d.torch.'+ fname if fname in torch_funcs else 'None'}\n")
105
+ f.write(f" return _call_based_on_args('{fname}', args, kwargs)\n\n")
106
+
utils3d/pyproject.toml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "utils3d"
7
+ version = "0.0.2"
8
+ description = "A small package for 3D graphics"
9
+ readme = "README.md"
10
+ authors = [
11
+ {name = "EasternJournalist", email = "wangrc2081cs@mail.ustc.edu.cn"}
12
+ ]
13
+ license = {text = "MIT"}
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent"
18
+ ]
19
+ dependencies = [
20
+ "moderngl",
21
+ "numpy",
22
+ "plyfile",
23
+ "scipy"
24
+ ]
25
+ requires-python = ">=3.7"
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/EasternJournalist/utils3d"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["."]
32
+ include = ["utils3d*"]
33
+
34
+ [tool.setuptools.package-data]
35
+ "utils3d.numpy.shaders" = ["*"]
utils3d/test/io_/write_ply.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ image_uv, image_mesh = utils3d.numpy.utils.image_mesh(128, 128)
9
+ image_mesh = image_mesh.reshape(-1, 4)
10
+ depth = np.ones((128, 128), dtype=float) * 2
11
+ depth[32:96, 32:96] = 1
12
+ depth = depth.reshape(-1)
13
+ intrinsics = utils3d.numpy.transforms.intrinsics_from_fov(1.0, 128, 128)
14
+ intrinsics = utils3d.numpy.transforms.normalize_intrinsics(intrinsics, 128, 128)
15
+ extrinsics = utils3d.numpy.transforms.extrinsics_look_at([0, 0, 1], [0, 0, 0], [0, 1, 0])
16
+ pts = utils3d.numpy.transforms.unproject_cv(image_uv, depth, extrinsics, intrinsics)
17
+ pts = pts.reshape(-1, 3)
18
+ image_mesh = utils3d.numpy.mesh.triangulate(image_mesh, vertices=pts)
19
+ utils3d.io.write_ply(os.path.join(os.path.dirname(__file__), '..', 'results_to_check', 'write_ply.ply'), pts, image_mesh)
20
+
21
+ if __name__ == '__main__':
22
+ run()
utils3d/test/numpy_/mesh/compute_face_angle.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
12
+ faces = np.array([[0, 1, 2]])
13
+ expected = np.array([[np.pi/2, np.pi/4, np.pi/4]])
14
+ else:
15
+ dim = np.random.randint(4)
16
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
17
+ N = np.random.randint(100, 1000)
18
+ vertices = np.random.rand(*spatial, N, 3)
19
+ L = np.random.randint(1, 1000)
20
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
21
+ faces[..., 1] = (faces[..., 0] + 1) % N
22
+ faces[..., 2] = (faces[..., 0] + 2) % N
23
+
24
+ faces_ = faces.reshape(-1, L, 3)
25
+ vertices_ = vertices.reshape(-1, N, 3)
26
+ N = vertices_.shape[0]
27
+ expected = np.zeros((N, L, 3), dtype=float)
28
+ for i in range(3):
29
+ edge0 = vertices_[np.arange(N)[:, None], faces_[..., (i+1)%3]] - vertices_[np.arange(N)[:, None], faces_[..., i]]
30
+ edge1 = vertices_[np.arange(N)[:, None], faces_[..., (i+2)%3]] - vertices_[np.arange(N)[:, None], faces_[..., i]]
31
+ expected[..., i] = np.arccos(np.sum(
32
+ edge0 / np.linalg.norm(edge0, axis=-1, keepdims=True) * \
33
+ edge1 / np.linalg.norm(edge1, axis=-1, keepdims=True),
34
+ axis=-1
35
+ ))
36
+ expected = expected.reshape(*spatial, L, 3)
37
+
38
+ actual = utils3d.numpy.compute_face_angle(vertices, faces)
39
+
40
+ assert np.allclose(expected, actual), '\n' + \
41
+ 'Input:\n' + \
42
+ f'{faces}\n' + \
43
+ 'Actual:\n' + \
44
+ f'{actual}\n' + \
45
+ 'Expected:\n' + \
46
+ f'{expected}'
utils3d/test/numpy_/mesh/compute_face_normal.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
12
+ faces = np.array([[0, 1, 2]])
13
+ expected = np.array([[0, 0, 1]])
14
+ else:
15
+ dim = np.random.randint(4)
16
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
17
+ N = np.random.randint(100, 1000)
18
+ vertices = np.random.rand(*spatial, N, 3)
19
+ L = np.random.randint(1, 1000)
20
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
21
+ faces[..., 1] = (faces[..., 0] + 1) % N
22
+ faces[..., 2] = (faces[..., 0] + 2) % N
23
+
24
+ faces_ = faces.reshape(-1, L, 3)
25
+ vertices_ = vertices.reshape(-1, N, 3)
26
+ N = vertices_.shape[0]
27
+ expected = np.cross(
28
+ vertices_[np.arange(N)[:, None], faces_[..., 1]] - vertices_[np.arange(N)[:, None], faces_[..., 0]],
29
+ vertices_[np.arange(N)[:, None], faces_[..., 2]] - vertices_[np.arange(N)[:, None], faces_[..., 0]]
30
+ ).reshape(*spatial, L, 3)
31
+ expected = np.nan_to_num(expected / np.linalg.norm(expected, axis=-1, keepdims=True))
32
+
33
+ actual = utils3d.numpy.compute_face_normal(vertices, faces)
34
+
35
+ assert np.allclose(expected, actual), '\n' + \
36
+ 'Input:\n' + \
37
+ f'{faces}\n' + \
38
+ 'Actual:\n' + \
39
+ f'{actual}\n' + \
40
+ 'Expected:\n' + \
41
+ f'{expected}'
utils3d/test/numpy_/mesh/compute_vertex_normal.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ from trimesh import geometry
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+ face_normals = utils3d.numpy.compute_face_normal(vertices, faces)
25
+
26
+ faces_ = faces.reshape(-1, L, 3)
27
+ face_normals = face_normals.reshape(-1, L, 3)
28
+ vertices_normals = []
29
+ for face, face_normal in zip(faces_, face_normals):
30
+ vertices_normals.append(
31
+ geometry.mean_vertex_normals(N, face, face_normal)
32
+ )
33
+ expected = np.array(vertices_normals).reshape(*spatial, N, 3)
34
+
35
+ actual = utils3d.numpy.compute_vertex_normal(vertices, faces)
36
+
37
+ assert np.allclose(expected, actual), '\n' + \
38
+ 'Input:\n' + \
39
+ f'{faces}\n' + \
40
+ 'Actual:\n' + \
41
+ f'{actual}\n' + \
42
+ 'Expected:\n' + \
43
+ f'{expected}'
utils3d/test/numpy_/mesh/compute_vertex_normal_weighted.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ from trimesh import geometry
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+ face_normals = utils3d.numpy.compute_face_normal(vertices, faces)
25
+ face_angles = utils3d.numpy.compute_face_angle(vertices, faces)
26
+
27
+ faces_ = faces.reshape(-1, L, 3)
28
+ face_normals = face_normals.reshape(-1, L, 3)
29
+ face_angles = face_angles.reshape(-1, L, 3)
30
+ vertices_normals = []
31
+ for face, face_normal, face_angle in zip(faces_, face_normals, face_angles):
32
+ vertices_normals.append(
33
+ geometry.weighted_vertex_normals(N, face, face_normal, face_angle)
34
+ )
35
+ expected = np.array(vertices_normals).reshape(*spatial, N, 3)
36
+
37
+ actual = utils3d.numpy.compute_vertex_normal_weighted(vertices, faces)
38
+
39
+ assert np.allclose(expected, actual), '\n' + \
40
+ 'Input:\n' + \
41
+ f'{faces}\n' + \
42
+ 'Actual:\n' + \
43
+ f'{actual}\n' + \
44
+ 'Expected:\n' + \
45
+ f'{expected}'
utils3d/test/numpy_/mesh/merge_duplicate_vertices.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=float)
12
+ faces = np.array([[0, 1, 2]])
13
+ expected_vertices = np.array([[0, 0, 0], [1, 0, 0]])
14
+ expected_faces = np.array([[0, 1, 1]])
15
+ expected = expected_vertices[expected_faces]
16
+ else:
17
+ N = np.random.randint(100, 1000)
18
+ vertices = np.random.rand(N, 3)
19
+ L = np.random.randint(1, 1000)
20
+ faces = np.random.randint(0, N, size=(L, 3))
21
+ faces[..., 1] = (faces[..., 0] + 1) % N
22
+ faces[..., 2] = (faces[..., 0] + 2) % N
23
+ vertices[-(N//2):] = vertices[:N//2]
24
+
25
+ expected_vertices = vertices[:-(N//2)].copy()
26
+ expected_faces = faces.copy()
27
+ expected_faces[expected_faces >= N - N//2] -= N - N//2
28
+ expected = expected_vertices[expected_faces]
29
+
30
+ actual_vertices, actual_faces = utils3d.numpy.merge_duplicate_vertices(vertices, faces)
31
+ actual = actual_vertices[actual_faces]
32
+
33
+ assert expected_vertices.shape == actual_vertices.shape and np.allclose(expected, actual), '\n' + \
34
+ 'Input:\n' + \
35
+ f'{faces}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
utils3d/test/numpy_/mesh/remove_corrupted_faces.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ faces = np.array([[0, 1, 2], [0, 2, 2], [0, 2, 3]])
11
+ expected = np.array([[0, 1, 2], [0, 2, 3]])
12
+ else:
13
+ L = np.random.randint(1, 1000)
14
+ N = np.random.randint(100, 1000)
15
+ faces = np.random.randint(0, N, size=(L, 3))
16
+ faces[..., 1] = (faces[..., 0] + 1) % N
17
+ faces[..., 2] = (faces[..., 0] + 2) % N
18
+ corrupted = np.random.randint(0, 2, size=L).astype(bool)
19
+ faces[corrupted, 1] = faces[corrupted, 0]
20
+ expected = faces[~corrupted]
21
+
22
+ actual = utils3d.numpy.remove_corrupted_faces(faces)
23
+
24
+ assert np.allclose(expected, actual), '\n' + \
25
+ 'Input:\n' + \
26
+ f'{faces}\n' + \
27
+ 'Actual:\n' + \
28
+ f'{actual}\n' + \
29
+ 'Expected:\n' + \
30
+ f'{expected}'
utils3d/test/numpy_/mesh/triangulate.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ L = 1
12
+ N = 5
13
+ faces = np.array([[0, 1, 2, 3, 4]])
14
+ expected = np.array([[0, 1, 2], [0, 2, 3], [0, 3, 4]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ L = np.random.randint(1, 1000)
19
+ N = np.random.randint(3, 10)
20
+ faces = np.random.randint(0, 10000, size=(*spatial, L, N))
21
+
22
+ loop_indices = [[0, i, i + 1] for i in range(1, N - 1)]
23
+ expected = faces[..., loop_indices].reshape((*spatial, L * (N - 2), 3))
24
+
25
+ actual = utils3d.numpy.triangulate(faces)
26
+
27
+ assert np.allclose(expected, actual), '\n' + \
28
+ 'Input:\n' + \
29
+ f'{faces}\n' + \
30
+ 'Actual:\n' + \
31
+ f'{actual}\n' + \
32
+ 'Expected:\n' + \
33
+ f'{expected}'
utils3d/test/numpy_/rasterization/warp_image_by_depth.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import imageio
7
+
8
+ def run():
9
+ depth = np.ones((128, 128), dtype=np.float32) * 2
10
+ depth[32:48, 32:48] = 1
11
+ intrinsics = utils3d.numpy.transforms.intrinsics(1.0, 1.0, 0.5, 0.5).astype(np.float32)
12
+ extrinsics_src = utils3d.numpy.transforms.extrinsics_look_at([0, 0, 1], [0, 0, 0], [0, 1, 0]).astype(np.float32)
13
+ extrinsics_tgt = utils3d.numpy.transforms.extrinsics_look_at([1, 0, 1], [0, 0, 0], [0, 1, 0]).astype(np.float32)
14
+ ctx = utils3d.numpy.rasterization.RastContext(
15
+ standalone=True,
16
+ backend='egl',
17
+ device_index=0,
18
+ )
19
+ uv, _ = utils3d.numpy.rasterization.warp_image_by_depth(
20
+ ctx,
21
+ depth,
22
+ extrinsics_src=extrinsics_src,
23
+ extrinsics_tgt=extrinsics_tgt,
24
+ intrinsics_src=intrinsics
25
+ )
26
+ uv = (np.concatenate([uv, np.zeros((128, 128, 1), dtype=np.float32)], axis=-1) * 255).astype(np.uint8)
27
+ imageio.imwrite(os.path.join(os.path.dirname(__file__), '..', '..', 'results_to_check', 'warp_image_uv.png'), uv)
28
+
29
+ if __name__ == '__main__':
30
+ run()
utils3d/test/numpy_/transforms/crop_intrinsic.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ else:
12
+ dim = np.random.randint(4)
13
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
14
+ fov = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
15
+ width = np.random.uniform(1, 10000, spatial)
16
+ height = np.random.uniform(1, 10000, spatial)
17
+ left = np.random.uniform(0, width, spatial)
18
+ top = np.random.uniform(0, height, spatial)
19
+ crop_width = np.random.uniform(0, width - left, spatial)
20
+ crop_height = np.random.uniform(0, height - top, spatial)
21
+
22
+ focal = np.maximum(width, height) / (2 * np.tan(fov / 2))
23
+ cx = width / 2 - left
24
+ cy = height / 2 - top
25
+ expected = np.zeros((*spatial, 3, 3))
26
+ expected[..., 0, 0] = focal
27
+ expected[..., 1, 1] = focal
28
+ expected[..., 0, 2] = cx
29
+ expected[..., 1, 2] = cy
30
+ expected[..., 2, 2] = 1
31
+ expected = utils3d.numpy.normalize_intrinsics(expected, crop_width, crop_height)
32
+
33
+ actual = utils3d.numpy.crop_intrinsics(
34
+ utils3d.numpy.normalize_intrinsics(
35
+ utils3d.numpy.intrinsics_from_fov(fov, width, height),
36
+ width, height
37
+ ),
38
+ width, height, left, top, crop_width, crop_height
39
+ )
40
+
41
+ assert np.allclose(expected, actual), '\n' + \
42
+ 'Input:\n' + \
43
+ f'\tfov: {fov}\n' + \
44
+ f'\twidth: {width}\n' + \
45
+ f'\theight: {height}\n' + \
46
+ f'\tleft: {left}\n' + \
47
+ f'\ttop: {top}\n' + \
48
+ f'\tcrop_width: {crop_width}\n' + \
49
+ f'\tcrop_height: {crop_height}\n' + \
50
+ 'Actual:\n' + \
51
+ f'{actual}\n' + \
52
+ 'Expected:\n' + \
53
+ f'{expected}'
utils3d/test/numpy_/transforms/extrinsic_look_at.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ eye = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
16
+ lookat = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
17
+ up = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
18
+
19
+ expected = []
20
+ for i in range(np.prod(spatial) if len(spatial) > 0 else 1):
21
+ expected.append(utils3d.numpy.view_to_extrinsics(np.array(glm.lookAt(
22
+ glm.vec3(eye.reshape([-1, 3])[i]),
23
+ glm.vec3(lookat.reshape([-1, 3])[i]),
24
+ glm.vec3(up.reshape([-1, 3])[i])
25
+ ))))
26
+ expected = np.concatenate(expected, axis=0).reshape([*spatial, 4, 4])
27
+
28
+ actual = utils3d.numpy.extrinsics_look_at(eye, lookat, up)
29
+
30
+ assert np.allclose(expected, actual, 1e-5, 1e-5), '\n' + \
31
+ 'Input:\n' + \
32
+ f'eye: {eye}\n' + \
33
+ f'lookat: {lookat}\n' + \
34
+ f'up: {up}\n' + \
35
+ 'Actual:\n' + \
36
+ f'{actual}\n' + \
37
+ 'Expected:\n' + \
38
+ f'{expected}'
39
+
utils3d/test/numpy_/transforms/extrinsic_to_view.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ eye = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
16
+ lookat = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
17
+ up = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
18
+
19
+ expected = utils3d.numpy.view_look_at(eye, lookat, up)
20
+
21
+ actual = utils3d.numpy.view_to_extrinsics(utils3d.numpy.extrinsics_look_at(eye, lookat, up))
22
+
23
+ assert np.allclose(expected, actual, 1e-5, 1e-5), '\n' + \
24
+ 'Input:\n' + \
25
+ f'eye: {eye}\n' + \
26
+ f'lookat: {lookat}\n' + \
27
+ f'up: {up}\n' + \
28
+ 'Actual:\n' + \
29
+ f'{actual}\n' + \
30
+ 'Expected:\n' + \
31
+ f'{expected}'
32
+
utils3d/test/numpy_/transforms/intrinsic.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ else:
12
+ dim = np.random.randint(4)
13
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
14
+ focal_x = np.random.uniform(1, 10000, spatial)
15
+ focal_y = np.random.uniform(1, 10000, spatial)
16
+ center_x = np.random.uniform(1, 10000, spatial)
17
+ center_y = np.random.uniform(1, 10000, spatial)
18
+
19
+ expected = np.zeros((*spatial, 3, 3))
20
+ expected[..., 0, 0] = focal_x
21
+ expected[..., 1, 1] = focal_y
22
+ expected[..., 0, 2] = center_x
23
+ expected[..., 1, 2] = center_y
24
+ expected[..., 2, 2] = 1
25
+
26
+ actual = utils3d.numpy.intrinsics(focal_x, focal_y, center_x, center_y)
27
+
28
+ assert np.allclose(expected, actual), '\n' + \
29
+ 'Input:\n' + \
30
+ f'\tfocal_x: {focal_x}\n' + \
31
+ f'\tfocal_y: {focal_y}\n' + \
32
+ f'\tcenter_x: {center_x}\n' + \
33
+ f'\tcenter_y: {center_y}\n' + \
34
+ 'Actual:\n' + \
35
+ f'{actual}\n' + \
36
+ 'Expected:\n' + \
37
+ f'{expected}'
utils3d/test/numpy_/transforms/intrinsic_from_fov.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ else:
12
+ dim = np.random.randint(4)
13
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
14
+ fov = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
15
+ width = np.random.uniform(1, 10000, spatial)
16
+ height = np.random.uniform(1, 10000, spatial)
17
+
18
+ focal = np.maximum(width, height) / (2 * np.tan(fov / 2))
19
+ cx = width / 2
20
+ cy = height / 2
21
+ expected = np.zeros((*spatial, 3, 3))
22
+ expected[..., 0, 0] = focal
23
+ expected[..., 1, 1] = focal
24
+ expected[..., 0, 2] = cx
25
+ expected[..., 1, 2] = cy
26
+ expected[..., 2, 2] = 1
27
+
28
+ actual = utils3d.numpy.intrinsics_from_fov(fov, width, height)
29
+
30
+ assert np.allclose(expected, actual), '\n' + \
31
+ 'Input:\n' + \
32
+ f'\tfov: {fov}\n' + \
33
+ f'\twidth: {width}\n' + \
34
+ f'\theight: {height}\n' + \
35
+ 'Actual:\n' + \
36
+ f'{actual}\n' + \
37
+ 'Expected:\n' + \
38
+ f'{expected}'
utils3d/test/numpy_/transforms/intrinsic_from_fov_xy.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ else:
12
+ dim = np.random.randint(4)
13
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
14
+ fov_x = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
15
+ fov_y = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+
17
+ focal_x = 0.5 / np.tan(fov_x / 2)
18
+ focal_y = 0.5 / np.tan(fov_y / 2)
19
+ cx = cy = 0.5
20
+ expected = np.zeros((*spatial, 3, 3))
21
+ expected[..., 0, 0] = focal_x
22
+ expected[..., 1, 1] = focal_y
23
+ expected[..., 0, 2] = cx
24
+ expected[..., 1, 2] = cy
25
+ expected[..., 2, 2] = 1
26
+
27
+ actual = utils3d.numpy.intrinsics_from_fov_xy(fov_x, fov_y)
28
+
29
+ assert np.allclose(expected, actual), '\n' + \
30
+ 'Input:\n' + \
31
+ f'\tfov_x: {fov_x}\n' + \
32
+ f'\tfov_y: {fov_y}\n' + \
33
+ 'Actual:\n' + \
34
+ f'{actual}\n' + \
35
+ 'Expected:\n' + \
36
+ f'{expected}'
utils3d/test/numpy_/transforms/intrinsic_to_perspective.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ fov_x = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+ fov_y = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
17
+ near = np.random.uniform(0.1, 100, spatial)
18
+ far = np.random.uniform(near*2, 1000, spatial)
19
+
20
+ expected = utils3d.numpy.perspective_from_fov_xy(fov_x, fov_y, near, far)
21
+
22
+ actual = utils3d.numpy.intrinsics_to_perspective(
23
+ utils3d.numpy.intrinsics_from_fov_xy(fov_x, fov_y),
24
+ near,
25
+ far
26
+ )
27
+
28
+ assert np.allclose(expected, actual), '\n' + \
29
+ 'Input:\n' + \
30
+ f'\tfov_x: {fov_x}\n' + \
31
+ f'\tfov_y: {fov_y}\n' + \
32
+ f'\tnear: {near}\n' + \
33
+ f'\tfar: {far}\n' + \
34
+ 'Actual:\n' + \
35
+ f'{actual}\n' + \
36
+ 'Expected:\n' + \
37
+ f'{expected}'
38
+
utils3d/test/numpy_/transforms/linearize_depth.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ near = np.random.uniform(0.1, 100, spatial)
16
+ far = np.random.uniform(near*2, 1000, spatial)
17
+ depth = np.random.uniform(near, far, spatial)
18
+
19
+ expected = depth
20
+
21
+ actual = utils3d.numpy.depth_buffer_to_linear(
22
+ utils3d.numpy.project_depth(depth, near, far),
23
+ near, far
24
+ )
25
+
26
+ assert np.allclose(expected, actual), '\n' + \
27
+ 'Input:\n' + \
28
+ f'\tdepth: {depth}\n' + \
29
+ f'\tnear: {near}\n' + \
30
+ f'\tfar: {far}\n' + \
31
+ 'Actual:\n' + \
32
+ f'{actual}\n' + \
33
+ 'Expected:\n' + \
34
+ f'{expected}'
utils3d/test/numpy_/transforms/normalize_intrinsic.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ if i == 0:
10
+ spatial = []
11
+ else:
12
+ dim = np.random.randint(4)
13
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
14
+ fov = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
15
+ width = np.random.uniform(1, 10000, spatial)
16
+ height = np.random.uniform(1, 10000, spatial)
17
+ fov_x = np.where(width >= height, fov, 2 * np.arctan(np.tan(fov / 2) * width / height))
18
+ fov_y = np.where(width >= height, 2 * np.arctan(np.tan(fov / 2) * height / width), fov)
19
+
20
+ expected = utils3d.numpy.intrinsics_from_fov_xy(fov_x, fov_y)
21
+
22
+ actual = utils3d.numpy.normalize_intrinsics(utils3d.numpy.intrinsics_from_fov(fov, width, height), width, height)
23
+
24
+ assert np.allclose(expected, actual), '\n' + \
25
+ 'Input:\n' + \
26
+ f'\tfov: {fov}\n' + \
27
+ f'\twidth: {width}\n' + \
28
+ f'\theight: {height}\n' + \
29
+ 'Actual:\n' + \
30
+ f'{actual}\n' + \
31
+ 'Expected:\n' + \
32
+ f'{expected}'
utils3d/test/numpy_/transforms/perspective.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ fovy = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+ aspect = np.random.uniform(0.01, 100, spatial)
17
+ near = np.random.uniform(0.1, 100, spatial)
18
+ far = np.random.uniform(near*2, 1000, spatial)
19
+
20
+ expected = []
21
+ for i in range(np.prod(spatial) if len(spatial) > 0 else 1):
22
+ expected.append(glm.perspective(fovy.flat[i], aspect.flat[i], near.flat[i], far.flat[i]))
23
+ expected = np.concatenate(expected, axis=0).reshape(*spatial, 4, 4)
24
+
25
+ actual = utils3d.numpy.perspective(fovy, aspect, near, far)
26
+
27
+ assert np.allclose(expected, actual), '\n' + \
28
+ 'Input:\n' + \
29
+ f'\tfovy: {fovy}\n' + \
30
+ f'\taspect: {aspect}\n' + \
31
+ f'\tnear: {near}\n' + \
32
+ f'\tfar: {far}\n' + \
33
+ 'Actual:\n' + \
34
+ f'{actual}\n' + \
35
+ 'Expected:\n' + \
36
+ f'{expected}'
utils3d/test/numpy_/transforms/perspective_from_fov.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ fov = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+ width = np.random.uniform(1, 10000, spatial)
17
+ height = np.random.uniform(1, 10000, spatial)
18
+ near = np.random.uniform(0.1, 100, spatial)
19
+ far = np.random.uniform(near*2, 1000, spatial)
20
+
21
+ fov_y = 2 * np.arctan(np.tan(fov / 2) * height / np.maximum(width, height))
22
+ expected = []
23
+ for i in range(np.prod(spatial) if len(spatial) > 0 else 1):
24
+ expected.append(glm.perspective(fov_y.flat[i], width.flat[i] / height.flat[i], near.flat[i], far.flat[i]))
25
+ expected = np.concatenate(expected, axis=0).reshape(*spatial, 4, 4)
26
+
27
+ actual = utils3d.numpy.perspective_from_fov(fov, width, height, near, far)
28
+
29
+ assert np.allclose(expected, actual), '\n' + \
30
+ 'Input:\n' + \
31
+ f'\tfov: {fov}\n' + \
32
+ f'\twidth: {width}\n' + \
33
+ f'\theight: {height}\n' + \
34
+ f'\tnear: {near}\n' + \
35
+ f'\tfar: {far}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
40
+
utils3d/test/numpy_/transforms/perspective_from_fov_xy.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ fov_x = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+ fov_y = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
17
+ near = np.random.uniform(0.1, 100, spatial)
18
+ far = np.random.uniform(near*2, 1000, spatial)
19
+
20
+ aspect = np.tan(fov_x / 2) / np.tan(fov_y / 2)
21
+ expected = []
22
+ for i in range(np.prod(spatial) if len(spatial) > 0 else 1):
23
+ expected.append(glm.perspective(fov_y.flat[i], aspect.flat[i], near.flat[i], far.flat[i]))
24
+ expected = np.concatenate(expected, axis=0).reshape(*spatial, 4, 4)
25
+
26
+ actual = utils3d.numpy.perspective_from_fov_xy(fov_x, fov_y, near, far)
27
+
28
+ assert np.allclose(expected, actual), '\n' + \
29
+ 'Input:\n' + \
30
+ f'\tfov_x: {fov_x}\n' + \
31
+ f'\tfov_y: {fov_y}\n' + \
32
+ f'\tnear: {near}\n' + \
33
+ f'\tfar: {far}\n' + \
34
+ 'Actual:\n' + \
35
+ f'{actual}\n' + \
36
+ 'Expected:\n' + \
37
+ f'{expected}'
utils3d/test/numpy_/transforms/perspective_to_intrinsic.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ fov_x = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
16
+ fov_y = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
17
+ near = np.random.uniform(0.1, 100)
18
+ far = np.random.uniform(near*2, 1000)
19
+
20
+ expected = utils3d.numpy.intrinsics_from_fov_xy(fov_x, fov_y)
21
+
22
+ actual = utils3d.numpy.perspective_to_intrinsics(
23
+ utils3d.numpy.perspective_from_fov_xy(fov_x, fov_y, near, far)
24
+ )
25
+
26
+ assert np.allclose(expected, actual), '\n' + \
27
+ 'Input:\n' + \
28
+ f'\tfov_x: {fov_x}\n' + \
29
+ f'\tfov_y: {fov_y}\n' + \
30
+ f'\tnear: {near}\n' + \
31
+ f'\tfar: {far}\n' + \
32
+ 'Actual:\n' + \
33
+ f'{actual}\n' + \
34
+ 'Expected:\n' + \
35
+ f'{expected}'
36
+
utils3d/test/numpy_/transforms/pixel_to_ndc.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ H = np.random.randint(1, 1000)
10
+ W = np.random.randint(1, 1000)
11
+ x, y = np.meshgrid(np.arange(W), np.arange(H), indexing='xy')
12
+ pixel = np.stack([x, y], axis=-1)
13
+
14
+ expected = np.stack(
15
+ np.meshgrid(
16
+ np.linspace(-1 + 1 / W, 1 - 1 / W, W),
17
+ np.linspace(1 - 1 / H, -1 + 1 / H, H),
18
+ indexing='xy'
19
+ ),
20
+ axis=-1
21
+ )
22
+
23
+ actual = utils3d.numpy.pixel_to_ndc(pixel, W, H)
24
+
25
+ assert np.allclose(expected, actual), '\n' + \
26
+ 'Input:\n' + \
27
+ f'\tH: {H}\n' + \
28
+ f'\tW: {W}\n' + \
29
+ 'Actual:\n' + \
30
+ f'{actual}\n' + \
31
+ 'Expected:\n' + \
32
+ f'{expected}'
utils3d/test/numpy_/transforms/pixel_to_uv.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ for i in range(100):
9
+ H = np.random.randint(1, 1000)
10
+ W = np.random.randint(1, 1000)
11
+ x, y = np.meshgrid(np.arange(W), np.arange(H), indexing='xy')
12
+ pixel = np.stack([x, y], axis=-1)
13
+
14
+ expected = np.stack(
15
+ np.meshgrid(
16
+ np.linspace(0.5 / W, 1 - 0.5 / W, W),
17
+ np.linspace(0.5 / H, 1 - 0.5 / H, H),
18
+ indexing='xy'
19
+ ),
20
+ axis=-1
21
+ )
22
+
23
+ actual = utils3d.numpy.pixel_to_uv(pixel, W, H)
24
+
25
+ assert np.allclose(expected, actual), '\n' + \
26
+ 'Input:\n' + \
27
+ f'\tH: {H}\n' + \
28
+ f'\tW: {W}\n' + \
29
+ 'Actual:\n' + \
30
+ f'{actual}\n' + \
31
+ 'Expected:\n' + \
32
+ f'{expected}'
utils3d/test/numpy_/transforms/project_cv.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ N = 1
13
+ else:
14
+ dim = np.random.randint(4)
15
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
16
+ N = np.random.randint(1, 10)
17
+ focal_x = np.random.uniform(0, 10, spatial)
18
+ focal_y = np.random.uniform(0, 10, spatial)
19
+ center_x = np.random.uniform(0, 1, spatial)
20
+ center_y = np.random.uniform(0, 1, spatial)
21
+ eye = np.random.uniform(-10, 10, [*spatial, 3])
22
+ lookat = np.random.uniform(-10, 10, [*spatial, 3])
23
+ up = np.random.uniform(-10, 10, [*spatial, 3])
24
+ points = np.random.uniform(-10, 10, [*spatial, N, 3])
25
+
26
+ pts = points - eye[..., None, :]
27
+ z_axis = lookat - eye
28
+ x_axis = np.cross(-up, z_axis)
29
+ y_axis = np.cross(z_axis, x_axis)
30
+ x_axis = x_axis / np.linalg.norm(x_axis, axis=-1, keepdims=True)
31
+ y_axis = y_axis / np.linalg.norm(y_axis, axis=-1, keepdims=True)
32
+ z_axis = z_axis / np.linalg.norm(z_axis, axis=-1, keepdims=True)
33
+ z = (pts * z_axis[..., None, :]).sum(axis=-1)
34
+ x = (pts * x_axis[..., None, :]).sum(axis=-1)
35
+ y = (pts * y_axis[..., None, :]).sum(axis=-1)
36
+ x = (x / z * focal_x[..., None] + center_x[..., None])
37
+ y = (y / z * focal_y[..., None] + center_y[..., None])
38
+ expected = np.stack([x, y], axis=-1)
39
+
40
+ actual, _ = utils3d.numpy.transforms.project_cv(points,
41
+ utils3d.numpy.extrinsics_look_at(eye, lookat, up),
42
+ utils3d.numpy.intrinsics(focal_x, focal_y, center_x, center_y))
43
+
44
+ assert np.allclose(expected, actual), '\n' + \
45
+ 'Input:\n' + \
46
+ f'\tfocal_x: {focal_x}\n' + \
47
+ f'\tfocal_y: {focal_y}\n' + \
48
+ f'\tcenter_x: {center_x}\n' + \
49
+ f'\tcenter_y: {center_y}\n' + \
50
+ f'\teye: {eye}\n' + \
51
+ f'\tlookat: {lookat}\n' + \
52
+ f'\tup: {up}\n' + \
53
+ f'\tpoints: {points}\n' + \
54
+ 'Actual:\n' + \
55
+ f'{actual}\n' + \
56
+ 'Expected:\n' + \
57
+ f'{expected}'
utils3d/test/numpy_/transforms/project_depth.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ near = np.random.uniform(0.1, 100, spatial)
16
+ far = np.random.uniform(near*2, 1000, spatial)
17
+ depth = np.random.uniform(near, far, spatial)
18
+
19
+ proj = utils3d.numpy.perspective(1.0, 1.0, near, far)[..., 2, 2:4]
20
+ expected = ((proj[..., 0] * -depth + proj[..., 1]) / depth) * 0.5 + 0.5
21
+
22
+ actual = utils3d.numpy.project_depth(depth, near, far)
23
+
24
+ assert np.allclose(expected, actual), '\n' + \
25
+ 'Input:\n' + \
26
+ f'\tdepth: {depth}\n' + \
27
+ f'\tnear: {near}\n' + \
28
+ f'\tfar: {far}\n' + \
29
+ 'Actual:\n' + \
30
+ f'{actual}\n' + \
31
+ 'Expected:\n' + \
32
+ f'{expected}'
utils3d/test/numpy_/transforms/project_gl.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ N = 1
13
+ else:
14
+ dim = np.random.randint(4)
15
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
16
+ N = np.random.randint(1, 10)
17
+ fovy = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
18
+ aspect = np.random.uniform(0.01, 100, spatial)
19
+ near = np.random.uniform(0.1, 100, spatial)
20
+ far = np.random.uniform(near*2, 1000, spatial)
21
+ eye = np.random.uniform(-10, 10, [*spatial, 3])
22
+ lookat = np.random.uniform(-10, 10, [*spatial, 3])
23
+ up = np.random.uniform(-10, 10, [*spatial, 3])
24
+ points = np.random.uniform(-10, 10, [*spatial, N, 3])
25
+
26
+ pts = points - eye[..., None, :]
27
+ z_axis = (eye - lookat)
28
+ x_axis = np.cross(up, z_axis)
29
+ y_axis = np.cross(z_axis, x_axis)
30
+ x_axis = x_axis / np.linalg.norm(x_axis, axis=-1, keepdims=True)
31
+ y_axis = y_axis / np.linalg.norm(y_axis, axis=-1, keepdims=True)
32
+ z_axis = z_axis / np.linalg.norm(z_axis, axis=-1, keepdims=True)
33
+ z = (pts * z_axis[..., None, :]).sum(axis=-1)
34
+ x = (pts * x_axis[..., None, :]).sum(axis=-1)
35
+ y = (pts * y_axis[..., None, :]).sum(axis=-1)
36
+ x = (x / -z / np.tan(fovy[..., None] / 2) / aspect[..., None]) * 0.5 + 0.5
37
+ y = (y / -z / np.tan(fovy[..., None] / 2)) * 0.5 + 0.5
38
+ z = utils3d.numpy.project_depth(-z, near[..., None], far[..., None])
39
+ expected = np.stack([x, y, z], axis=-1)
40
+
41
+ actual, _ = utils3d.numpy.transforms.project_gl(points, None,
42
+ utils3d.numpy.view_look_at(eye, lookat, up),
43
+ utils3d.numpy.perspective(fovy, aspect, near, far))
44
+
45
+ assert np.allclose(expected, actual), '\n' + \
46
+ 'Input:\n' + \
47
+ f'\tfovy: {fovy}\n' + \
48
+ f'\taspect: {aspect}\n' + \
49
+ f'\tnear: {near}\n' + \
50
+ f'\tfar: {far}\n' + \
51
+ f'\teye: {eye}\n' + \
52
+ f'\tlookat: {lookat}\n' + \
53
+ f'\tup: {up}\n' + \
54
+ f'\tpoints: {points}\n' + \
55
+ 'Actual:\n' + \
56
+ f'{actual}\n' + \
57
+ 'Expected:\n' + \
58
+ f'{expected}'
utils3d/test/numpy_/transforms/project_gl_cv.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ N = 1
13
+ else:
14
+ dim = np.random.randint(4)
15
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
16
+ N = np.random.randint(1, 10)
17
+ fovy = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
18
+ aspect = np.random.uniform(0.01, 100, spatial)
19
+ focal_x = 0.5 / (np.tan(fovy / 2) * aspect)
20
+ focal_y = 0.5 / np.tan(fovy / 2)
21
+ near = np.random.uniform(0.1, 100, spatial)
22
+ far = np.random.uniform(near*2, 1000, spatial)
23
+ eye = np.random.uniform(-10, 10, [*spatial, 3])
24
+ lookat = np.random.uniform(-10, 10, [*spatial, 3])
25
+ up = np.random.uniform(-10, 10, [*spatial, 3])
26
+ points = np.random.uniform(-10, 10, [*spatial, N, 3])
27
+
28
+ gl = utils3d.numpy.transforms.project_gl(points, None,
29
+ utils3d.numpy.view_look_at(eye, lookat, up),
30
+ utils3d.numpy.perspective(fovy, aspect, near, far))
31
+ gl_uv = gl[0][..., :2]
32
+ gl_uv[..., 1] = 1 - gl_uv[..., 1]
33
+ gl_depth = gl[1]
34
+
35
+ cv = utils3d.numpy.transforms.project_cv(points,
36
+ utils3d.numpy.extrinsics_look_at(eye, lookat, up),
37
+ utils3d.numpy.intrinsics(focal_x, focal_y, 0.5, 0.5))
38
+ cv_uv = cv[0][..., :2]
39
+ cv_depth = cv[1]
40
+
41
+ assert np.allclose(gl_uv, cv_uv) and np.allclose(gl_depth, cv_depth), '\n' + \
42
+ 'Input:\n' + \
43
+ f'\tfovy: {fovy}\n' + \
44
+ f'\taspect: {aspect}\n' + \
45
+ f'\teye: {eye}\n' + \
46
+ f'\tlookat: {lookat}\n' + \
47
+ f'\tup: {up}\n' + \
48
+ f'\tpoints: {points}\n' + \
49
+ 'GL:\n' + \
50
+ f'{gl}\n' + \
51
+ 'CV:\n' + \
52
+ f'{cv}'
utils3d/test/numpy_/transforms/unproject_cv.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ N = 1
13
+ else:
14
+ dim = np.random.randint(4)
15
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
16
+ N = np.random.randint(1, 10)
17
+ focal_x = np.random.uniform(0, 10, spatial)
18
+ focal_y = np.random.uniform(0, 10, spatial)
19
+ center_x = np.random.uniform(0, 1, spatial)
20
+ center_y = np.random.uniform(0, 1, spatial)
21
+ eye = np.random.uniform(-10, 10, [*spatial, 3])
22
+ lookat = np.random.uniform(-10, 10, [*spatial, 3])
23
+ up = np.random.uniform(-10, 10, [*spatial, 3])
24
+ points = np.random.uniform(-10, 10, [*spatial, N, 3])
25
+
26
+ expected = points
27
+
28
+ actual = utils3d.numpy.transforms.unproject_cv(
29
+ *utils3d.numpy.transforms.project_cv(points,
30
+ utils3d.numpy.transforms.extrinsics_look_at(eye, lookat, up),
31
+ utils3d.numpy.transforms.intrinsics(focal_x, focal_y, center_x, center_y)),
32
+ utils3d.numpy.transforms.extrinsics_look_at(eye, lookat, up),
33
+ utils3d.numpy.transforms.intrinsics(focal_x, focal_y, center_x, center_y)
34
+ )
35
+
36
+ assert np.allclose(expected, actual), '\n' + \
37
+ 'Input:\n' + \
38
+ f'\tfocal_x: {focal_x}\n' + \
39
+ f'\tfocal_y: {focal_y}\n' + \
40
+ f'\tcenter_x: {center_x}\n' + \
41
+ f'\tcenter_y: {center_y}\n' + \
42
+ f'\teye: {eye}\n' + \
43
+ f'\tlookat: {lookat}\n' + \
44
+ f'\tup: {up}\n' + \
45
+ f'\tpoints: {points}\n' + \
46
+ 'Actual:\n' + \
47
+ f'{actual}\n' + \
48
+ 'Expected:\n' + \
49
+ f'{expected}'
utils3d/test/numpy_/transforms/unproject_gl.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ N = 1
13
+ else:
14
+ dim = np.random.randint(4)
15
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
16
+ N = np.random.randint(1, 10)
17
+ fovy = np.random.uniform(5 / 180 * np.pi, 175 / 180 * np.pi, spatial)
18
+ aspect = np.random.uniform(0.01, 100, spatial)
19
+ near = np.random.uniform(0.1, 100, spatial)
20
+ far = np.random.uniform(near*2, 1000, spatial)
21
+ eye = np.random.uniform(-10, 10, [*spatial, 3])
22
+ lookat = np.random.uniform(-10, 10, [*spatial, 3])
23
+ up = np.random.uniform(-10, 10, [*spatial, 3])
24
+ points = np.random.uniform(-10, 10, [*spatial, N, 3])
25
+
26
+ expected = points
27
+
28
+ actual = utils3d.numpy.transforms.unproject_gl(
29
+ utils3d.numpy.transforms.project_gl(points, None,
30
+ utils3d.numpy.view_look_at(eye, lookat, up),
31
+ utils3d.numpy.perspective(fovy, aspect, near, far))[0],
32
+ None,
33
+ utils3d.numpy.view_look_at(eye, lookat, up),
34
+ utils3d.numpy.perspective(fovy, aspect, near, far)
35
+ )
36
+
37
+ assert np.allclose(expected, actual), '\n' + \
38
+ 'Input:\n' + \
39
+ f'\tfovy: {fovy}\n' + \
40
+ f'\taspect: {aspect}\n' + \
41
+ f'\tnear: {near}\n' + \
42
+ f'\tfar: {far}\n' + \
43
+ f'\teye: {eye}\n' + \
44
+ f'\tlookat: {lookat}\n' + \
45
+ f'\tup: {up}\n' + \
46
+ f'\tpoints: {points}\n' + \
47
+ 'Actual:\n' + \
48
+ f'{actual}\n' + \
49
+ 'Expected:\n' + \
50
+ f'{expected}'
utils3d/test/numpy_/transforms/view_look_at.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ eye = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
16
+ lookat = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
17
+ up = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
18
+
19
+ expected = []
20
+ for i in range(np.prod(spatial) if len(spatial) > 0 else 1):
21
+ expected.append(np.array(glm.lookAt(
22
+ glm.vec3(eye.reshape([-1, 3])[i]),
23
+ glm.vec3(lookat.reshape([-1, 3])[i]),
24
+ glm.vec3(up.reshape([-1, 3])[i])
25
+ )))
26
+ expected = np.concatenate(expected, axis=0).reshape([*spatial, 4, 4])
27
+
28
+ actual = utils3d.numpy.view_look_at(eye, lookat, up)
29
+
30
+ assert np.allclose(expected, actual, 1e-5, 1e-5), '\n' + \
31
+ 'Input:\n' + \
32
+ f'eye: {eye}\n' + \
33
+ f'lookat: {lookat}\n' + \
34
+ f'up: {up}\n' + \
35
+ 'Actual:\n' + \
36
+ f'{actual}\n' + \
37
+ 'Expected:\n' + \
38
+ f'{expected}'
39
+
utils3d/test/numpy_/transforms/view_to_extrinsic.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import glm
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ else:
13
+ dim = np.random.randint(4)
14
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
15
+ eye = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
16
+ lookat = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
17
+ up = np.random.uniform(-10, 10, [*spatial, 3]).astype(np.float32)
18
+
19
+ expected = utils3d.numpy.extrinsics_look_at(eye, lookat, up)
20
+
21
+ actual = utils3d.numpy.view_to_extrinsics(utils3d.numpy.view_look_at(eye, lookat, up))
22
+
23
+ assert np.allclose(expected, actual, 1e-5, 1e-5), '\n' + \
24
+ 'Input:\n' + \
25
+ f'eye: {eye}\n' + \
26
+ f'lookat: {lookat}\n' + \
27
+ f'up: {up}\n' + \
28
+ 'Actual:\n' + \
29
+ f'{actual}\n' + \
30
+ 'Expected:\n' + \
31
+ f'{expected}'
32
+
utils3d/test/numpy_/utils/image_mesh.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+
7
+ def run():
8
+ args = [
9
+ {'W':2, 'H':2, 'backslash': np.array([False])},
10
+ {'W':2, 'H':2, 'backslash': np.array([True])},
11
+ {'H':2, 'W':3, 'backslash': np.array([True, False])},
12
+ ]
13
+
14
+ expected = [
15
+ np.array([[0, 2, 1], [1, 2, 3]]),
16
+ np.array([[0, 2, 3], [0, 3, 1]]),
17
+ np.array([[0, 3, 4], [0, 4, 1], [1, 4, 2], [2, 4, 5]]),
18
+ ]
19
+
20
+ for args, expected in zip(args, expected):
21
+ actual = utils3d.numpy.triangulate(
22
+ utils3d.numpy.image_mesh(args['H'], args['W'])[1],
23
+ backslash=args.get('backslash', None),
24
+ )
25
+
26
+ assert np.allclose(expected, actual), '\n' + \
27
+ 'Input:\n' + \
28
+ f'{args}\n' + \
29
+ 'Actual:\n' + \
30
+ f'{actual}\n' + \
31
+ 'Expected:\n' + \
32
+ f'{expected}'
utils3d/test/rasterization_/gl/basic.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import moderngl
6
+ import numpy as np
7
+ from PIL import Image
8
+ from pyrr import Matrix44
9
+
10
+ # -------------------
11
+ # CREATE CONTEXT HERE
12
+ # -------------------
13
+
14
+ import moderngl
15
+
16
+ def run():
17
+ ctx = moderngl.create_context(
18
+ standalone=True,
19
+ backend='egl',
20
+ # These are OPTIONAL if you want to load a specific version
21
+ libgl='libGL.so.1',
22
+ libegl='libEGL.so.1',
23
+ )
24
+
25
+ prog = ctx.program(vertex_shader="""
26
+ #version 330
27
+ uniform mat4 model;
28
+ in vec2 in_vert;
29
+ in vec3 in_color;
30
+ out vec3 color;
31
+ void main() {
32
+ gl_Position = model * vec4(in_vert, 0.0, 1.0);
33
+ color = in_color;
34
+ }
35
+ """,
36
+ fragment_shader="""
37
+ #version 330
38
+ in vec3 color;
39
+ out vec4 fragColor;
40
+ void main() {
41
+ fragColor = vec4(color, 1.0);
42
+ }
43
+ """)
44
+
45
+ vertices = np.array([
46
+ -0.6, -0.6,
47
+ 1.0, 0.0, 0.0,
48
+ 0.6, -0.6,
49
+ 0.0, 1.0, 0.0,
50
+ 0.0, 0.6,
51
+ 0.0, 0.0, 1.0,
52
+ ], dtype='f4')
53
+
54
+ vbo = ctx.buffer(vertices)
55
+ vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_color')
56
+ fbo = ctx.framebuffer(color_attachments=[ctx.texture((512, 512), 4)])
57
+
58
+ fbo.use()
59
+ ctx.clear()
60
+ prog['model'].write(Matrix44.from_eulers((0.0, 0.1, 0.0), dtype='f4'))
61
+ vao.render(moderngl.TRIANGLES)
62
+
63
+ data = fbo.read(components=3)
64
+ image = Image.frombytes('RGB', fbo.size, data)
65
+ image = image.transpose(Image.FLIP_TOP_BOTTOM)
66
+ image.save(os.path.join(os.path.dirname(__file__), '..', '..', 'results_to_check', 'output.png'))
67
+
68
+
69
+ if __name__ == '__main__':
70
+ run()
utils3d/test/rasterization_/gl/rasterize_uv.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import imageio
7
+
8
+ def run():
9
+ image_uv, image_mesh = utils3d.numpy.utils.image_mesh(128, 128)
10
+ image_mesh = image_mesh.reshape(-1, 4)
11
+ depth = np.ones((128, 128), dtype=np.float32) * 2
12
+ depth[32:96, 32:96] = 1
13
+ depth = depth.reshape(-1)
14
+ intrinsics = utils3d.numpy.transforms.intrinsics_from_fov(1.0, 128, 128).astype(np.float32)
15
+ intrinsics = utils3d.numpy.transforms.normalize_intrinsics(intrinsics, 128, 128)
16
+ extrinsics = utils3d.numpy.transforms.extrinsics_look_at([0, 0, 1], [0, 0, 0], [0, 1, 0]).astype(np.float32)
17
+ pts = utils3d.numpy.transforms.unproject_cv(image_uv, depth, extrinsics, intrinsics)
18
+ pts = pts.reshape(-1, 3)
19
+ image_mesh = utils3d.numpy.mesh.triangulate(image_mesh, vertices=pts)
20
+
21
+ perspective = utils3d.numpy.transforms.perspective(1.0, 1.0, 0.1, 10)
22
+ view = utils3d.numpy.transforms.view_look_at([1, 0, 1], [0, 0, 0], [0, 1, 0])
23
+ mvp = np.matmul(perspective, view)
24
+ ctx = utils3d.numpy.rasterization.RastContext(
25
+ standalone=True,
26
+ backend='egl',
27
+ device_index=0,
28
+ )
29
+ uv = utils3d.numpy.rasterization.rasterize_triangle_faces(
30
+ ctx,
31
+ pts,
32
+ image_mesh,
33
+ image_uv,
34
+ width=128,
35
+ height=128,
36
+ mvp=mvp,
37
+ )[0]
38
+ uv = (np.concatenate([uv, np.zeros((128, 128, 1), dtype=np.float32)], axis=-1) * 255).astype(np.uint8)
39
+ imageio.imwrite(os.path.join(os.path.dirname(__file__), '..', '..', 'results_to_check', 'rasterize_uv.png'), uv)
40
+
41
+ if __name__ == '__main__':
42
+ run()
utils3d/test/test.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ import torch
4
+ import traceback
5
+
6
+ CRED = '\033[91m'
7
+ CGREEN = '\033[92m'
8
+ CEND = '\033[0m'
9
+
10
+ if __name__ == '__main__':
11
+ # list all tests
12
+ tests = []
13
+ for root, dirs, files in os.walk('test'):
14
+ if root == 'test':
15
+ continue
16
+ for file in files:
17
+ if file.endswith('.py'):
18
+ root = root.replace('test/', '').replace('test\\', '')
19
+ test = os.path.join(root, file)
20
+ test = test.replace('/', '.').replace('\\', '.').replace('.py', '')
21
+ tests.append(test)
22
+ tests.sort()
23
+ print(f'Found {len(tests)} tests:')
24
+ for test in tests:
25
+ print(f' {test}')
26
+ print()
27
+
28
+ # disable torch optimizations
29
+ torch.backends.cudnn.enabled = False
30
+ torch.backends.cuda.matmul.allow_tf32 = False
31
+
32
+ # import and run
33
+ passed = 0
34
+ for test in tests:
35
+ print(f'Running test: {test}... ', end='')
36
+ test = importlib.import_module(test, '.'.join(test.split('.')[:-1]))
37
+ try:
38
+ test.run()
39
+ except Exception as e:
40
+ print(CRED, end='')
41
+ print('Failed')
42
+ traceback.print_exc()
43
+ else:
44
+ print(CGREEN, end='')
45
+ print('Passed')
46
+ passed += 1
47
+ print(CEND, end='')
48
+
49
+ print(f'Passed {passed}/{len(tests)} tests')
50
+
utils3d/test/torch_/mesh/compute_face_angle.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[np.pi/2, np.pi/4, np.pi/4]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+
25
+ expected = utils3d.numpy.compute_face_angle(vertices, faces)
26
+
27
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
28
+ vertices = torch.tensor(vertices, device=device)
29
+ faces = torch.tensor(faces, device=device)
30
+
31
+ actual = utils3d.torch.compute_face_angle(vertices, faces).cpu().numpy()
32
+
33
+ assert np.allclose(expected, actual), '\n' + \
34
+ 'Input:\n' + \
35
+ f'{faces}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
utils3d/test/torch_/mesh/compute_face_normal.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[0, 0, 1]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+
25
+ expected = utils3d.numpy.compute_face_normal(vertices, faces)
26
+
27
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
28
+ vertices = torch.tensor(vertices, device=device)
29
+ faces = torch.tensor(faces, device=device)
30
+
31
+ actual = utils3d.torch.compute_face_normal(vertices, faces).cpu().numpy()
32
+
33
+ assert np.allclose(expected, actual), '\n' + \
34
+ 'Input:\n' + \
35
+ f'{faces}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
utils3d/test/torch_/mesh/compute_vertex_normal.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+
25
+ expected = utils3d.numpy.compute_vertex_normal(vertices, faces)
26
+
27
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
28
+ vertices = torch.tensor(vertices, device=device)
29
+ faces = torch.tensor(faces, device=device)
30
+
31
+ actual = utils3d.torch.compute_vertex_normal(vertices, faces).cpu().numpy()
32
+
33
+ assert np.allclose(expected, actual), '\n' + \
34
+ 'Input:\n' + \
35
+ f'{faces}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
utils3d/test/torch_/mesh/compute_vertex_normal_weighted.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
15
+ else:
16
+ dim = np.random.randint(4)
17
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(*spatial, N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(*spatial, L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+
25
+ expected = utils3d.numpy.compute_vertex_normal_weighted(vertices, faces)
26
+
27
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
28
+ vertices = torch.tensor(vertices, device=device)
29
+ faces = torch.tensor(faces, device=device)
30
+
31
+ actual = utils3d.torch.compute_vertex_normal_weighted(vertices, faces).cpu().numpy()
32
+
33
+ assert np.allclose(expected, actual), '\n' + \
34
+ 'Input:\n' + \
35
+ f'{faces}\n' + \
36
+ 'Actual:\n' + \
37
+ f'{actual}\n' + \
38
+ 'Expected:\n' + \
39
+ f'{expected}'
utils3d/test/torch_/mesh/merge_duplicate_vertices.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=float)
13
+ faces = np.array([[0, 1, 2]])
14
+ expected_vertices = np.array([[0, 0, 0], [1, 0, 0]])
15
+ expected_faces = np.array([[0, 1, 1]])
16
+ expected = expected_vertices[expected_faces]
17
+ else:
18
+ N = np.random.randint(100, 1000)
19
+ vertices = np.random.rand(N, 3)
20
+ L = np.random.randint(1, 1000)
21
+ faces = np.random.randint(0, N, size=(L, 3))
22
+ faces[..., 1] = (faces[..., 0] + 1) % N
23
+ faces[..., 2] = (faces[..., 0] + 2) % N
24
+ vertices[-(N//2):] = vertices[:N//2]
25
+
26
+ expected_vertices, expected_faces = utils3d.numpy.merge_duplicate_vertices(vertices, faces)
27
+ expected = expected_vertices[expected_faces]
28
+
29
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
30
+ vertices = torch.tensor(vertices, device=device)
31
+ faces = torch.tensor(faces, device=device)
32
+
33
+ actual_vertices, actual_faces = utils3d.torch.merge_duplicate_vertices(vertices, faces)
34
+ actual_vertices = actual_vertices.cpu().numpy()
35
+ actual_faces = actual_faces.cpu().numpy()
36
+ actual = actual_vertices[actual_faces]
37
+
38
+ assert expected_vertices.shape == actual_vertices.shape and np.allclose(expected, actual), '\n' + \
39
+ 'Input:\n' + \
40
+ f'{faces}\n' + \
41
+ 'Actual:\n' + \
42
+ f'{actual}\n' + \
43
+ 'Expected:\n' + \
44
+ f'{expected}'
utils3d/test/torch_/mesh/remove_corrupted_faces.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ faces = np.array([[0, 1, 2], [0, 2, 2], [0, 2, 3]])
12
+ expected = np.array([[0, 1, 2], [0, 2, 3]])
13
+ else:
14
+ L = np.random.randint(1, 1000)
15
+ N = np.random.randint(100, 1000)
16
+ faces = np.random.randint(0, N, size=(L, 3))
17
+ faces[..., 1] = (faces[..., 0] + 1) % N
18
+ faces[..., 2] = (faces[..., 0] + 2) % N
19
+
20
+ expected = utils3d.numpy.remove_corrupted_faces(faces)
21
+
22
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
23
+ faces = torch.tensor(faces, device=device)
24
+
25
+ actual = utils3d.torch.remove_corrupted_faces(faces).cpu().numpy()
26
+
27
+ assert np.allclose(expected, actual), '\n' + \
28
+ 'Input:\n' + \
29
+ f'{faces}\n' + \
30
+ 'Actual:\n' + \
31
+ f'{actual}\n' + \
32
+ 'Expected:\n' + \
33
+ f'{expected}'
utils3d/test/torch_/mesh/triangulate.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+
8
+ def run():
9
+ for i in range(100):
10
+ if i == 0:
11
+ spatial = []
12
+ L = 1
13
+ N = 5
14
+ faces = np.array([[0, 1, 2, 3, 4]])
15
+ expected = np.array([[0, 1, 2], [0, 2, 3], [0, 3, 4]])
16
+ else:
17
+ dim = np.random.randint(4)
18
+ spatial = [np.random.randint(1, 10) for _ in range(dim)]
19
+ L = np.random.randint(1, 1000)
20
+ N = np.random.randint(3, 10)
21
+ faces = np.random.randint(0, 10000, size=(*spatial, L, N))
22
+
23
+ expected = utils3d.numpy.triangulate(faces)
24
+
25
+ device = [torch.device('cpu'), torch.device('cuda')][np.random.randint(2)]
26
+ faces = torch.tensor(faces, device=device)
27
+
28
+ actual = utils3d.torch.triangulate(faces).cpu().numpy()
29
+
30
+ assert np.allclose(expected, actual), '\n' + \
31
+ 'Input:\n' + \
32
+ f'{faces}\n' + \
33
+ 'Actual:\n' + \
34
+ f'{actual}\n' + \
35
+ 'Expected:\n' + \
36
+ f'{expected}'
utils3d/test/torch_/rasterization/warp_image_by_depth.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
4
+ import utils3d
5
+ import numpy as np
6
+ import torch
7
+ import imageio
8
+
9
+ def run():
10
+ depth = torch.ones((1, 128, 128), dtype=torch.float32, device='cuda') * 2
11
+ depth[:, 32:48, 32:48] = 1
12
+ intrinsics = utils3d.torch.transforms.intrinsics(1.0, 1.0, 0.5, 0.5).to(depth)
13
+ extrinsics_src = utils3d.torch.transforms.extrinsics_look_at([0., 0., 1.], [0., 0., 0.], [0., 1., 0.]).to(depth)
14
+ extrinsics_tgt = utils3d.torch.transforms.extrinsics_look_at([1., 0., 1.], [0., 0., 0.], [0., 1., 0.]).to(depth)
15
+ ctx = utils3d.torch.rasterization.RastContext(backend='gl', device='cuda')
16
+ uv, _ = utils3d.torch.rasterization.warp_image_by_depth(
17
+ ctx,
18
+ depth,
19
+ extrinsics_src=extrinsics_src,
20
+ extrinsics_tgt=extrinsics_tgt,
21
+ intrinsics_src=intrinsics,
22
+ antialiasing=False,
23
+ )
24
+ uv = torch.cat([uv, torch.zeros((1, 1, 128, 128)).to(uv)], dim=1) * 255
25
+ uv = uv.permute(0, 2, 3, 1).squeeze().cpu().numpy().astype(np.uint8)
26
+
27
+ imageio.imwrite(os.path.join(os.path.dirname(__file__), '..', '..', 'results_to_check', 'torch_warp_image_uv.png'), uv)
28
+
29
+ if __name__ == '__main__':
30
+ run()