import logging from typing import Dict import torch from datasets.datatypes import SliceData logger = logging.getLogger(__name__) def _lift_queries( sample: SliceData, depths: torch.Tensor, intrinsics: torch.Tensor, c2w: torch.Tensor, ) -> torch.Tensor: """Move the GT query points into the given world through their GT pixel and the depth there. A non-positive sampled depth uses the frame median of positive depths. """ gt_query = sample.gt_query_point[0] frames = gt_query[:, 0].long() T, H, W = depths.shape gt_w2c = sample.gt_extrinsics[0][frames] gt_K = sample.gt_intrinsics[0][frames] world = torch.cat([gt_query[:, 1:], torch.ones_like(gt_query[:, :1])], dim=-1) cam = torch.einsum("nij,nj->ni", gt_w2c, world)[:, :3] pix = torch.einsum("nij,nj->ni", gt_K, cam) uv = pix[:, :2] / pix[:, 2:3].clamp_min(1e-6) u = uv[:, 0].round().long().clamp(0, W - 1) v = uv[:, 1].round().long().clamp(0, H - 1) d = depths[frames, v, u] invalid = d <= 0 if invalid.any(): frame_medians = torch.stack([ depths[t][depths[t] > 0].median() if (depths[t] > 0).any() else depths.new_tensor(1.0) for t in range(T) ]) d = torch.where(invalid, frame_medians[frames], d) logger.warning( f"{int(invalid.sum())}/{len(d)} query points fall on invalid ABot depth; using the frame median depth" ) uv1 = torch.cat([uv, torch.ones_like(uv[:, :1])], dim=-1) abot_cam = torch.einsum("nij,nj->ni", torch.linalg.inv(intrinsics[frames]), uv1) * d[:, None] abot_cam = torch.cat([abot_cam, torch.ones_like(abot_cam[:, :1])], dim=-1) abot_world = torch.einsum("nij,nj->ni", c2w[frames], abot_cam)[:, :3] return torch.cat([gt_query[:, :1], abot_world], dim=-1) @torch.no_grad() def apply_abot_geometry( sample: SliceData, geometry: Dict[str, torch.Tensor], ) -> SliceData: """ sample: a batched (B=1) eval sample; geometry: the output of PointTracker3D.predict_abot_geometry on sample.rgbs. Returns a copy with est_* replaced by the ABot depths and cameras. """ assert sample.rgbs.ndim == 5 and sample.rgbs.shape[0] == 1, "ABot eval geometry expects batch size 1" device = sample.rgbs.device depths = geometry["depths"][0].to(device=device, dtype=torch.float32) intrinsics = geometry["intrinsics"][0].to(device=device, dtype=torch.float32) c2w = geometry["c2w"][0].to(device=device, dtype=torch.float32) assert depths.shape == sample.rgbs.shape[1:2] + sample.rgbs.shape[-2:], "ABot geometry must match the sample frames" out = sample.copy() out.est_depths = depths[None] out.est_intrinsics = intrinsics[None] out.est_extrinsics = torch.linalg.inv(c2w)[None] out.est_query_point = _lift_queries(sample, depths, intrinsics, c2w)[None] return out