actionbench / projection.py
Remy's picture
Upload ActionBench dataset (imgs + surfaces + cameras)
2796071 verified
Raw
History Blame Contribute Delete
3.08 kB
"""Project animated point cloud onto image using camera parameters."""
import json
import numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter
def project_points(
points: np.ndarray, camera: dict, img_size: int
) -> tuple[np.ndarray, np.ndarray]:
"""Project 3D points to pixel coordinates.
Uses Blender camera convention:
X_cam = points @ R^T + T, camera looks along -Z.
Args:
points: (N, 3) world-space points.
camera: dict with R, T, focal_length_ndc, principal_point_ndc.
img_size: output image resolution (square).
Returns:
(x_pixels, y_pixels): each (N,) array of pixel coordinates.
"""
R = np.asarray(camera["R"], dtype=np.float64)
T = np.asarray(camera["T"], dtype=np.float64)
focal = camera["focal_length_ndc"]
pp = camera["principal_point_ndc"]
X_cam = points @ R.T + T
depth = -X_cam[:, 2]
Z = np.clip(depth, 1e-4, None)
x_ndc = focal[0] * X_cam[:, 0] / Z + pp[0]
y_ndc = focal[1] * X_cam[:, 1] / Z + pp[1]
x_px = img_size / 2.0 * (1.0 + x_ndc)
y_px = img_size / 2.0 * (1.0 - y_ndc)
return x_px, y_px
def render_projection(
image: Image.Image, x_px: np.ndarray, y_px: np.ndarray, img_size: int
) -> np.ndarray:
"""Overlay projected points as a heatmap on an image.
Returns:
(H, W, 3) float32 blended image in [0, 1].
"""
valid = (x_px >= 0) & (x_px < img_size) & (y_px >= 0) & (y_px < img_size)
mask = np.zeros((img_size, img_size), dtype=np.float32)
mask[y_px[valid].astype(int), x_px[valid].astype(int)] = 1.0
mask = np.clip(gaussian_filter(mask, sigma=1.5) * 5.0, 0, 1)
img_np = np.array(image.convert("RGB")).astype(np.float32) / 255.0
overlay = np.array([1.0, 0.3, 0.1])
alpha = 0.4 * mask[..., None]
blended = img_np * (1 - alpha) + overlay * alpha
return np.clip(blended, 0, 1)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Project point cloud onto an image.")
parser.add_argument("--image", required=True, help="Path to input image")
parser.add_argument("--points", required=True, help="Path to surfaces.npy (T,V,6)")
parser.add_argument(
"-t",
"--timestep",
type=int,
default=0,
help="Keyframe index to project (default: 0)",
)
parser.add_argument("--camera", required=True, help="Path to camera.json")
parser.add_argument("--output", required=True, help="Path to output image")
args = parser.parse_args()
# (T, V, 6) -> take keyframe t, xyz only
surfaces = np.load(args.points)
points = surfaces[args.timestep, :, :3].astype(np.float64)
with open(args.camera) as f:
camera = json.load(f)
image = Image.open(args.image)
img_size = image.size[0]
x_px, y_px = project_points(points, camera, img_size)
result = render_projection(image, x_px, y_px, img_size)
out = Image.fromarray((result * 255).astype(np.uint8))
out.save(args.output)
print(f"Saved projection to {args.output}")