"docs/vscode:/vscode.git/clone" did not exist on "352d63c57858a8717eeece82c393072a1b7d701f"
test_camera_conversions.py 7.62 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
2
3
4
5
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
David Novotny's avatar
David Novotny committed
6
7
8
9
10
11
12
13


import json
import unittest

import numpy as np
import torch
from pytorch3d.ops import eyes
14
from pytorch3d.renderer.points.pulsar import Renderer as PulsarRenderer
15
from pytorch3d.transforms import so3_exp_map, so3_log_map
David Novotny's avatar
David Novotny committed
16
17
from pytorch3d.utils import (
    cameras_from_opencv_projection,
18
    opencv_from_cameras_projection,
19
    pulsar_from_opencv_projection,
David Novotny's avatar
David Novotny committed
20
21
)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
22
23
from .common_testing import get_tests_dir, TestCaseMixin

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
24

David Novotny's avatar
David Novotny committed
25
26
27
28
29
30
31
DATA_DIR = get_tests_dir() / "data"


def cv2_project_points(pts, rvec, tvec, camera_matrix):
    """
    Reproduces the `cv2.projectPoints` function from OpenCV using PyTorch.
    """
32
    R = so3_exp_map(rvec)
David Novotny's avatar
David Novotny committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    pts_proj_3d = (
        camera_matrix.bmm(R.bmm(pts.permute(0, 2, 1)) + tvec[:, :, None])
    ).permute(0, 2, 1)
    depth = pts_proj_3d[..., 2:]
    pts_proj_2d = pts_proj_3d[..., :2] / depth
    return pts_proj_2d


class TestCameraConversions(TestCaseMixin, unittest.TestCase):
    def setUp(self) -> None:
        super().setUp()
        torch.manual_seed(42)
        np.random.seed(42)

    def test_cv2_project_points(self):
        """
        Tests that the local implementation of cv2_project_points gives the same
        restults OpenCV's `cv2.projectPoints`. The check is done against a set
        of precomputed results `cv_project_points_precomputed`.
        """
        with open(DATA_DIR / "cv_project_points_precomputed.json", "r") as f:
            cv_project_points_precomputed = json.load(f)

        for test_case in cv_project_points_precomputed:
            _pts_proj = cv2_project_points(
                **{
                    k: torch.tensor(test_case[k])[None]
                    for k in ("pts", "rvec", "tvec", "camera_matrix")
                }
            )
            pts_proj = torch.tensor(test_case["pts_proj"])[None]
            self.assertClose(_pts_proj, pts_proj, atol=1e-4)

    def test_opencv_conversion(self):
        """
        Tests that the cameras converted from opencv to pytorch3d convention
        return correct projections of random 3D points. The check is done
        against a set of results precomuted using `cv2.projectPoints` function.
        """
72
        device = torch.device("cuda:0")
David Novotny's avatar
David Novotny committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
        image_size = [[480, 640]] * 4
        R = [
            [
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 1.0],
            ],
            [
                [1.0, 0.0, 0.0],
                [0.0, 0.0, -1.0],
                [0.0, 1.0, 0.0],
            ],
            [
                [0.0, 0.0, 1.0],
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
            ],
            [
                [0.0, 0.0, 1.0],
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
            ],
        ]

        tvec = [
            [0.0, 0.0, 3.0],
            [0.3, -0.3, 3.0],
            [-0.15, 0.1, 4.0],
            [0.0, 0.0, 4.0],
        ]
        focal_length = [
            [100.0, 100.0],
            [115.0, 115.0],
            [105.0, 105.0],
            [120.0, 120.0],
        ]
109
110
111
        # These values are in y, x format, but they should be in x, y format.
        # The tests work like this because they only test for consistency,
        # but this format is misleading.
David Novotny's avatar
David Novotny committed
112
113
114
115
116
117
118
119
        principal_point = [
            [240, 320],
            [240.5, 320.3],
            [241, 318],
            [242, 322],
        ]

        principal_point, focal_length, R, tvec, image_size = [
120
            torch.tensor(x, device=device)
David Novotny's avatar
David Novotny committed
121
122
            for x in (principal_point, focal_length, R, tvec, image_size)
        ]
123
        camera_matrix = eyes(dim=3, N=4, device=device)
