File size: 13,448 Bytes
205a7af |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 72 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
"""Implementation of perspective fields.
Adapted from https://github.com/jinlinyi/PerspectiveFields/blob/main/perspective2d/utils/panocam.py
"""
from typing import Tuple
import torch
from torch.nn import functional as F
from siclib.geometry.base_camera import BaseCamera
from siclib.geometry.gravity import Gravity
from siclib.geometry.jacobians import J_up_projection, J_vecnorm
from siclib.geometry.manifolds import SphericalManifold
# flake8: noqa: E266
def get_horizon_line(camera: BaseCamera, gravity: Gravity, relative: bool = True) -> torch.Tensor:
"""Get the horizon line from the camera parameters.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
relative (bool, optional): Whether to normalize horizon line by img_h. Defaults to True.
Returns:
torch.Tensor: In image frame, fraction of image left/right border intersection with
respect to image height.
"""
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
# project horizon midpoint to image plane
horizon_midpoint = camera.new_tensor([0, 0, 1])
horizon_midpoint = camera.K @ gravity.R @ horizon_midpoint
midpoint = horizon_midpoint[:2] / horizon_midpoint[2]
# compute left and right offset to borders
left_offset = midpoint[0] * torch.tan(gravity.roll)
right_offset = (camera.size[0] - midpoint[0]) * torch.tan(gravity.roll)
left, right = midpoint[1] + left_offset, midpoint[1] - right_offset
horizon = camera.new_tensor([left, right])
return horizon / camera.size[1] if relative else horizon
def get_up_field(camera: BaseCamera, gravity: Gravity, normalize: bool = True) -> torch.Tensor:
"""Get the up vector field from the camera parameters.
Args:
camera (Camera): Camera parameters.
normalize (bool, optional): Whether to normalize the up vector. Defaults to True.
Returns:
torch.Tensor: up vector field as tensor of shape (..., h, w, 2).
"""
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
uv = camera.normalize(camera.pixel_coordinates())
# projected up is (a, b) - c * (u, v)
abc = gravity.vec3d
projected_up2d = abc[..., None, :2] - abc[..., 2, None, None] * uv # (..., N, 2)
if hasattr(camera, "dist"):
d_uv = camera.distort(uv, return_scale=True)[0] # (..., N, 1)
d_uv = torch.diag_embed(d_uv.expand(d_uv.shape[:-1] + (2,))) # (..., N, 2, 2)
offset = camera.up_projection_offset(uv) # (..., N, 2)
offset = torch.einsum("...i,...j->...ij", offset, uv) # (..., N, 2, 2)
# (..., N, 2)
projected_up2d = torch.einsum("...Nij,...Nj->...Ni", d_uv + offset, projected_up2d)
if normalize:
projected_up2d = F.normalize(projected_up2d, dim=-1) # (..., N, 2)
return projected_up2d.reshape(camera.shape[0], h, w, 2)
def J_up_field(
camera: BaseCamera, gravity: Gravity, spherical: bool = False, log_focal: bool = False
) -> torch.Tensor:
"""Get the jacobian of the up field.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
spherical (bool, optional): Whether to use spherical coordinates. Defaults to False.
log_focal (bool, optional): Whether to use log-focal length. Defaults to False.
Returns:
torch.Tensor: Jacobian of the up field as a tensor of shape (..., h, w, 2, 2, 3).
"""
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
# Forward
xy = camera.pixel_coordinates()
uv = camera.normalize(xy)
projected_up2d = gravity.vec3d[..., None, :2] - gravity.vec3d[..., 2, None, None] * uv
# Backward
J = []
# (..., N, 2, 2)
J_norm2proj = J_vecnorm(
get_up_field(camera, gravity, normalize=False).reshape(camera.shape[0], -1, 2)
)
# distortion values
if hasattr(camera, "dist"):
d_uv = camera.distort(uv, return_scale=True)[0] # (..., N, 1)
d_uv = torch.diag_embed(d_uv.expand(d_uv.shape[:-1] + (2,))) # (..., N, 2, 2)
offset = camera.up_projection_offset(uv) # (..., N, 2)
offset_uv = torch.einsum("...i,...j->...ij", offset, uv) # (..., N, 2, 2)
######################
## Gravity Jacobian ##
######################
J_proj2abc = J_up_projection(uv, gravity.vec3d, wrt="abc") # (..., N, 2, 3)
if hasattr(camera, "dist"):
# (..., N, 2, 3)
J_proj2abc = torch.einsum("...Nij,...Njk->...Nik", d_uv + offset_uv, J_proj2abc)
J_abc2delta = SphericalManifold.J_plus(gravity.vec3d) if spherical else gravity.J_rp()
J_proj2delta = torch.einsum("...Nij,...jk->...Nik", J_proj2abc, J_abc2delta)
J_up2delta = torch.einsum("...Nij,...Njk->...Nik", J_norm2proj, J_proj2delta)
J.append(J_up2delta)
######################
### Focal Jacobian ###
######################
J_proj2uv = J_up_projection(uv, gravity.vec3d, wrt="uv") # (..., N, 2, 2)
if hasattr(camera, "dist"):
J_proj2up = torch.einsum("...Nij,...Njk->...Nik", d_uv + offset_uv, J_proj2uv)
J_proj2duv = torch.einsum("...i,...j->...ji", offset, projected_up2d)
inner = (uv * projected_up2d).sum(-1)[..., None, None]
J_proj2offset1 = inner * camera.J_up_projection_offset(uv, wrt="uv")
J_proj2offset2 = torch.einsum("...i,...j->...ij", offset, projected_up2d) # (..., N, 2, 2)
J_proj2uv = (J_proj2duv + J_proj2offset1 + J_proj2offset2) + J_proj2up
J_uv2f = camera.J_normalize(xy) # (..., N, 2, 2)
if log_focal:
J_uv2f = J_uv2f * camera.f[..., None, None, :] # (..., N, 2, 2)
J_uv2f = J_uv2f.sum(-1) # (..., N, 2)
J_proj2f = torch.einsum("...ij,...j->...i", J_proj2uv, J_uv2f) # (..., N, 2)
J_up2f = torch.einsum("...Nij,...Nj->...Ni", J_norm2proj, J_proj2f)[..., None] # (..., N, 2, 1)
J.append(J_up2f)
######################
##### K1 Jacobian ####
######################
if hasattr(camera, "dist"):
J_duv = camera.J_distort(uv, wrt="scale2dist")
J_duv = torch.diag_embed(J_duv.expand(J_duv.shape[:-1] + (2,))) # (..., N, 2, 2)
J_offset = torch.einsum(
"...i,...j->...ij", camera.J_up_projection_offset(uv, wrt="dist"), uv
)
J_proj2k1 = torch.einsum("...Nij,...Nj->...Ni", J_duv + J_offset, projected_up2d)
J_k1 = torch.einsum("...Nij,...Nj->...Ni", J_norm2proj, J_proj2k1)[..., None]
J.append(J_k1)
n_params = sum(j.shape[-1] for j in J)
return torch.cat(J, axis=-1).reshape(camera.shape[0], h, w, 2, n_params)
def get_latitude_field(camera: BaseCamera, gravity: Gravity) -> torch.Tensor:
"""Get the latitudes of the camera pixels in radians.
Latitudes are defined as the angle between the ray and the up vector.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
Returns:
torch.Tensor: Latitudes in radians as a tensor of shape (..., h, w, 1).
"""
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
uv1, _ = camera.image2world(camera.pixel_coordinates())
rays = camera.pixel_bearing_many(uv1)
lat = torch.einsum("...Nj,...j->...N", rays, gravity.vec3d)
eps = 1e-6
lat_asin = torch.asin(lat.clamp(min=-1 + eps, max=1 - eps))
return lat_asin.reshape(camera.shape[0], h, w, 1)
def J_latitude_field(
camera: BaseCamera, gravity: Gravity, spherical: bool = False, log_focal: bool = False
) -> torch.Tensor:
"""Get the jacobian of the latitude field.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
spherical (bool, optional): Whether to use spherical coordinates. Defaults to False.
log_focal (bool, optional): Whether to use log-focal length. Defaults to False.
Returns:
torch.Tensor: Jacobian of the latitude field as a tensor of shape (..., h, w, 1, 3).
"""
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
# Forward
xy = camera.pixel_coordinates()
uv1, _ = camera.image2world(xy)
uv1_norm = camera.pixel_bearing_many(uv1) # (..., N, 3)
# Backward
J = []
J_norm2w_to_img = J_vecnorm(uv1)[..., :2] # (..., N, 2)
######################
## Gravity Jacobian ##
######################
J_delta = SphericalManifold.J_plus(gravity.vec3d) if spherical else gravity.J_rp()
J_delta = torch.einsum("...Ni,...ij->...Nj", uv1_norm, J_delta) # (..., N, 2)
J.append(J_delta)
######################
### Focal Jacobian ###
######################
J_w_to_img2f = camera.J_image2world(xy, "f") # (..., N, 2, 2)
if log_focal:
J_w_to_img2f = J_w_to_img2f * camera.f[..., None, None, :]
J_w_to_img2f = J_w_to_img2f.sum(-1) # (..., N, 2)
J_norm2f = torch.einsum("...Nij,...Nj->...Ni", J_norm2w_to_img, J_w_to_img2f) # (..., N, 3)
J_f = torch.einsum("...Ni,...i->...N", J_norm2f, gravity.vec3d).unsqueeze(-1) # (..., N, 1)
J.append(J_f)
######################
##### K1 Jacobian ####
######################
if hasattr(camera, "dist"):
J_w_to_img2k1 = camera.J_image2world(xy, "dist") # (..., N, 2)
# (..., N, 2)
J_norm2k1 = torch.einsum("...Nij,...Nj->...Ni", J_norm2w_to_img, J_w_to_img2k1)
# (..., N, 1)
J_k1 = torch.einsum("...Ni,...i->...N", J_norm2k1, gravity.vec3d).unsqueeze(-1)
J.append(J_k1)
n_params = sum(j.shape[-1] for j in J)
return torch.cat(J, axis=-1).reshape(camera.shape[0], h, w, 1, n_params)
def get_perspective_field(
camera: BaseCamera,
gravity: Gravity,
use_up: bool = True,
use_latitude: bool = True,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Get the perspective field from the camera parameters.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
use_up (bool, optional): Whether to include the up vector field. Defaults to True.
use_latitude (bool, optional): Whether to include the latitude field. Defaults to True.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Up and latitude fields as tensors of shape
(..., 2, h, w) and (..., 1, h, w).
"""
assert use_up or use_latitude, "At least one of use_up or use_latitude must be True."
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
if use_up:
permute = (0, 3, 1, 2)
# (..., 2, h, w)
up = get_up_field(camera, gravity).permute(permute)
else:
shape = (camera.shape[0], 2, h, w)
up = camera.new_zeros(shape)
if use_latitude:
permute = (0, 3, 1, 2)
# (..., 1, h, w)
lat = get_latitude_field(camera, gravity).permute(permute)
else:
shape = (camera.shape[0], 1, h, w)
lat = camera.new_zeros(shape)
return up, lat
def J_perspective_field(
camera: BaseCamera,
gravity: Gravity,
use_up: bool = True,
use_latitude: bool = True,
spherical: bool = False,
log_focal: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Get the jacobian of the perspective field.
Args:
camera (Camera): Camera parameters.
gravity (Gravity): Gravity vector.
use_up (bool, optional): Whether to include the up vector field. Defaults to True.
use_latitude (bool, optional): Whether to include the latitude field. Defaults to True.
spherical (bool, optional): Whether to use spherical coordinates. Defaults to False.
log_focal (bool, optional): Whether to use log-focal length. Defaults to False.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Up and latitude jacobians as tensors of shape
(..., h, w, 2, 4) and (..., h, w, 1, 4).
"""
assert use_up or use_latitude, "At least one of use_up or use_latitude must be True."
camera = camera.unsqueeze(0) if len(camera.shape) == 0 else camera
gravity = gravity.unsqueeze(0) if len(gravity.shape) == 0 else gravity
w, h = camera.size[0].unbind(-1)
h, w = h.round().to(int), w.round().to(int)
if use_up:
J_up = J_up_field(camera, gravity, spherical, log_focal) # (..., h, w, 2, 4)
else:
shape = (camera.shape[0], h, w, 2, 4)
J_up = camera.new_zeros(shape)
if use_latitude:
J_lat = J_latitude_field(camera, gravity, spherical, log_focal) # (..., h, w, 1, 4)
else:
shape = (camera.shape[0], h, w, 1, 4)
J_lat = camera.new_zeros(shape)
return J_up, J_lat
|