import os
import numpy as np
import plotly.graph_objects as go
from action_state.utils import (
CO3DDataLoader,
get_camera_center,
get_view_direction,
get_camera_up,
get_sequence_geometry
)
# --- 配置 ---
ROOT_PATH = "/run/determined/NAS1/public/lixinyuan/interleaved-co3d"
CATEGORY = "tv"
SEQUENCE_NAME = "398_50483_99041"
OUTPUT_FILE = "interactive_3d_aligned.html"
HIGHLIGHT_FRAMES = [74, 85, 157, 98, 116]
def main():
print(f"Loading sequence: {SEQUENCE_NAME}...")
loader = CO3DDataLoader(ROOT_PATH, CATEGORY)
if SEQUENCE_NAME not in loader.get_sequences():
print(f"Error: Sequence {SEQUENCE_NAME} not found.")
return
frame_ids = sorted(loader.get_frames(SEQUENCE_NAME))
seq_data = loader.seq_data[SEQUENCE_NAME]
# 使用CO3D官方对齐方法
mean_center, basis, aligned_seq_data = get_sequence_geometry(
seq_data, align_to_standard=True
)
print(f"\n{'='*60}")
print(f"Aligned to Standard Y-Up Coordinate System")
print(f"Original CO3D ground normal → Standard [0,1,0]")
print(f"{'='*60}\n")
# 收集对齐后的相机数据
camera_centers = []
view_dirs = []
up_vectors = []
for fid in frame_ids:
info = aligned_seq_data[fid]
C = get_camera_center(info['R'], info['T'])
V = get_view_direction(info['R'])
U = get_camera_up(info['R'])
camera_centers.append(C)
view_dirs.append(V)
up_vectors.append(U)
camera_centers = np.array(camera_centers)
view_dirs = np.array(view_dirs)
up_vectors = np.array(up_vectors)
# 计算统计
dists = np.linalg.norm(camera_centers - mean_center, axis=1)
avg_dist = np.mean(dists)
arrow_len = avg_dist * 0.3
# 分析Up向量对齐度
mean_camera_up = np.mean(up_vectors, axis=0)
mean_camera_up_normalized = mean_camera_up / np.linalg.norm(mean_camera_up)
alignment = np.dot(mean_camera_up_normalized, basis[2])
# === 创建Plotly图形 ===
fig = go.Figure()
# 1. 地面平面(XZ平面)
plane_size = avg_dist * 2
x_range = np.linspace(mean_center[0] - plane_size, mean_center[0] + plane_size, 20)
z_range = np.linspace(mean_center[2] - plane_size, mean_center[2] + plane_size, 20)
X_grid, Z_grid = np.meshgrid(x_range, z_range)
Y_grid = np.ones_like(X_grid) * mean_center[1]
fig.add_trace(go.Surface(
x=X_grid, y=Y_grid, z=Z_grid,
colorscale=[[0, 'lightblue'], [1, 'lightblue']],
showscale=False,
opacity=0.15,
name='Ground Plane (XZ)',
hoverinfo='skip'
))
# 2. 世界坐标系轴
axis_len = avg_dist * 0.5
# X轴 - 红色
fig.add_trace(go.Scatter3d(
x=[mean_center[0], mean_center[0] + axis_len],
y=[mean_center[1], mean_center[1]],
z=[mean_center[2], mean_center[2]],
mode='lines+markers',
line=dict(color='red', width=8),
marker=dict(size=[0, 10], symbol='arrow', angleref='previous'),
name='World X',
hovertemplate='X Axis'
))
# Y轴 - 绿色(Up,对齐后的地面法向量)
fig.add_trace(go.Scatter3d(
x=[mean_center[0], mean_center[0]],
y=[mean_center[1], mean_center[1] + axis_len],
z=[mean_center[2], mean_center[2]],
mode='lines+markers',
line=dict(color='lime', width=8),
marker=dict(size=[0, 10], symbol='arrow', angleref='previous'),
name='World Y (Up/Ground Normal)',
hovertemplate='Y Axis (Up)
Aligned from CO3D ground normal'
))
# Z轴 - 蓝色
fig.add_trace(go.Scatter3d(
x=[mean_center[0], mean_center[0]],
y=[mean_center[1], mean_center[1]],
z=[mean_center[2], mean_center[2] + axis_len],
mode='lines+markers',
line=dict(color='cyan', width=8),
marker=dict(size=[0, 10], symbol='arrow', angleref='previous'),
name='World Z',
hovertemplate='Z Axis'
))
# 3. 物体中心
fig.add_trace(go.Scatter3d(
x=[mean_center[0]],
y=[mean_center[1]],
z=[mean_center[2]],
mode='markers',
marker=dict(size=15, color='black', symbol='x',
line=dict(width=3, color='yellow')),
name='Object Center',
hovertemplate='Object Center
X: %{x:.2f}
Y: %{y:.2f}
Z: %{z:.2f}'
))
# 4. 相机轨迹线
fig.add_trace(go.Scatter3d(
x=camera_centers[:, 0],
y=camera_centers[:, 1],
z=camera_centers[:, 2],
mode='lines',
line=dict(color='gray', width=2, dash='dash'),
name='Camera Trajectory',
opacity=0.5,
hoverinfo='skip'
))
# 5. 所有相机位置
fig.add_trace(go.Scatter3d(
x=camera_centers[:, 0],
y=camera_centers[:, 1],
z=camera_centers[:, 2],
mode='markers',
marker=dict(size=3, color=frame_ids, colorscale='Viridis',
colorbar=dict(title="Frame ID"), opacity=0.6),
text=[f'Frame {fid}' for fid in frame_ids],
name='All Cameras',
hovertemplate='%{text}
X: %{x:.2f}
Y: %{y:.2f}
Z: %{z:.2f}'
))
# 6. 高亮帧
highlight_indices = [i for i, fid in enumerate(frame_ids) if fid in HIGHLIGHT_FRAMES]
if highlight_indices:
highlight_centers = camera_centers[highlight_indices]
highlight_fids = [frame_ids[i] for i in highlight_indices]
fig.add_trace(go.Scatter3d(
x=highlight_centers[:, 0],
y=highlight_centers[:, 1],
z=highlight_centers[:, 2],
mode='markers+text',
marker=dict(size=10, color='red', symbol='circle',
line=dict(width=2, color='black')),
text=[str(fid) for fid in highlight_fids],
textposition='top center',
textfont=dict(size=12, color='red', family='Arial Black'),
name='Highlighted Frames',
hovertemplate='Frame %{text}
X: %{x:.2f}
Y: %{y:.2f}
Z: %{z:.2f}'
))
# 7. 高亮帧的相机朝向和Up向量
for idx in highlight_indices:
C = camera_centers[idx]
V = view_dirs[idx]
U = up_vectors[idx]
# View direction (深蓝色)
view_end = C + V * arrow_len
fig.add_trace(go.Scatter3d(
x=[C[0], view_end[0]],
y=[C[1], view_end[1]],
z=[C[2], view_end[2]],
mode='lines',
line=dict(color='darkblue', width=4),
name=f'View Dir (Frame {frame_ids[idx]})',
showlegend=False,
hovertemplate=f'View Direction
Frame {frame_ids[idx]}'
))
# Up vector (洋红色)
up_end = C + U * arrow_len
fig.add_trace(go.Scatter3d(
x=[C[0], up_end[0]],
y=[C[1], up_end[1]],
z=[C[2], up_end[2]],
mode='lines',
line=dict(color='magenta', width=4),
name=f'Up Vec (Frame {frame_ids[idx]})',
showlegend=False,
hovertemplate=f'Camera Up Vector
Frame {frame_ids[idx]}'
))
# 连线到物体中心
fig.add_trace(go.Scatter3d(
x=[C[0], mean_center[0]],
y=[C[1], mean_center[1]],
z=[C[2], mean_center[2]],
mode='lines',
line=dict(color='black', width=1, dash='dot'),
opacity=0.3,
showlegend=False,
hoverinfo='skip'
))
# 8. 平均相机Up向量(用金色虚线表示)
mean_up_end = mean_center + mean_camera_up_normalized * axis_len * 0.9
fig.add_trace(go.Scatter3d(
x=[mean_center[0], mean_up_end[0]],
y=[mean_center[1], mean_up_end[1]],
z=[mean_center[2], mean_up_end[2]],
mode='lines',
line=dict(color='gold', width=6, dash='dash'),
name=f'Mean Camera Up (align={alignment:.2f})',
hovertemplate=f'Mean Camera Up
Alignment: {alignment:.3f}'
))
# 设置布局
fig.update_layout(
title=dict(
text=f'Interactive 3D Camera Trajectory (CO3D Aligned)
' +
f'Sequence: {CATEGORY}/{SEQUENCE_NAME}
' +
f'Original CO3D Ground Normal: [-0.0396,-0.8306,-0.5554] → Aligned [0,1,0]
' +
f' 0.7 else "red"}">Camera Up Alignment: {alignment:.3f} {"✓" if abs(alignment) > 0.7 else "✗"}',
x=0.5,
xanchor='center'
),
scene=dict(
xaxis=dict(
title='X (PyTorch3D: Left)',
backgroundcolor="rgb(240, 240, 240)",
gridcolor="white",
showbackground=True
),
yaxis=dict(
title='Y (PyTorch3D: Up)',
backgroundcolor="rgb(230, 255, 230)",
gridcolor="white",
showbackground=True
),
zaxis=dict(
title='Z (PyTorch3D: Forward)',
backgroundcolor="rgb(240, 240, 240)",
gridcolor="white",
showbackground=True
),
aspectmode='data',
camera=dict(
eye=dict(x=1.5, y=1.5, z=1.5),
center=dict(x=0, y=0, z=0),
up=dict(x=0, y=1, z=0)
)
),
hovermode='closest',
width=1400,
height=900,
showlegend=True,
legend=dict(
x=0.02,
y=0.98,
bgcolor='rgba(255,255,255,0.9)',
bordercolor='black',
borderwidth=1
)
)
# 添加注释说明
fig.add_annotation(
text="🖱️ Controls:
" +
"• Drag to rotate
" +
"• Scroll to zoom
" +
"• Hover for details
" +
"• Double-click to reset",
xref="paper", yref="paper",
x=0.98, y=0.02,
xanchor='right', yanchor='bottom',
showarrow=False,
bgcolor='rgba(255,255,200,0.8)',
bordercolor='black',
borderwidth=1,
font=dict(size=10)
)
# 保存为HTML
fig.write_html(OUTPUT_FILE)
print(f"\n✅ Interactive 3D plot saved to {OUTPUT_FILE}")
print(f"📂 Open it in your browser to interact!")
print(f"\n📊 Analysis:")
print(f" Camera Up Alignment: {alignment:.3f}")
print(f" Status: {'✓ Well aligned' if abs(alignment) > 0.7 else '✗ Misaligned'}")
print(f" Total Frames: {len(frame_ids)}")
print(f" Highlighted Frames: {len(highlight_indices)}")
if __name__ == "__main__":
main()