David Novotny's avatar
David Novotny committed
124
125
126
127
128
129
        camera_matrix[:, 0, 0], camera_matrix[:, 1, 1] = (
            focal_length[:, 0],
            focal_length[:, 1],
        )
        camera_matrix[:, :2, 2] = principal_point

130
131
132
        pts = torch.nn.functional.normalize(
            torch.randn(4, 1000, 3, device=device), dim=-1
        )
David Novotny's avatar
David Novotny committed
133
134

        # project the 3D points with the opencv projection function
135
        rvec = so3_log_map(R)
David Novotny's avatar
David Novotny committed
136
137
138
139
        pts_proj_opencv = cv2_project_points(pts, rvec, tvec, camera_matrix)

        # make the pytorch3d cameras
        cameras_opencv_to_pytorch3d = cameras_from_opencv_projection(
140
            R, tvec, camera_matrix, image_size
David Novotny's avatar
David Novotny committed
141
        )
142
        self.assertEqual(cameras_opencv_to_pytorch3d.device, device)
David Novotny's avatar
David Novotny committed
143

144
145
146
147
        # project the 3D points with converted cameras to screen space.
        pts_proj_pytorch3d_screen = cameras_opencv_to_pytorch3d.transform_points_screen(
            pts
        )[..., :2]
David Novotny's avatar
David Novotny committed
148
149

        # compare to the cached projected points
150
        self.assertClose(pts_proj_opencv, pts_proj_pytorch3d_screen, atol=1e-5)
151
152

        # Check the inverse.
153
        R_i, tvec_i, camera_matrix_i = opencv_from_cameras_projection(
154
155
            cameras_opencv_to_pytorch3d, image_size
        )
156
        self.assertClose(R, R_i)
157
158
        self.assertClose(tvec, tvec_i)
        self.assertClose(camera_matrix, camera_matrix_i)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

    def test_pulsar_conversion(self):
        """
        Tests that the cameras converted from opencv to pulsar convention
        return correct projections of random 3D points. The check is done
        against a set of results precomputed using `cv2.projectPoints` function.
        """
        image_size = [[480, 640]]
        R = [
            [
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 1.0],
            ],
            [
                [0.1968, -0.6663, -0.7192],
                [0.7138, -0.4055, 0.5710],
                [-0.6721, -0.6258, 0.3959],
            ],
        ]
        tvec = [
            [10.0, 10.0, 3.0],
            [-0.0, -0.0, 20.0],
        ]
        focal_length = [
            [100.0, 100.0],
            [10.0, 10.0],
        ]
        principal_point = [
            [320, 240],
            [320, 240],
        ]

        principal_point, focal_length, R, tvec, image_size = [
            torch.FloatTensor(x)
            for x in (principal_point, focal_length, R, tvec, image_size)
        ]
        camera_matrix = eyes(dim=3, N=2)
        camera_matrix[:, 0, 0] = focal_length[:, 0]
        camera_matrix[:, 1, 1] = focal_length[:, 1]
        camera_matrix[:, :2, 2] = principal_point
        rvec = so3_log_map(R)
        pts = torch.tensor(
            [[[0.0, 0.0, 120.0]], [[0.0, 0.0, 120.0]]], dtype=torch.float32
        )
        radii = torch.tensor([[1e-5], [1e-5]], dtype=torch.float32)
        col = torch.zeros((2, 1, 1), dtype=torch.float32)

        # project the 3D points with the opencv projection function
        pts_proj_opencv = cv2_project_points(pts, rvec, tvec, camera_matrix)
        pulsar_cam = pulsar_from_opencv_projection(
            R, tvec, camera_matrix, image_size, znear=100.0
        )
        pulsar_rend = PulsarRenderer(
            640, 480, 1, right_handed_system=False, n_channels=1
        )
        rendered = torch.flip(
            pulsar_rend(
                pts,
                col,
                radii,
                pulsar_cam,
                1e-5,
                max_depth=150.0,
                min_depth=100.0,
            ),
            dims=(1,),
        )
        for batch_id in range(2):
            point_pos = torch.where(rendered[batch_id] == rendered[batch_id].min())
            point_pos = point_pos[1][0], point_pos[0][0]
            self.assertLess(
                torch.abs(point_pos[0] - pts_proj_opencv[batch_id, 0, 0]), 2
            )
            self.assertLess(
                torch.abs(point_pos[1] - pts_proj_opencv[batch_id, 0, 1]), 2
            )