File size: 11,245 Bytes
65f8c96 | 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 | 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='<b>X Axis</b><extra></extra>'
))
# 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='<b>Y Axis (Up)</b><br>Aligned from CO3D ground normal<extra></extra>'
))
# 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='<b>Z Axis</b><extra></extra>'
))
# 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='<b>Object Center</b><br>X: %{x:.2f}<br>Y: %{y:.2f}<br>Z: %{z:.2f}<extra></extra>'
))
# 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='<b>%{text}</b><br>X: %{x:.2f}<br>Y: %{y:.2f}<br>Z: %{z:.2f}<extra></extra>'
))
# 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='<b>Frame %{text}</b><br>X: %{x:.2f}<br>Y: %{y:.2f}<br>Z: %{z:.2f}<extra></extra>'
))
# 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'<b>View Direction</b><br>Frame {frame_ids[idx]}<extra></extra>'
))
# 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'<b>Camera Up Vector</b><br>Frame {frame_ids[idx]}<extra></extra>'
))
# 连线到物体中心
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'<b>Mean Camera Up</b><br>Alignment: {alignment:.3f}<extra></extra>'
))
# 设置布局
fig.update_layout(
title=dict(
text=f'<b>Interactive 3D Camera Trajectory (CO3D Aligned)</b><br>' +
f'Sequence: {CATEGORY}/{SEQUENCE_NAME}<br>' +
f'<span style="font-size:12px">Original CO3D Ground Normal: [-0.0396,-0.8306,-0.5554] → Aligned [0,1,0]</span><br>' +
f'<span style="font-size:12px; color:{"green" if abs(alignment) > 0.7 else "red"}">Camera Up Alignment: {alignment:.3f} {"✓" if abs(alignment) > 0.7 else "✗"}</span>',
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="<b>🖱️ Controls:</b><br>" +
"• Drag to rotate<br>" +
"• Scroll to zoom<br>" +
"• Hover for details<br>" +
"• 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()
|