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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import h5py
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from matplotlib.patches import Patch
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
def extract_task_info_from_filename(filename):
|
| 10 |
+
"""从 HDF5 文件名提取 task_name 和 task_description"""
|
| 11 |
+
stem = Path(filename).stem # e.g., "KITCHEN_SCENE3_..."
|
| 12 |
+
task_name = stem
|
| 13 |
+
if stem.endswith("_demo"):
|
| 14 |
+
stem = stem[:-5]
|
| 15 |
+
|
| 16 |
+
parts = stem.split('_')
|
| 17 |
+
# 跳过场景前缀:KITCHEN, SCENE3, LIVING_ROOM, BEDROOM 等
|
| 18 |
+
i = 0
|
| 19 |
+
while i < len(parts):
|
| 20 |
+
part = parts[i]
|
| 21 |
+
if part.upper() in ["KITCHEN", "LIVING", "BEDROOM", "DINING", "ROOM", "STUDY"] or "SCENE" in part.upper():
|
| 22 |
+
i += 1
|
| 23 |
+
else:
|
| 24 |
+
break
|
| 25 |
+
description_words = parts[i:]
|
| 26 |
+
task_description = " ".join(description_words)
|
| 27 |
+
return task_name, task_description
|
| 28 |
+
|
| 29 |
+
def visualize_and_save_step(
|
| 30 |
+
demo_name,
|
| 31 |
+
agentview_rgb,
|
| 32 |
+
agentview_seg,
|
| 33 |
+
obj_name_to_seg_id,
|
| 34 |
+
save_dir
|
| 35 |
+
):
|
| 36 |
+
"""可视化单个 step 的 RGB + Seg,并保存图像"""
|
| 37 |
+
rgb_img = np.flipud(agentview_rgb)
|
| 38 |
+
seg_img = np.flipud(agentview_seg.squeeze())
|
| 39 |
+
|
| 40 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 8))
|
| 41 |
+
|
| 42 |
+
# RGB
|
| 43 |
+
axes[0].imshow(rgb_img)
|
| 44 |
+
axes[0].set_title("AgentView RGB", fontsize=14)
|
| 45 |
+
axes[0].axis("off")
|
| 46 |
+
|
| 47 |
+
# Segmentation
|
| 48 |
+
unique_ids = np.unique(seg_img)
|
| 49 |
+
cmap = plt.get_cmap("tab20", len(unique_ids))
|
| 50 |
+
im = axes[1].imshow(seg_img, cmap=cmap, vmin=unique_ids.min(), vmax=unique_ids.max())
|
| 51 |
+
axes[1].set_title("Segmentation", fontsize=14)
|
| 52 |
+
axes[1].axis("off")
|
| 53 |
+
|
| 54 |
+
# 图例
|
| 55 |
+
seg_id_to_name = {v: k for k, v in obj_name_to_seg_id.items()}
|
| 56 |
+
legend_elements = []
|
| 57 |
+
|
| 58 |
+
# 获取全局 min/max(用于归一化颜色映射)
|
| 59 |
+
id_min = unique_ids.min()
|
| 60 |
+
id_max = unique_ids.max()
|
| 61 |
+
|
| 62 |
+
for seg_id in sorted(unique_ids):
|
| 63 |
+
name = seg_id_to_name.get(seg_id, f"unknown_{int(seg_id)}")
|
| 64 |
+
# ✅ 正确使用 .min() 和 .max()
|
| 65 |
+
normed_color = (seg_id - id_min) / (id_max - id_min) if id_max > id_min else 0.0
|
| 66 |
+
color = cmap(normed_color)
|
| 67 |
+
legend_elements.append(Patch(facecolor=color, label=f"ID {int(seg_id)}: {name}"))
|
| 68 |
+
|
| 69 |
+
plt.legend(handles=legend_elements, bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10)
|
| 70 |
+
plt.tight_layout()
|
| 71 |
+
|
| 72 |
+
output_path = os.path.join(save_dir, f"{demo_name}_step_20_visualization.png")
|
| 73 |
+
plt.savefig(output_path, dpi=150, bbox_inches="tight")
|
| 74 |
+
plt.close(fig)
|
| 75 |
+
print(f"✅ Saved visualization: {output_path}")
|
| 76 |
+
|
| 77 |
+
def process_all_hdf5_files(data_dir="."):
|
| 78 |
+
"""处理所有 HDF5 文件,每个文件最多可视化 5 个 demo 的 step 20"""
|
| 79 |
+
hdf5_files = [f for f in os.listdir(data_dir) if f.endswith(".hdf5")]
|
| 80 |
+
if not hdf5_files:
|
| 81 |
+
print("⚠️ No .hdf5 files found.")
|
| 82 |
+
return
|
| 83 |
+
|
| 84 |
+
for file_name in hdf5_files:
|
| 85 |
+
file_path = os.path.join(data_dir, file_name)
|
| 86 |
+
try:
|
| 87 |
+
print(f"\n🔍 Processing: {file_name}")
|
| 88 |
+
task_name, task_description = extract_task_info_from_filename(file_name)
|
| 89 |
+
viz_dir = os.path.join("task_visualizations/libero_spatial", task_name)
|
| 90 |
+
os.makedirs(viz_dir, exist_ok=True)
|
| 91 |
+
|
| 92 |
+
desc_file_path = os.path.join(viz_dir, "task_description_id.txt")
|
| 93 |
+
obj_name_to_seg_id = None
|
| 94 |
+
|
| 95 |
+
with h5py.File(file_path, "r") as f:
|
| 96 |
+
data_group = f["data"]
|
| 97 |
+
demos = list(data_group.keys())
|
| 98 |
+
if not demos:
|
| 99 |
+
print(f"❌ No demos in {file_name}")
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
# 先找一个 demo 来提取 obj_name_to_seg_id(用于写文件)
|
| 103 |
+
sample_demo = None
|
| 104 |
+
for demo_name in sorted(demos):
|
| 105 |
+
demo_grp = data_group[demo_name]
|
| 106 |
+
if 'obj_name_to_seg_id' in demo_grp.attrs:
|
| 107 |
+
raw_data = demo_grp.attrs['obj_name_to_seg_id']
|
| 108 |
+
if isinstance(raw_data, bytes):
|
| 109 |
+
raw_data = raw_data.decode('utf-8')
|
| 110 |
+
obj_name_to_seg_id = json.loads(raw_data)
|
| 111 |
+
sample_demo = demo_grp
|
| 112 |
+
break
|
| 113 |
+
|
| 114 |
+
if obj_name_to_seg_id is None:
|
| 115 |
+
print(f"❌ Could not find 'obj_name_to_seg_id' in any demo of {file_name}")
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
# ✅ 现在可以安全写入文件了
|
| 119 |
+
if not os.path.exists(desc_file_path):
|
| 120 |
+
with open(desc_file_path, "w") as f:
|
| 121 |
+
f.write(f"{obj_name_to_seg_id}\n{task_description.strip()}\n{task_description.strip()}")
|
| 122 |
+
print(f"📝 Saved mapping and description to: {desc_file_path}")
|
| 123 |
+
|
| 124 |
+
# 选择最多 5 个 demo 进行可视化
|
| 125 |
+
selected_demos = sorted(demos)[:5]
|
| 126 |
+
|
| 127 |
+
for demo_name in selected_demos:
|
| 128 |
+
demo_grp = data_group[demo_name]
|
| 129 |
+
obs = demo_grp["obs"]
|
| 130 |
+
|
| 131 |
+
# 检查长度
|
| 132 |
+
num_steps = obs["agentview_rgb"].shape[0]
|
| 133 |
+
if num_steps <= 20:
|
| 134 |
+
print(f"🟡 Skipping {demo_name}: only {num_steps} steps (<21)")
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
agentview_rgb = obs["agentview_rgb"][20]
|
| 138 |
+
agentview_seg = obs["agentview_seg"][20]
|
| 139 |
+
|
| 140 |
+
# 获取当前 demo 的 obj_name_to_seg_id(确保一致性)
|
| 141 |
+
if 'obj_name_to_seg_id' in demo_grp.attrs:
|
| 142 |
+
raw_data = demo_grp.attrs['obj_name_to_seg_id']
|
| 143 |
+
if isinstance(raw_data, bytes):
|
| 144 |
+
raw_data = raw_data.decode('utf-8')
|
| 145 |
+
current_mapping = json.loads(raw_data)
|
| 146 |
+
else:
|
| 147 |
+
current_mapping = obj_name_to_seg_id # fallback
|
| 148 |
+
|
| 149 |
+
# 可视化
|
| 150 |
+
visualize_and_save_step(
|
| 151 |
+
demo_name=demo_name,
|
| 152 |
+
agentview_rgb=agentview_rgb,
|
| 153 |
+
agentview_seg=agentview_seg,
|
| 154 |
+
obj_name_to_seg_id=current_mapping,
|
| 155 |
+
save_dir=viz_dir
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"❌ Error processing {file_name}: {e}")
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
process_all_hdf5_files("/mnt/data/data/libero_plus/libero_spatial")
|