| |
| """ |
| Align Unified Layout Coordinate System to Z-up |
| |
| 统一所有数据集到 Z-up 坐标系,弧度制旋转。 |
| |
| 坐标系标准 (Z-up): |
| - X: 水平轴 (左右) |
| - Y: 水平轴 (前后) |
| - Z: 垂直轴 (高度,向上为正) |
| - 旋转: 弧度制 |
| |
| 数据现状分析: |
| ================================================================================ |
| | 数据源 | boundary | assets pos | assets rot | |
| |--------------------------------|-------------|-------------|---------------| |
| | Layout_info/scannet bbox | N/A | Z-up | 弧度 | |
| | layout_with_boundary.instances | N/A | Z-up | 弧度 | |
| | layout_with_boundary.boundary | Y-up | N/A | N/A | |
| | unified-layout/scannet | Y-up | Z-up | 角度 | |
| | unified-layout/3rscan | Y-up | Z-up | 角度 | |
| | unified-layout/arkitscenes | Y-up | Z-up | 角度 | |
| | unified-layout/3d-front | Y-up | Y-up | 弧度 | |
| ================================================================================ |
| |
| 需要执行的转换: |
| 1. scannet/3rscan/arkitscenes: |
| - boundary: Y-up -> Z-up |
| - assets pos: 已经是 Z-up,不变 |
| - assets rot: 角度 -> 弧度 |
| |
| 2. 3d-front: |
| - boundary: Y-up -> Z-up |
| - assets pos: Y-up -> Z-up |
| - assets rot: 已经是弧度,但绕轴需要调整 |
| |
| Y-up 到 Z-up 转换: |
| [x, y, z]_yup -> [x, z, -y]_zup |
| |
| 即: X不变, Y变成-Z, Z变成Y |
| |
| 使用方法: |
| python tools/post_process/align_unified_layout.py --input-dir /path/to/unified-layout --dataset all |
| python tools/post_process/align_unified_layout.py --input-dir /path/to/unified-layout --dataset 3d-front --in-place |
| """ |
|
|
| import argparse |
| import json |
| import math |
| import os |
| import sys |
| from pathlib import Path |
| from typing import Dict, List, Optional, Tuple |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
| import traceback |
| import copy |
|
|
| |
| SCRIPT_DIR = Path(__file__).parent |
| TOOLS_DIR = SCRIPT_DIR.parent |
| REPO_ROOT = TOOLS_DIR.parent |
| sys.path.insert(0, str(REPO_ROOT)) |
|
|
|
|
| def deg_to_rad(deg: float) -> float: |
| """角度转弧度""" |
| return deg * math.pi / 180.0 |
|
|
|
|
| def y_up_to_z_up_pos(pos: List[float]) -> List[float]: |
| """ |
| 将位置坐标从 Y-up 转换为 Z-up |
| |
| Y-up: [x, y, z] 其中 y 是高度 |
| Z-up: [x, y, z] 其中 z 是高度 |
| |
| 转换: [x, y, z]_yup -> [x, -z, y]_zup |
| |
| 这样可以保持: |
| - 原来的X仍是X |
| - 原来向上的Y变成向上的Z |
| - 原来的Z变成-Y (保持右手系) |
| """ |
| if len(pos) != 3: |
| return pos |
| x, y, z = pos |
| |
| return [round(x, 4), round(-z, 4), round(y, 4)] |
|
|
|
|
| def y_up_to_z_up_size(size: List[float]) -> List[float]: |
| """ |
| 将尺寸从 Y-up 转换为 Z-up |
| |
| Y-up size: [sx, sy, sz] 其中 sy 是高度 |
| Z-up size: [sx, sy, sz] 其中 sz 是高度 |
| |
| 转换: [sx, sy, sz]_yup -> [sx, sz, sy]_zup |
| """ |
| if len(size) != 3: |
| return size |
| sx, sy, sz = size |
| return [round(sx, 4), round(sz, 4), round(sy, 4)] |
|
|
|
|
| def y_up_to_z_up_rot(rot: List[float]) -> List[float]: |
| """ |
| 将旋转从 Y-up 转换为 Z-up |
| |
| Y-up 欧拉角: [rx, ry, rz] 绕 x, y, z 轴旋转 (y 是垂直轴) |
| Z-up 欧拉角: [rx, ry, rz] 绕 x, y, z 轴旋转 (z 是垂直轴) |
| |
| 坐标轴映射: X -> X, Y -> Z, Z -> -Y |
| |
| compose_generated.py 使用 euler_matrix(rot[0], rot[1], rot[2], axes='rzxy'): |
| - rot[0] 是绕 Z 轴的旋转 |
| - rot[1] 是绕 X 轴的旋转 |
| - rot[2] 是绕 Y 轴的旋转 |
| |
| 转换逻辑: |
| - 绕 Y_yup 旋转 (垂直轴) -> 绕 Z_zup 旋转 -> 放到 rot[0] |
| - 绕 X_yup 旋转 -> 绕 X_zup 旋转 -> 放到 rot[1] |
| - 绕 Z_yup 旋转 -> 绕 -Y_zup 旋转 -> 放到 rot[2] 取负 |
| |
| 所以: [rx, ry, rz]_yup -> [ry, rx, -rz]_zup |
| """ |
| if len(rot) != 3: |
| return rot |
| |
| rx, ry, rz = rot |
| |
| |
| new_rot0 = ry |
| new_rot1 = rx |
| new_rot2 = -rz |
| |
| return [round(new_rot0, 6), round(new_rot1, 6), round(new_rot2, 6)] |
|
|
|
|
| def y_up_to_z_up_normal(normal: List[float]) -> List[float]: |
| """ |
| 将法向量从 Y-up 转换为 Z-up |
| """ |
| if len(normal) != 3: |
| return normal |
| x, y, z = normal |
| return [round(x, 4), round(-z, 4), round(y, 4)] |
|
|
|
|
| def transform_boundary_y_to_z(boundary: List[List[float]]) -> List[List[float]]: |
| """ |
| 将边界多边形从 Y-up 转换为 Z-up |
| """ |
| return [y_up_to_z_up_pos(v) for v in boundary] |
|
|
|
|
| def transform_wall_segment_y_to_z(segment) -> List: |
| """ |
| 将墙壁段从 Y-up (2D: [x, z]) 转换为 Z-up (2D: [x, y]) |
| |
| 在 Y-up 系统中,墙壁段是 [x, z] (水平面是 XZ) |
| 在 Z-up 系统中,墙壁段是 [x, y] (水平面是 XY) |
| |
| 转换: [x, z]_yup -> [x, -z]_zup = [x, y]_zup |
| |
| 支持多种格式: |
| - [[x, z], [x, z]] - 标准格式 |
| - [x1, z1, x2, z2] - 扁平格式 |
| - 其他格式保持不变 |
| """ |
| if not isinstance(segment, list) or len(segment) == 0: |
| return segment |
| |
| |
| first = segment[0] |
| |
| |
| if isinstance(first, list): |
| result = [] |
| for point in segment: |
| if isinstance(point, list) and len(point) == 2: |
| x, z = point |
| result.append([round(x, 4), round(-z, 4)]) |
| else: |
| result.append(point) |
| return result |
| |
| |
| elif isinstance(first, (int, float)) and len(segment) == 4: |
| x1, z1, x2, z2 = segment |
| return [[round(x1, 4), round(-z1, 4)], [round(x2, 4), round(-z2, 4)]] |
| |
| |
| return segment |
|
|
|
|
| def transform_asset_scannet(asset: Dict, convert_rot_to_rad: bool = True) -> None: |
| """ |
| 转换 scannet/3rscan/arkitscenes 的 asset |
| |
| - pos: 已经是 Z-up,不变 |
| - size: 已经是 Z-up,不变 |
| - rot: 角度 -> 弧度 (如果需要) |
| """ |
| if "transform" in asset: |
| transform = asset["transform"] |
| |
| |
| if "rot" in transform and convert_rot_to_rad: |
| rot = transform["rot"] |
| transform["rot"] = [round(deg_to_rad(r), 6) for r in rot] |
| else: |
| |
| if "rot" in asset and convert_rot_to_rad: |
| rot = asset["rot"] |
| asset["rot"] = [round(deg_to_rad(r), 6) for r in rot] |
|
|
|
|
| def transform_asset_3dfront(asset: Dict) -> None: |
| """ |
| 转换 3D-FRONT 的 asset |
| |
| - pos: Y-up -> Z-up |
| - size: Y-up -> Z-up |
| - rot: Y-up -> Z-up |
| """ |
| if "transform" in asset: |
| transform = asset["transform"] |
| |
| |
| if "pos" in transform: |
| transform["pos"] = y_up_to_z_up_pos(transform["pos"]) |
| |
| |
| if "size" in transform: |
| transform["size"] = y_up_to_z_up_size(transform["size"]) |
| |
| |
| if "rot" in transform: |
| transform["rot"] = y_up_to_z_up_rot(transform["rot"]) |
| else: |
| if "pos" in asset: |
| asset["pos"] = y_up_to_z_up_pos(asset["pos"]) |
| if "size" in asset: |
| asset["size"] = y_up_to_z_up_size(asset["size"]) |
| if "rot" in asset: |
| asset["rot"] = y_up_to_z_up_rot(asset["rot"]) |
|
|
|
|
| def align_layout_scannet(data: Dict) -> int: |
| """ |
| 对齐 scannet/3rscan/arkitscenes 的 layout |
| |
| Returns: |
| 处理的 asset 数量 |
| """ |
| asset_count = 0 |
| |
| |
| if "architecture" in data: |
| arch = data["architecture"] |
| if "boundary_polygon" in arch: |
| arch["boundary_polygon"] = transform_boundary_y_to_z(arch["boundary_polygon"]) |
| |
| |
| if "structure_nodes" in arch: |
| for node in arch["structure_nodes"]: |
| if "segment" in node: |
| node["segment"] = transform_wall_segment_y_to_z(node["segment"]) |
| if "normal" in node: |
| node["normal"] = y_up_to_z_up_normal(node["normal"]) |
| |
| |
| if "functional_zones" in data: |
| for zone in data["functional_zones"]: |
| if "assets" in zone: |
| for asset in zone["assets"]: |
| transform_asset_scannet(asset, convert_rot_to_rad=True) |
| asset_count += 1 |
| |
| if "assets" in data: |
| for asset in data["assets"]: |
| transform_asset_scannet(asset, convert_rot_to_rad=True) |
| asset_count += 1 |
| |
| return asset_count |
|
|
|
|
| def align_layout_3dfront(data: Dict) -> int: |
| """ |
| 对齐 3D-FRONT 的 layout |
| |
| Returns: |
| 处理的 asset 数量 |
| """ |
| asset_count = 0 |
| |
| |
| if "architecture" in data: |
| arch = data["architecture"] |
| if "boundary_polygon" in arch: |
| arch["boundary_polygon"] = transform_boundary_y_to_z(arch["boundary_polygon"]) |
| |
| |
| if "structure_nodes" in arch: |
| for node in arch["structure_nodes"]: |
| if "segment" in node: |
| node["segment"] = transform_wall_segment_y_to_z(node["segment"]) |
| if "normal" in node: |
| node["normal"] = y_up_to_z_up_normal(node["normal"]) |
| |
| |
| if "functional_zones" in data: |
| for zone in data["functional_zones"]: |
| if "assets" in zone: |
| for asset in zone["assets"]: |
| transform_asset_3dfront(asset) |
| asset_count += 1 |
| |
| if "assets" in data: |
| for asset in data["assets"]: |
| transform_asset_3dfront(asset) |
| asset_count += 1 |
| |
| return asset_count |
|
|
|
|
| def align_single_layout( |
| input_path: str, |
| output_path: str, |
| dataset_type: str |
| ) -> Tuple[bool, str]: |
| """ |
| 对齐单个 layout.json 文件 |
| |
| Args: |
| input_path: 输入文件路径 |
| output_path: 输出文件路径 |
| dataset_type: 数据集类型 ('scannet', '3rscan', 'arkitscenes', '3d-front') |
| |
| Returns: |
| (success, message) |
| """ |
| try: |
| with open(input_path, 'r', encoding='utf-8') as f: |
| data = json.load(f) |
| |
| |
| if data.get("meta", {}).get("aligned"): |
| return True, "already aligned" |
| |
| |
| if dataset_type == "3d-front": |
| asset_count = align_layout_3dfront(data) |
| else: |
| |
| asset_count = align_layout_scannet(data) |
| |
| |
| if "meta" not in data: |
| data["meta"] = {} |
| data["meta"]["coordinate_system"] = "Z-up" |
| data["meta"]["rotation_unit"] = "radians" |
| data["meta"]["aligned"] = True |
| data["meta"]["original_dataset"] = dataset_type |
| |
| |
| os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| |
| |
| with open(output_path, 'w', encoding='utf-8') as f: |
| json.dump(data, f, ensure_ascii=False, indent=2) |
| |
| return True, f"success ({asset_count} assets)" |
| |
| except Exception as e: |
| traceback.print_exc() |
| return False, f"Error: {e}" |
|
|
|
|
| def process_scene(args: Tuple[str, str, str, str]) -> Tuple[str, bool, str]: |
| """处理单个场景 (用于多进程)""" |
| scene_id, input_dir, output_dir, dataset_type = args |
| |
| input_path = os.path.join(input_dir, scene_id, "layout.json") |
| output_path = os.path.join(output_dir, scene_id, "layout.json") |
| |
| if not os.path.isfile(input_path): |
| return scene_id, False, "input not found" |
| |
| success, msg = align_single_layout(input_path, output_path, dataset_type) |
| return scene_id, success, msg |
|
|
|
|
| def discover_scenes(base_dir: str, dataset: str = None) -> List[Tuple[str, str]]: |
| """ |
| 发现所有场景 |
| |
| Args: |
| base_dir: 基础目录 |
| dataset: 数据集名称 或 None 表示全部 |
| |
| Returns: |
| (场景路径, 数据集类型) 列表 |
| """ |
| scenes = [] |
|
|
| with open("/home/v-meiszhang/amlt-project/InternScenes/unified_layout_scenes.txt", 'r') as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| |
| scene_type = line.split('/')[0] |
| scenes.append((line, scene_type)) |
| |
| |
| if dataset and dataset != "all": |
| |
| scenes = [(path, ds_type) for path, ds_type in scenes if ds_type == dataset] |
| |
| |
| filtered_scenes = [] |
| for scene_name, ds_type in scenes: |
| scene_path = os.path.join(base_dir, scene_name) |
| if os.path.isdir(scene_path): |
| layout_path = os.path.join(scene_path, "layout.json") |
| if os.path.isfile(layout_path): |
| filtered_scenes.append((scene_name, ds_type)) |
| |
| return sorted(filtered_scenes, key=lambda x: x[0]) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Align unified-layout coordinate system to Z-up" |
| ) |
| |
| parser.add_argument( |
| "--input-dir", |
| default="/home/v-meiszhang/backup/datas/unified-layout", |
| help="Input unified-layout directory" |
| ) |
| |
| parser.add_argument( |
| "--output-dir", |
| default="/home/v-meiszhang/backup/datas/unified-layout-aligned", |
| help="Output directory (default: input-dir with suffix '-zup')" |
| ) |
| |
| parser.add_argument( |
| "--dataset", |
| choices=["scannet", "arkitscenes", "3rscan", "3d-front", "all"], |
| default="all", |
| help="Dataset to process" |
| ) |
| |
| parser.add_argument( |
| "--in-place", |
| action="store_true", |
| help="Modify files in place (output-dir = input-dir)" |
| ) |
| |
| parser.add_argument( |
| "--workers", "-j", |
| type=int, |
| default=16, |
| help="Number of worker processes" |
| ) |
| |
| parser.add_argument( |
| "--limit", |
| type=int, |
| help="Limit number of scenes to process" |
| ) |
| |
| parser.add_argument( |
| "--dry-run", |
| action="store_true", |
| help="Only show what would be done" |
| ) |
| |
| args = parser.parse_args() |
| |
| |
| if args.in_place: |
| output_dir = args.input_dir |
| elif args.output_dir: |
| output_dir = args.output_dir |
| else: |
| output_dir = args.input_dir + "-zup" |
| |
| print(f"Input directory: {args.input_dir}") |
| print(f"Output directory: {output_dir}") |
| print(f"Dataset: {args.dataset}") |
| print(f"Target coordinate system: Z-up") |
| print(f"Target rotation unit: radians") |
| |
| |
| scenes = discover_scenes(args.input_dir, args.dataset) |
| |
| if args.limit: |
| scenes = scenes[:args.limit] |
| |
| print(f"\nFound {len(scenes)} scenes to process") |
| |
| |
| ds_counts = {} |
| for _, ds_type in scenes: |
| ds_counts[ds_type] = ds_counts.get(ds_type, 0) + 1 |
| for ds, count in sorted(ds_counts.items()): |
| print(f" {ds}: {count}") |
| |
| if args.dry_run: |
| print("\n[DRY RUN] Would process:") |
| for scene, ds_type in scenes[:10]: |
| print(f" [{ds_type}] {scene}") |
| if len(scenes) > 10: |
| print(f" ... and {len(scenes) - 10} more") |
| return |
| |
| |
| task_args = [(scene, args.input_dir, output_dir, ds_type) |
| for scene, ds_type in scenes] |
| |
| results = {"success": 0, "failed": 0, "skipped": 0} |
| |
| print(f"\nProcessing with {args.workers} workers...") |
| |
| with ProcessPoolExecutor(max_workers=args.workers) as executor: |
| futures = {executor.submit(process_scene, arg): arg[0] for arg in task_args} |
| |
| for i, future in enumerate(as_completed(futures), 1): |
| scene_id = futures[future] |
| scene_id, success, msg = future.result() |
| |
| if success: |
| results["success"] += 1 |
| elif "not found" in msg or "already" in msg: |
| results["skipped"] += 1 |
| else: |
| results["failed"] += 1 |
| print(f" FAILED: {scene_id}: {msg}") |
| |
| if i % 500 == 0 or i == len(scenes): |
| print(f"[{i}/{len(scenes)}] success={results['success']}, " |
| f"skipped={results['skipped']}, failed={results['failed']}") |
| |
| |
| print("\n" + "=" * 60) |
| print("SUMMARY") |
| print("=" * 60) |
| print(f"Total scenes: {len(scenes)}") |
| print(f"Successfully aligned: {results['success']}") |
| print(f"Skipped (missing/already aligned): {results['skipped']}") |
| print(f"Failed: {results['failed']}") |
| print(f"\nOutput saved to: {output_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|