File size: 8,274 Bytes
208faa0 | 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 | """Compose reason (25f) + RGB (24f) training videos for coaf_dataset_24_25."""
import argparse
import csv
import json
from pathlib import Path
import cv2
import imageio
import numpy as np
DATASET_ROOT = Path("/project/llmsvgen/sunkai/robomaster_3d/Casual_CoAF/coaf_dataset_24_25")
RAW_ROOT = DATASET_ROOT / "raw"
MOD_ROOT = DATASET_ROOT / "modalities"
COMPOSED_ROOT = DATASET_ROOT / "composed"
REASON_FRAMES = 25
RGB_FRAMES = 24
VERSION_CONFIGS = {
"v1_pose_rgb": {"modalities": ["pose"]},
"v2_flow_rgb": {"modalities": ["flow"]},
"v3_pose_flow_rgb": {"modalities": ["pose", "flow"]},
"v4_depth_rgb": {"modalities": ["depth"]},
"v5_pose_depth_rgb": {"modalities": ["pose", "depth"]},
"v6_follow_rgb": {"modalities": ["follow"]},
"v7_follow_flow_rgb": {"modalities": ["follow", "flow"]},
"v8_follow_depth_rgb": {"modalities": ["follow", "depth"]},
}
def get_modality_video_path(modality: str, episode_idx: int) -> Path:
ep_name = f"episode_{episode_idx:06d}"
if modality == "pose":
return MOD_ROOT / "pose" / ep_name / "silhouette_silhouette.mp4"
if modality == "flow":
return MOD_ROOT / "flow" / ep_name / "preview.mp4"
if modality == "depth":
return MOD_ROOT / "depth" / ep_name / "depth.mp4"
if modality == "follow":
return MOD_ROOT / "follow" / ep_name / f"{ep_name}.mp4"
raise ValueError(f"Unknown modality: {modality}")
def read_video_frames(path: Path) -> np.ndarray:
cap = cv2.VideoCapture(str(path))
frames = []
while True:
ret, frame = cap.read()
if not ret:
break
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
cap.release()
if not frames:
raise ValueError(f"No frames read from {path}")
return np.stack(frames)
def sample_frames(frames: np.ndarray, num_frames: int) -> np.ndarray:
if len(frames) == num_frames:
return frames
indices = np.linspace(0, len(frames) - 1, num_frames).astype(int)
return frames[indices]
def read_rgb_pngs(rgb_dir: Path, num_frames: int = RGB_FRAMES) -> np.ndarray:
frames = []
for i in range(1, num_frames + 1):
path = rgb_dir / f"frame_{i:04d}.png"
img = cv2.imread(str(path))
if img is None:
raise FileNotFoundError(f"Missing {path}")
frames.append(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return np.stack(frames)
def resize_frames(frames: np.ndarray, width: int = 256, height: int = 256) -> np.ndarray:
if frames.shape[1] == height and frames.shape[2] == width:
return frames
src_pixels = frames.shape[1] * frames.shape[2]
dst_pixels = width * height
interpolation = cv2.INTER_LANCZOS4 if dst_pixels > src_pixels else cv2.INTER_AREA
return np.stack([cv2.resize(f, (width, height), interpolation=interpolation) for f in frames])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--version", type=str, required=True, choices=list(VERSION_CONFIGS.keys()))
parser.add_argument("--start", type=int, default=0)
parser.add_argument("--stop", type=int, default=5000)
parser.add_argument("--fps", type=int, default=8)
parser.add_argument("--size", type=int, default=None)
parser.add_argument("--width", type=int, default=None)
parser.add_argument("--height", type=int, default=None)
parser.add_argument("--output-suffix", type=str, default="")
parser.add_argument(
"--cond-frames",
type=int,
default=REASON_FRAMES,
help="Reason modality frames per stream (default 25)",
)
parser.add_argument(
"--rgb-frames",
type=int,
default=RGB_FRAMES,
help="RGB frames appended at end (default 24)",
)
parser.add_argument("--validation-count", type=int, default=10)
args = parser.parse_args()
if args.width is not None or args.height is not None:
if args.width is None or args.height is None:
parser.error("--width and --height must be set together")
out_width, out_height = args.width, args.height
else:
square = args.size if args.size is not None else 256
out_width = out_height = square
config = VERSION_CONFIGS[args.version]
output_name = f"{args.version}{args.output_suffix}"
output_root = COMPOSED_ROOT / output_name
videos_dir = output_root / "videos"
cond_dir = output_root / "condition_images"
videos_dir.mkdir(parents=True, exist_ok=True)
cond_dir.mkdir(parents=True, exist_ok=True)
video_paths, image_paths, prompts, state_paths, action_paths, failed = [], [], [], [], [], []
for idx in range(args.start, args.stop):
ep_name = f"episode_{idx:06d}"
rgb_dir = RAW_ROOT / ep_name / "rgb"
instruction_file = RAW_ROOT / ep_name / "instruction" / "instruction.txt"
state_path = RAW_ROOT / ep_name / "state" / "state.npy"
action_path = RAW_ROOT / ep_name / "action" / "action.npy"
try:
if not state_path.is_file() or not action_path.is_file():
raise FileNotFoundError(f"Missing state/action for {ep_name}")
modality_frames_list = []
for mod in config["modalities"]:
mod_path = get_modality_video_path(mod, idx)
frames = read_video_frames(mod_path)
frames = sample_frames(frames, args.cond_frames)
modality_frames_list.append(resize_frames(frames, out_width, out_height))
rgb_frames = read_rgb_pngs(rgb_dir, args.rgb_frames)
rgb_frames = resize_frames(rgb_frames, out_width, out_height)
combined = np.concatenate(modality_frames_list + [rgb_frames], axis=0)
expected = args.cond_frames * len(config["modalities"]) + args.rgb_frames
assert len(combined) == expected, f"expected {expected}, got {len(combined)}"
out_video = videos_dir / f"{ep_name}.mp4"
imageio.mimsave(
str(out_video), combined, fps=args.fps, codec="libx264", macro_block_size=1
)
cond_image = cond_dir / f"{ep_name}.png"
imageio.imwrite(str(cond_image), rgb_frames[0])
prompt = "robot manipulation task"
if instruction_file.exists():
text = instruction_file.read_text().strip()
if text:
prompt = text
video_paths.append(str(out_video))
image_paths.append(str(cond_image))
prompts.append(prompt)
state_paths.append(str(state_path))
action_paths.append(str(action_path))
if idx % 500 == 0 or idx == args.start:
print(f"[ok] {ep_name}: {len(combined)} frames")
except Exception as e:
print(f"[fail] {ep_name}: {e}")
failed.append({"episode_idx": idx, "error": str(e)})
(output_root / "videos.txt").write_text("\n".join(video_paths) + "\n")
(output_root / "images.txt").write_text("\n".join(image_paths) + "\n")
(output_root / "prompt.txt").write_text("\n".join(prompts) + "\n")
(output_root / "state_paths.txt").write_text("\n".join(state_paths) + "\n")
(output_root / "action_paths.txt").write_text("\n".join(action_paths) + "\n")
with (output_root / "metadata.csv").open("w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["index", "image", "video", "text"])
writer.writeheader()
for i, (video, image, prompt) in enumerate(zip(video_paths, image_paths, prompts)):
writer.writerow({"index": i, "image": image, "video": video, "text": prompt})
val_count = min(args.validation_count, len(video_paths))
val_entries = [
{
"sample_index": i,
"caption": prompts[i],
"image_path": image_paths[i],
"video_path": video_paths[i],
}
for i in range(val_count)
]
(output_root / "validation.json").write_text(json.dumps({"data": val_entries}, indent=2) + "\n")
if failed:
(output_root / "failed_episodes.json").write_text(json.dumps(failed, indent=2) + "\n")
print(f"\nDone: {len(video_paths)} composed, {len(failed)} failed -> {output_root}")
if __name__ == "__main__":
main()
|