import os import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from action_state.utils import ( CO3DDataLoader, get_camera_center, get_view_direction, get_sequence_geometry ) # --- 配置 --- ROOT_PATH = "/run/determined/NAS1/public/lixinyuan/interleaved-co3d" CATEGORY = "hairdryer" SEQUENCE_NAME = "400_51395_100959" # 设置为 None 则绘制所有序列,否则指定单个序列名 OUTPUT_DIR = "./debug/traj/task1_v2" # 输出目录 HIGHLIGHT_FRAMES = [5, 111, 92, 143, 172, 141, 129, 119] def plot_sequence_trajectory(loader, sequence_name, output_path, highlight_frames=None, verbose=True): """ 绘制单个序列的轨迹图 Args: loader: CO3DDataLoader 实例 sequence_name: 序列名称 output_path: 输出文件路径 highlight_frames: 需要高亮的帧ID列表 verbose: 是否显示详细信息 """ if verbose: print(f"\n{'='*60}") print(f"Processing sequence: {sequence_name}") print(f"{'='*60}") 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 ) if verbose: print(f"Scene Alignment Info:") print(f" Original CO3D ground normal: [-0.0396, -0.8306, -0.5554]") print(f" Aligned to standard Y-up: [0, 1, 0]") print(f" Object center: {mean_center}") print(f" Total frames: {len(frame_ids)}") # 使用对齐后的数据收集相机信息 camera_centers = [] view_dirs = [] for fid in frame_ids: info = aligned_seq_data[fid] C = get_camera_center(info['R'], info['T']) V = get_view_direction(info['R']) camera_centers.append(C) view_dirs.append(V) camera_centers = np.array(camera_centers) view_dirs = np.array(view_dirs) # 投影到地面平面(XZ平面,对齐后Y轴向上) x_coords = camera_centers[:, 0] - mean_center[0] z_coords = camera_centers[:, 2] - mean_center[2] y_coords = camera_centers[:, 1] - mean_center[1] # 高度 # 投影光轴向量到地面 view_x = view_dirs[:, 0] view_z = view_dirs[:, 2] view_ground_norm = np.sqrt(view_x**2 + view_z**2) view_ground_norm[view_ground_norm < 1e-6] = 1.0 view_x_normalized = view_x / view_ground_norm view_z_normalized = view_z / view_ground_norm # 绘图 - 只绘制俯视图 fig, ax = plt.subplots(1, 1, figsize=(12, 10)) # 俯视图(地面投影) ax.plot(x_coords, z_coords, c='lightgray', alpha=0.5, linestyle='--', linewidth=2, label='Camera Trajectory') sc = ax.scatter(x_coords, z_coords, c=frame_ids, cmap='viridis', s=50, zorder=5, alpha=0.7, edgecolors='white', linewidths=0.5) cbar = plt.colorbar(sc, ax=ax, label='Frame ID') ax.scatter(0, 0, c='black', marker='X', s=300, linewidths=3, label='Object Center', zorder=15, edgecolors='yellow') # 高亮帧 highlight_indices = [] if highlight_frames: for i, fid in enumerate(frame_ids): if fid in highlight_frames: highlight_indices.append(i) ax.scatter(x_coords[i], z_coords[i], c='red', s=200, zorder=12, edgecolors='black', linewidths=2.5, marker='o') arrow_scale = max(np.std(x_coords), np.std(z_coords)) * 0.3 ax.arrow(x_coords[i], z_coords[i], view_x_normalized[i] * arrow_scale, view_z_normalized[i] * arrow_scale, head_width=arrow_scale*0.15, head_length=arrow_scale*0.2, fc='red', ec='darkred', zorder=11, linewidth=2.5, alpha=0.8) ax.text(x_coords[i], z_coords[i] - arrow_scale*0.5, str(fid), fontsize=16, color='red', fontweight='bold', ha='center', va='top', bbox=dict(boxstyle='round,pad=0.4', facecolor='yellow', edgecolor='red', alpha=0.9, linewidth=2)) ax.plot([0, x_coords[i]], [0, z_coords[i]], 'k:', alpha=0.4, linewidth=1.5, zorder=1) # 计算角度信息 if len(highlight_indices) > 1: ref_idx = highlight_indices[0] ref_angle = np.arctan2(z_coords[ref_idx], x_coords[ref_idx]) angle_info = f"Reference Frame: {frame_ids[ref_idx]} (angle=0°)\n" for idx in highlight_indices[1:]: curr_angle = np.arctan2(z_coords[idx], x_coords[idx]) diff_angle = np.degrees(curr_angle - ref_angle) diff_angle = (diff_angle + 180) % 360 - 180 direction = "CCW" if diff_angle > 0 else "CW" angle_info += f"Frame {frame_ids[idx]}: {abs(diff_angle):.1f}° {direction}\n" ax.text(0.02, 0.98, angle_info, transform=ax.transAxes, fontsize=11, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8), family='monospace') ax.set_title(f"Top-Down View (Ground Plane Projection)\n" f"Aligned to Standard Coordinate System (Y-up)", fontsize=14, fontweight='bold') ax.set_xlabel("X Coordinate (Horizontal, relative to object)", fontsize=12) ax.set_ylabel("Z Coordinate (Horizontal, relative to object)", fontsize=12) ax.axis('equal') ax.grid(True, alpha=0.3, linestyle='--', linewidth=0.5) ax.legend(fontsize=11, loc='upper right') ax.axhline(y=0, color='k', linewidth=0.5, alpha=0.3) ax.axvline(x=0, color='k', linewidth=0.5, alpha=0.3) plt.suptitle(f"CO3D Scene Aligned to Standard Coordinate System\n" f"Sequence: {CATEGORY}/{sequence_name}\n" f"Ground Normal: CO3D [-0.0396,-0.8306,-0.5554] → Standard [0,1,0]", fontsize=15, fontweight='bold') plt.tight_layout() plt.savefig(output_path, dpi=200, bbox_inches='tight') plt.close(fig) if verbose: print(f"✓ Plot saved to {output_path}") print(f" Camera height (Y) range: [{y_coords.min():.3f}, {y_coords.max():.3f}]") print(f" Ground projection range:") print(f" X ∈ [{x_coords.min():.3f}, {x_coords.max():.3f}]") print(f" Z ∈ [{z_coords.min():.3f}, {z_coords.max():.3f}]") def main(): print(f"Loading CO3D data from: {ROOT_PATH}") print(f"Category: {CATEGORY}") loader = CO3DDataLoader(ROOT_PATH, CATEGORY) # 创建输出目录 os.makedirs(OUTPUT_DIR, exist_ok=True) print(f"Output directory: {OUTPUT_DIR}") if SEQUENCE_NAME is None or SEQUENCE_NAME == "": # 绘制所有序列 sequences = loader.get_sequences() print(f"\n{'='*60}") print(f"Processing ALL sequences in category '{CATEGORY}'") print(f"Total sequences: {len(sequences)}") print(f"{'='*60}\n") success_count = 0 error_count = 0 # 使用 tqdm 显示进度 for seq_name in tqdm(sequences, desc="Processing sequences", unit="seq"): output_path = os.path.join(OUTPUT_DIR, f"{seq_name}_traj.png") try: plot_sequence_trajectory( loader, seq_name, output_path, highlight_frames=HIGHLIGHT_FRAMES, verbose=False # 批量处理时不显示详细信息 ) success_count += 1 except Exception as e: tqdm.write(f"✗ Error processing {seq_name}: {e}") error_count += 1 continue print(f"\n{'='*60}") print(f"✓ Processing completed!") print(f" Success: {success_count}/{len(sequences)}") if error_count > 0: print(f" Failed: {error_count}/{len(sequences)}") print(f" Output directory: {OUTPUT_DIR}") print(f"{'='*60}") else: # 绘制单个序列 if SEQUENCE_NAME not in loader.get_sequences(): print(f"Error: Sequence {SEQUENCE_NAME} not found in category {CATEGORY}.") print(f"Available sequences: {loader.get_sequences()}") return output_path = os.path.join(OUTPUT_DIR, f"{SEQUENCE_NAME}_traj.png") plot_sequence_trajectory( loader, SEQUENCE_NAME, output_path, highlight_frames=HIGHLIGHT_FRAMES, verbose=True # 单个序列处理时显示详细信息 ) if __name__ == "__main__": main()