File size: 9,128 Bytes
65534cb 65f8c96 65534cb 65f8c96 e380e4a 65534cb e380e4a 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb 65f8c96 65534cb | 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 | 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()
|