Skip to content

Commit 61e38de

Browse files
bottlerfacebook-github-bot
authored andcommitted
rotate_on_spot
Summary: Function to relatively rotate a camera position. Also document how to relatively translate a camera position. Reviewed By: theschnitz Differential Revision: D25900166 fbshipit-source-id: 2ddaf06ee7c5e2a2e973c04d7dee6ccb61c6ff84
1 parent e12a081 commit 61e38de

File tree

4 files changed

+192
-3
lines changed

4 files changed

+192
-3
lines changed

pytorch3d/renderer/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
sigmoid_alpha_blend,
77
softmax_rgb_blend,
88
)
9+
from .camera_utils import rotate_on_spot
910
from .cameras import OpenGLOrthographicCameras # deprecated
1011
from .cameras import OpenGLPerspectiveCameras # deprecated
1112
from .cameras import SfMOrthographicCameras # deprecated

pytorch3d/renderer/camera_utils.py

+75
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,78 @@ def camera_to_eye_at_up(
6262
eye, at, up_plus_eye = eye_at_up_world.unbind(1)
6363
up = up_plus_eye - eye
6464
return eye, at, up
65+
66+
67+
def rotate_on_spot(
68+
R: torch.Tensor, T: torch.Tensor, rotation: torch.Tensor
69+
) -> Tuple[torch.Tensor, torch.Tensor]:
70+
"""
71+
Given a camera position as R and T (batched or not),
72+
and a rotation matrix (batched or not)
73+
return a new R and T representing camera position(s)
74+
in the same location but rotated on the spot by the
75+
given rotation. In particular the new world to view
76+
rotation will be the previous one followed by the inverse
77+
of the given rotation.
78+
79+
For example, adding the following lines before constructing a camera
80+
will make the camera point a little to the right of where it
81+
otherwise would have been.
82+
83+
.. code-block::
84+
85+
from math import radians
86+
from pytorch3d.transforms import axis_angle_to_matrix
87+
angles = [0, radians(10), 0]
88+
rotation = axis_angle_to_matrix(torch.FloatTensor(angles))
89+
R, T = rotate_on_spot(R, T, rotation)
90+
91+
Note here that if you have a column vector, then when you
92+
premultiply it by this `rotation` (see the rotation_conversions doc),
93+
then it will be rotated anticlockwise if facing the -y axis.
94+
In our context, where we postmultiply row vectors to transform them,
95+
`rotation` will rotate the camera clockwise around the -y axis
96+
(i.e. when looking down), which is a turn to the right.
97+
98+
If angles was [radians(10), 0, 0], the camera would get pointed
99+
up a bit instead.
100+
101+
If angles was [0, 0, radians(10)], the camera would be rotated anticlockwise
102+
a bit, so the image would appear rotated clockwise from how it
103+
otherwise would have been.
104+
105+
If you want to translate the camera from the origin in camera
106+
coordinates, this is simple and does not need a separate function.
107+
In particular, a translation by X = [a, b, c] would cause
108+
the camera to move a units left, b units up, and c units
109+
forward. This is achieved by using T-X in place of T.
110+
111+
Args:
112+
R: FloatTensor of shape [3, 3] or [N, 3, 3]
113+
T: FloatTensor of shape [3] or [N, 3]
114+
rotation: FloatTensor of shape [3, 3] or [n, 3, 3]
115+
where if neither n nor N is 1, then n and N must be equal.
116+
117+
Returns:
118+
R: FloatTensor of shape [max(N, n), 3, 3]
119+
T: FloatTensor of shape [max(N, n), 3]
120+
"""
121+
if R.ndim == 2:
122+
R = R[None]
123+
if T.ndim == 1:
124+
T = T[None]
125+
if rotation.ndim == 2:
126+
rotation = rotation[None]
127+
128+
if R.ndim != 3 or R.shape[1:] != (3, 3):
129+
raise ValueError("Invalid R")
130+
if T.ndim != 2 or T.shape[1] != 3:
131+
raise ValueError("Invalid T")
132+
if rotation.ndim != 3 or rotation.shape[1:] != (3, 3):
133+
raise ValueError("Invalid rotation")
134+
135+
new_R = R @ rotation.transpose(1, 2)
136+
old_RT = torch.bmm(R, T[:, :, None])
137+
new_T = torch.matmul(new_R.transpose(1, 2), old_RT)[:, :, 0]
138+
139+
return new_R, new_T

pytorch3d/renderer/cameras.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ class CamerasBase(TensorProperties):
3838
- Screen coordinate system: This is another representation of the view volume with
3939
the XY coordinates defined in pixel space instead of a normalized space.
4040
41-
A better illustration of the coordinate systems can be found in pytorch3d/docs/notes/cameras.md.
41+
A better illustration of the coordinate systems can be found in
42+
pytorch3d/docs/notes/cameras.md.
4243
4344
It defines methods that are common to all camera models:
4445
- `get_camera_center` that returns the optical center of the camera in

tests/test_camera_utils.py

+114-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,29 @@
11
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
22

33
import unittest
4+
from math import radians
45

56
import torch
67
from common_testing import TestCaseMixin
7-
from pytorch3d.renderer.camera_utils import camera_to_eye_at_up
8-
from pytorch3d.renderer.cameras import PerspectiveCameras, look_at_view_transform
8+
from pytorch3d.renderer.camera_utils import camera_to_eye_at_up, rotate_on_spot
9+
from pytorch3d.renderer.cameras import (
10+
PerspectiveCameras,
11+
get_world_to_view_transform,
12+
look_at_view_transform,
13+
)
14+
from pytorch3d.transforms import axis_angle_to_matrix
915
from torch.nn.functional import normalize
1016

1117

18+
def _batched_dotprod(x: torch.Tensor, y: torch.Tensor):
19+
"""
20+
Takes two tensors of shape (N,3) and returns their batched
21+
dot product along the last dimension as a tensor of shape
22+
(N,).
23+
"""
24+
return torch.einsum("ij,ij->i", x, y)
25+
26+
1227
class TestCameraUtils(TestCaseMixin, unittest.TestCase):
1328
def setUp(self) -> None:
1429
torch.manual_seed(42)
@@ -28,6 +43,7 @@ def test_invert_eye_at_up(self):
2843

2944
# The retrieved eye matches
3045
self.assertClose(eye, eye2, atol=1e-5)
46+
self.assertClose(cameras.get_camera_center(), eye)
3147

3248
# at-eye as retrieved must be a vector in the same direction as
3349
# the original.
@@ -49,3 +65,99 @@ def test_invert_eye_at_up(self):
4965
cam_trans2 = cameras2.get_world_to_view_transform()
5066

5167
self.assertClose(cam_trans.get_matrix(), cam_trans2.get_matrix(), atol=1e-5)
68+
69+
def test_rotate_on_spot_yaw(self):
70+
N = 14
71+
eye = torch.rand(N, 3)
72+
at = torch.rand(N, 3)
73+
up = torch.rand(N, 3)
74+
75+
R, T = look_at_view_transform(eye=eye, at=at, up=up)
76+
77+
# Moving around the y axis looks left.
78+
angles = torch.FloatTensor([0, -radians(10), 0])
79+
rotation = axis_angle_to_matrix(angles)
80+
R_rot, T_rot = rotate_on_spot(R, T, rotation)
81+
82+
eye_rot, at_rot, up_rot = camera_to_eye_at_up(
83+
get_world_to_view_transform(R=R_rot, T=T_rot)
84+
)
85+
self.assertClose(eye, eye_rot, atol=1e-5)
86+
87+
# Make vectors pointing exactly left and up
88+
left = torch.cross(up, at - eye, dim=-1)
89+
left_rot = torch.cross(up_rot, at_rot - eye_rot, dim=-1)
90+
fully_up = torch.cross(at - eye, left, dim=-1)
91+
fully_up_rot = torch.cross(at_rot - eye_rot, left_rot, dim=-1)
92+
93+
# The up direction is unchanged
94+
self.assertClose(normalize(fully_up), normalize(fully_up_rot), atol=1e-5)
95+
96+
# The camera has moved left
97+
agree = _batched_dotprod(torch.cross(left, left_rot, dim=1), fully_up)
98+
self.assertGreater(agree.min(), 0)
99+
100+
# Batch dimension for rotation
101+
R_rot2, T_rot2 = rotate_on_spot(R, T, rotation.expand(N, 3, 3))
102+
self.assertClose(R_rot, R_rot2)
103+
self.assertClose(T_rot, T_rot2)
104+
105+
# No batch dimension for either
106+
R_rot3, T_rot3 = rotate_on_spot(R[0], T[0], rotation)
107+
self.assertClose(R_rot[:1], R_rot3)
108+
self.assertClose(T_rot[:1], T_rot3)
109+
110+
# No batch dimension for R, T
111+
R_rot4, T_rot4 = rotate_on_spot(R[0], T[0], rotation.expand(N, 3, 3))
112+
self.assertClose(R_rot[:1].expand(N, 3, 3), R_rot4)
113+
self.assertClose(T_rot[:1].expand(N, 3), T_rot4)
114+
115+
def test_rotate_on_spot_pitch(self):
116+
N = 14
117+
eye = torch.rand(N, 3)
118+
at = torch.rand(N, 3)
119+
up = torch.rand(N, 3)
120+
121+
R, T = look_at_view_transform(eye=eye, at=at, up=up)
122+
123+
# Moving around the x axis looks down.
124+
angles = torch.FloatTensor([-radians(10), 0, 0])
125+
rotation = axis_angle_to_matrix(angles)
126+
R_rot, T_rot = rotate_on_spot(R, T, rotation)
127+
eye_rot, at_rot, up_rot = camera_to_eye_at_up(
128+
get_world_to_view_transform(R=R_rot, T=T_rot)
129+
)
130+
self.assertClose(eye, eye_rot, atol=1e-5)
131+
132+
# A vector pointing left is unchanged
133+
left = torch.cross(up, at - eye, dim=-1)
134+
left_rot = torch.cross(up_rot, at_rot - eye_rot, dim=-1)
135+
self.assertClose(normalize(left), normalize(left_rot), atol=1e-5)
136+
137+
# The camera has moved down
138+
fully_up = torch.cross(at - eye, left, dim=-1)
139+
fully_up_rot = torch.cross(at_rot - eye_rot, left_rot, dim=-1)
140+
agree = _batched_dotprod(torch.cross(fully_up, fully_up_rot, dim=1), left)
141+
self.assertGreater(agree.min(), 0)
142+
143+
def test_rotate_on_spot_roll(self):
144+
N = 14
145+
eye = torch.rand(N, 3)
146+
at = torch.rand(N, 3)
147+
up = torch.rand(N, 3)
148+
149+
R, T = look_at_view_transform(eye=eye, at=at, up=up)
150+
151+
# Moving around the z axis rotates the image.
152+
angles = torch.FloatTensor([0, 0, -radians(10)])
153+
rotation = axis_angle_to_matrix(angles)
154+
R_rot, T_rot = rotate_on_spot(R, T, rotation)
155+
eye_rot, at_rot, up_rot = camera_to_eye_at_up(
156+
get_world_to_view_transform(R=R_rot, T=T_rot)
157+
)
158+
self.assertClose(eye, eye_rot, atol=1e-5)
159+
self.assertClose(normalize(at - eye), normalize(at_rot - eye), atol=1e-5)
160+
161+
# The camera has moved clockwise
162+
agree = _batched_dotprod(torch.cross(up, up_rot, dim=1), at - eye)
163+
self.assertGreater(agree.min(), 0)

0 commit comments

Comments
 (0)