| """ |
| 给定一张物体在初始视角的图片,camera将围绕该静止物体进行水平移动。旋转的方向(顺时针或逆时针)是基于从物体正上方俯视(鸟瞰视角)的平面来定义的。模型需要根据给定的旋转方向和角度,推断出新视角下的物体图像,并从四个图像中选出正确的一项。 |
| |
| 注:{angle}就是 xx degrees, {direction} 就是 clockwise / anticlockwise |
| |
| 1. |
| The {object} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {object}. The direction of rotation is defined from a **top-down bird's-eye view**. |
| |
| Please identify the view of the {object} after the camera rotates {angle} {direction} based on this top-down perspective, and select the correct answer. |
| |
| A. <image_start>[image_A]<image_end> |
| B. <image_start>[image_B]<image_end> |
| C. <image_start>[image_C]<image_end> |
| D. <image_start>[image_D]<image_end> |
| |
| |
| 2. |
| Given the initial view of a **static** {object}: <image_start>[image_1]<image_end>. |
| |
| Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle} {direction} around the {object}. |
| |
| Which of the following images shows what the {object} looks like from this new position? |
| |
| A. <image_start>[image_A]<image_end> |
| B. <image_start>[image_B]<image_end> |
| C. <image_start>[image_C]<image_end> |
| D. <image_start>[image_D]<image_end> |
| |
| """ |
|
|
|
|
| import argparse |
| import random |
| import json |
| import os |
| from tqdm import tqdm |
| import numpy as np |
|
|
| |
| from utils import ( |
| CO3DDataLoader, |
| get_relative_yaw, |
| format_angle_direction, |
| get_angle_diff, |
| format_image_path, |
| save_jsonl_splits, |
| get_sequence_geometry_pca, |
| decompose_angle |
| ) |
|
|
| class Task1Generator: |
| def __init__(self, loader, image_prefix): |
| self.loader = loader |
| self.image_prefix = image_prefix |
| self.cat_name = self.loader.category.replace('_', ' ') |
| |
| self.ROTATION_STEPS = [30, 15] |
| |
| self.MAX_COT_ERROR = 10.0 |
|
|
| def verify(self, start_R, start_T, target_R, target_T, distractor_infos, |
| min_angle, max_angle, min_interval, mean_center, basis): |
| """ |
| Task 1 专用验证逻辑: |
| 确保 Start, Target, Distractors 任意两张图之间的角度差都大于 min_interval |
| """ |
| target_yaw = get_relative_yaw(start_R, start_T, target_R, target_T, mean_center, basis) |
| |
| if not (min_angle <= abs(target_yaw) <= max_angle): |
| return False, None, [] |
|
|
| distractor_yaws = [] |
| for d_info in distractor_infos: |
| d_yaw = get_relative_yaw(start_R, start_T, d_info['R'], d_info['T'], mean_center, basis) |
| distractor_yaws.append(d_yaw) |
|
|
| all_angles = [0.0, target_yaw] + distractor_yaws |
| |
| for i in range(len(all_angles)): |
| for j in range(i + 1, len(all_angles)): |
| if get_angle_diff(all_angles[i], all_angles[j]) < min_interval: |
| return False, None, [] |
| |
| return True, target_yaw, distractor_yaws |
|
|
| def _get_all_relative_angles(self, start_idx, all_frames, seq_data_dict, mean_center, basis): |
| """ |
| 计算序列中所有帧相对于 start_idx 的角度。 |
| """ |
| start_info = seq_data_dict[start_idx] |
| results = [] |
| |
| for f_idx in all_frames: |
| if f_idx == start_idx: |
| results.append({'idx': f_idx, 'angle': 0.0}) |
| continue |
| |
| f_info = seq_data_dict[f_idx] |
| yaw = get_relative_yaw( |
| start_info['R'], start_info['T'], |
| f_info['R'], f_info['T'], |
| mean_center, basis |
| ) |
| results.append({'idx': f_idx, 'angle': yaw}) |
| |
| return results |
|
|
| def _check_cot_feasibility(self, target_yaw, all_rel_data): |
| """ |
| [新增] 检查 CoT 路径的可行性。 |
| 如果中间某一步找不到足够接近的真实图片(误差 > MAX_COT_ERROR),则返回 False。 |
| """ |
| rotation_sign = 1 if target_yaw >= 0 else -1 |
| total_delta = abs(target_yaw) |
| steps = decompose_angle(total_delta, self.ROTATION_STEPS) |
| |
| current_simulated_angle = 0.0 |
| |
| for step in steps: |
| current_simulated_angle += (step * rotation_sign) |
| |
| |
| min_diff = float('inf') |
| for item in all_rel_data: |
| diff = abs(item['angle'] - current_simulated_angle) |
| if diff < min_diff: |
| min_diff = diff |
| |
| |
| if min_diff > self.MAX_COT_ERROR: |
| return False |
| |
| return True |
|
|
| def generate_sample(self, seq_name, config): |
| frames = self.loader.get_frames(seq_name) |
| if len(frames) < 10: |
| return None |
|
|
| seq_data_dict = self.loader.seq_data[seq_name] |
| mean_center, basis, _ = get_sequence_geometry_pca(seq_data_dict) |
|
|
| max_attempts = 5000 |
| for _ in range(max_attempts): |
| |
| start_idx = random.choice(frames) |
| start_info = seq_data_dict[start_idx] |
| |
| possible_targets = [f for f in frames if f != start_idx] |
| if not possible_targets: continue |
| target_idx = random.choice(possible_targets) |
| target_info = seq_data_dict[target_idx] |
| |
| remaining = [f for f in frames if f != start_idx and f != target_idx] |
| if len(remaining) < 3: continue |
| distractor_indices = random.sample(remaining, 3) |
| distractor_infos = [seq_data_dict[d] for d in distractor_indices] |
|
|
| |
| is_valid, target_yaw, distractor_yaws = self.verify( |
| start_info['R'], start_info['T'], |
| target_info['R'], target_info['T'], |
| distractor_infos, |
| config['min_angle'], |
| config['max_angle'], |
| config['min_interval'], |
| mean_center, basis |
| ) |
|
|
| if is_valid: |
| |
| all_rel_data = self._get_all_relative_angles( |
| start_idx, frames, seq_data_dict, mean_center, basis |
| ) |
| |
| |
| if not self._check_cot_feasibility(target_yaw, all_rel_data): |
| continue |
| |
| return self.create_entry( |
| seq_name, start_idx, target_idx, distractor_indices, |
| target_yaw, distractor_yaws, start_info, target_info, distractor_infos, |
| all_rel_data |
| ) |
| return None |
|
|
| def create_entry(self, seq_name, start_idx, target_idx, distractor_indices, |
| target_yaw, distractor_yaws, start_info, target_info, distractor_infos, |
| all_rel_data): |
| |
| angle_deg, direction_str = format_angle_direction(target_yaw) |
| |
| |
| options = [{ |
| "path": format_image_path(target_info['path'], self.loader.root_path, self.image_prefix), |
| "angle": target_yaw, |
| "is_correct": True |
| }] |
| for d_idx, d_yaw, d_info in zip(distractor_indices, distractor_yaws, distractor_infos): |
| options.append({ |
| "path": format_image_path(d_info['path'], self.loader.root_path, self.image_prefix), |
| "angle": d_yaw, |
| "is_correct": False |
| }) |
| |
| random.shuffle(options) |
| |
| |
| images_dict = { |
| "image_1": format_image_path(start_info['path'], self.loader.root_path, self.image_prefix) |
| } |
| option_labels = ['A', 'B', 'C', 'D'] |
| correct_label = "" |
| |
| |
| options_meta = {} |
| |
| for label, opt in zip(option_labels, options): |
| img_key = f"image_{label}" |
| images_dict[img_key] = opt["path"] |
| |
| options_meta[label] = { |
| "image_key": img_key, |
| "angle": opt["angle"], |
| "is_correct": opt["is_correct"] |
| } |
| |
| if opt["is_correct"]: |
| correct_label = label |
| |
| |
| |
| |
| rotation_sign = 1 if target_yaw >= 0 else -1 |
| total_delta = abs(target_yaw) |
| steps = decompose_angle(total_delta, self.ROTATION_STEPS) |
| |
| oracle_chain = [] |
| current_simulated_angle = 0.0 |
| |
| |
| for step_idx, step_angle in enumerate(steps): |
| current_simulated_angle += (step_angle * rotation_sign) |
| |
| |
| closest_frame_data = min(all_rel_data, key=lambda x: abs(x['angle'] - current_simulated_angle)) |
| closest_frame_idx = closest_frame_data['idx'] |
| closest_frame_info = self.loader.get_frame_info(seq_name, closest_frame_idx) |
| |
| |
| reasoning_key = f"reasoning_image_{step_idx + 1}" |
| images_dict[reasoning_key] = format_image_path( |
| closest_frame_info['path'], self.loader.root_path, self.image_prefix |
| ) |
| |
| |
| chain_item = { |
| "step_index": step_idx + 1, |
| "action": { |
| "type": "rotate", |
| "degrees": step_angle, |
| "direction": direction_str, |
| "total_angle_so_far": current_simulated_angle |
| }, |
| "result_image_key": reasoning_key, |
| "is_final_step": (step_idx == len(steps) - 1) |
| } |
| oracle_chain.append(chain_item) |
| |
| |
| |
| template_id = random.choice([1, 2]) |
| if template_id == 1: |
| question = f"""The {self.cat_name} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {self.cat_name}. The direction of rotation is defined from a **top-down bird's-eye view**. |
| |
| Please identify the view of the {self.cat_name} after the camera rotates {angle_deg} degrees {direction_str} based on this top-down perspective, and select the correct answer. |
| |
| A. <image_start>[image_A]<image_end> |
| B. <image_start>[image_B]<image_end> |
| C. <image_start>[image_C]<image_end> |
| D. <image_start>[image_D]<image_end>""" |
| else: |
| question = f"""Given the initial view of a **static** {self.cat_name}: <image_start>[image_1]<image_end>. |
| |
| Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle_deg} degrees {direction_str} around the {self.cat_name}. |
| |
| Which of the following images shows what the {self.cat_name} looks like from this new position? |
| |
| A. <image_start>[image_A]<image_end> |
| B. <image_start>[image_B]<image_end> |
| C. <image_start>[image_C]<image_end> |
| D. <image_start>[image_D]<image_end>""" |
|
|
| |
| |
| |
| return { |
| "id": f"task1_{seq_name}_{start_idx}_{target_idx}", |
| "task": "camera_view_prediction", |
| "sequence": seq_name, |
| "question": question, |
| "images": images_dict, |
| "oracle_meta": { |
| "start_frame": start_idx, |
| "target_frame": target_idx, |
| "angle_degrees": angle_deg, |
| "direction": direction_str, |
| "correct_label": correct_label, |
| "options": options_meta, |
| "chain": oracle_chain |
| }, |
| |
| "gt_answer": f"<answer>{correct_label}</answer>" |
| } |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Generate Task 1: Camera View Prediction") |
| |
| |
| parser.add_argument("--root_path", type=str, required=True, help="CO3D dataset root") |
| parser.add_argument("--output_dir", type=str, default="output_task1", help="Output directory") |
| parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths") |
| parser.add_argument("--filter_path", type=str, default=None, help="Root directory for filter logs") |
| |
| |
| parser.add_argument("--category", type=str, default=None, help="Specific category or None for all") |
| parser.add_argument("--num_samples", type=int, default=1, help="Samples per sequence") |
| parser.add_argument("--seed", type=int, default=42) |
| |
| |
| parser.add_argument("--min_angle", type=float, default=40.0) |
| parser.add_argument("--max_angle", type=float, default=140.0) |
| parser.add_argument("--min_interval", type=float, default=25.0) |
| |
| |
| parser.add_argument("--train_ratio", type=float, default=0.8) |
| parser.add_argument("--val_ratio", type=float, default=0.1) |
| parser.add_argument("--test_ratio", type=float, default=0.1) |
| parser.add_argument("--max_items", type=int, default=10000) |
|
|
| args = parser.parse_args() |
| |
| random.seed(args.seed) |
| np.random.seed(args.seed) |
| |
| if args.category: |
| categories = [args.category] |
| else: |
| data_dir = os.path.join(args.root_path, 'data', 'original') |
| if os.path.exists(data_dir): |
| categories = sorted([d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]) |
| else: |
| print(f"Error: {data_dir} not found.") |
| return |
|
|
| all_results = [] |
| config = { |
| 'min_angle': args.min_angle, |
| 'max_angle': args.max_angle, |
| 'min_interval': args.min_interval |
| } |
|
|
| for cat in categories: |
| loader = CO3DDataLoader(args.root_path, cat) |
| if not loader.seq_data: |
| continue |
| |
| generator = Task1Generator(loader, args.image_prefix) |
| sequences = loader.get_sequences() |
|
|
| if args.filter_path: |
| keep_file = os.path.join(args.filter_path, cat, "keep.json") |
| if os.path.exists(keep_file): |
| try: |
| with open(keep_file, 'r') as f: |
| keep_list = set(json.load(f)) |
| sequences = [s for s in sequences if s in keep_list] |
| print(f"[{cat}] Filter applied: {len(sequences)} sequences retained.") |
| except Exception as e: |
| print(f"[{cat}] Error reading keep.json: {e}. Skipping.") |
| sequences = [] |
| else: |
| print(f"[{cat}] Warning: No keep.json found. Skipping.") |
| sequences = [] |
| |
| if not sequences: |
| continue |
| |
| for seq in tqdm(sequences, desc=f"Task1 - {cat}", leave=False): |
| for _ in range(args.num_samples): |
| sample = generator.generate_sample(seq, config) |
| if sample: |
| all_results.append(sample) |
|
|
| print(f"Total generated: {len(all_results)}") |
| save_jsonl_splits( |
| all_results, |
| args.output_dir, |
| ratios=(args.train_ratio, args.val_ratio, args.test_ratio), |
| max_items=args.max_items, |
| seed=args.seed |
| ) |
| print(f"Done. Output saved to {args.output_dir}") |
|
|
| if __name__ == "__main__": |
| main() |
|
|