ZoneMaestro_code / tools /data_gen /normalize_internscenes.py
kkkkiiii's picture
Add files using upload-large-folder tool
4f9eed9 verified
Raw
History Blame Contribute Delete
24.1 kB
#!/usr/bin/env python3
"""
InternScenes 数据归一化工具
将 InternScenes 的杂乱数据(scannet, 3rscan, arkitscenes)归一化为与 3D-FRONT 一致的格式:
1. 烘焙(Bake) 3D资产:把 init_rotation 烘焙进mesh顶点,生成干净的 Z-up 资产
2. 清洗 Layout:rot 只保留 Z 轴旋转(yaw)
原理:
- InternScenes 的 compose_scenes.py 变换链:
final_transform = Y_to_Z_convert @ euler_matrix(rot, axes='rzxy') @ init_rotation @ mesh
其中 init_rotation 是为了把各种来源的mesh(可能是Y-up或其他朝向)统一到一个canonical姿态
- 我们要做的是:
把 init_rotation 烘焙进 mesh,这样新的 mesh 就是干净的 Z-up
然后 rot 就只需要简单的 yaw 角度
使用方法:
python normalize_internscenes.py analyze <layout_path>
python normalize_internscenes.py bake-asset <uid> --output <output_path>
python normalize_internscenes.py normalize <input_dir> --output-dir <output_dir>
"""
import json
import numpy as np
import argparse
import os
import copy
import trimesh
from pathlib import Path
from typing import Dict, List, Tuple, Optional
from scipy.spatial.transform import Rotation as R
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
# 路径配置
BASE_DIR = str(Path(__file__).resolve().parents[2])
ASSET_LIBRARY_FOLDER = os.environ.get('PTH_ASSET_LIBRARY') or os.path.join(BASE_DIR, "data/asset_library")
class AssetProcessor:
"""处理3D资产的烘焙和归一化"""
def __init__(self, asset_library_path: str = ASSET_LIBRARY_FOLDER):
self.asset_dir = asset_library_path
# 加载辅助数据
uid_2_angle_path = os.path.join(asset_library_path, "uid_2_angle.json")
uid_2_cate_path = os.path.join(asset_library_path, "uid_2_origin_cate.json")
self.obja_uid_2_rotation = {}
self.pm_uid_2_origin_cate = {}
if os.path.exists(uid_2_angle_path):
with open(uid_2_angle_path) as f:
self.obja_uid_2_rotation = json.load(f)
if os.path.exists(uid_2_cate_path):
with open(uid_2_cate_path) as f:
self.pm_uid_2_origin_cate = json.load(f)
def get_mesh_path(self, uid: str) -> Optional[str]:
"""获取mesh文件路径"""
if uid.startswith("objaverse/"):
objaverse_rel = uid.split("objaverse/")[-1] + ".glb"
candidates = [
os.path.join(self.asset_dir, uid + ".glb"),
os.path.join(self.asset_dir, "objaverse", "objaverse", objaverse_rel)
]
objaverse_root = os.environ.get("OBJAVERSE_ROOT")
if objaverse_root:
candidates.insert(0, os.path.join(objaverse_root, objaverse_rel))
for path in candidates:
if os.path.exists(path):
return path
return None
elif uid.startswith("objaverse_old/"):
return os.path.join(self.asset_dir, uid + ".glb")
elif uid.startswith("partnet_mobility"):
return os.path.join(self.asset_dir, uid, "whole.glb")
elif uid.startswith("3D-FUTURE-model"):
return os.path.join(self.asset_dir, uid + ".glb")
elif uid.startswith("hssd-models"):
return os.path.join(self.asset_dir, uid + ".glb")
elif uid.startswith("gen_assets"):
return os.path.join(self.asset_dir, uid + ".glb")
elif uid.startswith("gr100"):
return os.path.join(self.asset_dir, uid + ".glb")
else:
return None
def get_init_rotation_matrix(self, uid: str) -> np.ndarray:
"""
获取 init_rotation 矩阵(4x4)
这是 compose_scenes.py 中 load_init_rotation 的逻辑
"""
def rotation_matrix(angle, axis):
"""创建绕指定轴旋转的4x4矩阵"""
r = R.from_rotvec(angle * np.array(axis))
mat = np.eye(4)
mat[:3, :3] = r.as_matrix()
return mat
if uid.startswith("objaverse/"):
objaverse_id = uid.split("objaverse/")[-1]
rot_deg = self.obja_uid_2_rotation.get(objaverse_id, 0)
rot_rad = rot_deg / 180.0 * np.pi
transform = rotation_matrix(rot_rad, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
elif uid.startswith("objaverse_old/"):
transform = rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
elif uid.startswith("partnet_mobility"):
transform = rotation_matrix(np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
# 特殊类别处理
pm_cate = self.pm_uid_2_origin_cate.get(uid, "")
if pm_cate in ["Pen", "Remote", "Phone"]:
rotation_1 = rotation_matrix(np.pi, [0, 0, 1])
rotation_2 = rotation_matrix(np.pi / 2, [0, 1, 0])
transform = rotation_2 @ rotation_1 @ transform
elif uid.startswith("3D-FUTURE-model"):
transform = rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
elif uid.startswith("hssd-models"):
transform = rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
elif uid.startswith("gen_assets"):
transform = rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
elif uid.startswith("gr100"):
transform = rotation_matrix(0.5 * np.pi, [0, 0, 1]) @ \
rotation_matrix(0.5 * np.pi, [1, 0, 0])
else:
# 默认:无变换
transform = np.eye(4)
return transform
def load_and_bake_mesh(self, uid: str, use_texture: bool = False) -> Optional[trimesh.Trimesh]:
"""
加载mesh并烘焙 init_rotation
烘焙后的mesh是干净的 Z-up,且正面朝向统一
"""
mesh_path = self.get_mesh_path(uid)
if mesh_path is None or not os.path.exists(mesh_path):
return None
try:
if use_texture:
mesh = trimesh.load(mesh_path)
else:
mesh = trimesh.load(mesh_path, force="mesh")
# 获取 init_rotation
init_transform = self.get_init_rotation_matrix(uid)
# 居中
if hasattr(mesh, 'bounding_box'):
centroid = mesh.bounding_box.centroid
mesh.apply_translation(-centroid)
# 应用 init_rotation(烘焙)
mesh.apply_transform(init_transform)
return mesh
except Exception as e:
print(f"Error loading mesh {uid}: {e}")
return None
def euler_zxy_to_yaw(rot_zxy: List[float]) -> float:
"""
从 ZXY 顺序的 euler 角提取等效的 yaw(绕Z轴旋转)
对于纯yaw情况,直接返回 rot[0]
对于有倾斜的情况,计算完整旋转矩阵后提取 yaw
"""
# 构建旋转矩阵
R_mat = R.from_euler('zxy', rot_zxy).as_matrix()
# 提取 yaw:在 Z-up 坐标系中,yaw 是绕 Z 轴的旋转
# 看 X 轴被转到哪里,取其在 XY 平面的角度
x_transformed = R_mat @ np.array([1, 0, 0])
yaw = np.arctan2(x_transformed[1], x_transformed[0])
return yaw
def is_pure_yaw_zxy(rot: List[float], threshold_deg: float = 2.0) -> bool:
"""检查 ZXY 格式的旋转是否是纯yaw (rot[1]=rx, rot[2]=ry 接近0)"""
rx_deg = abs(np.degrees(rot[1]))
ry_deg = abs(np.degrees(rot[2]))
return rx_deg < threshold_deg and ry_deg < threshold_deg
def is_pure_yaw_xyz(rot: List[float], threshold_deg: float = 2.0) -> bool:
"""检查 XYZ 格式的旋转是否是纯yaw (rot[0]=rx, rot[1]=ry 接近0)"""
rx_deg = abs(np.degrees(rot[0]))
ry_deg = abs(np.degrees(rot[1]))
return rx_deg < threshold_deg and ry_deg < threshold_deg
def analyze_layout(layout_path: str, asset_processor: AssetProcessor = None) -> dict:
"""分析 layout 文件"""
with open(layout_path, 'r') as f:
layout = json.load(f)
results = {
'path': layout_path,
'total_assets': 0,
'pure_yaw': 0,
'tilted': 0,
'unique_uids': set(),
'sources': {},
'details': [],
'format': 'unknown' # 'zxy' (原始InternScenes) 或 'xyz' (归一化后/3D-FRONT)
}
# 检测格式
if isinstance(layout, list):
items = layout
get_rot = lambda item: item['bbox'][6:9]
get_uid = lambda item: item.get('model_uid', '')
get_cat = lambda item: item.get('category', 'unknown')
else:
items = []
for zone in layout.get('functional_zones', []):
items.extend(zone.get('assets', []))
get_rot = lambda item: item.get('transform', {}).get('rot', [0,0,0])
get_uid = lambda item: item.get('model_uid', '')
get_cat = lambda item: item.get('category', 'unknown')
# 自动检测是 ZXY 还是 XYZ 格式
# 如果大多数 rot[0], rot[1] 接近0,那么是 XYZ 格式(归一化后)
# 如果大多数 rot[1], rot[2] 接近0,那么是 ZXY 格式(原始)
xyz_count = 0
zxy_count = 0
for item in items:
rot = get_rot(item)
if is_pure_yaw_xyz(rot):
xyz_count += 1
if is_pure_yaw_zxy(rot):
zxy_count += 1
# 判断格式
if xyz_count > zxy_count:
results['format'] = 'xyz'
is_pure_yaw = is_pure_yaw_xyz
else:
results['format'] = 'zxy'
is_pure_yaw = is_pure_yaw_zxy
for item in items:
uid = get_uid(item)
rot = get_rot(item)
cat = get_cat(item)
results['total_assets'] += 1
results['unique_uids'].add(uid)
# 统计来源
source = uid.split('/')[0] if '/' in uid else 'unknown'
results['sources'][source] = results['sources'].get(source, 0) + 1
# 分析旋转
pure = is_pure_yaw(rot)
if pure:
results['pure_yaw'] += 1
else:
results['tilted'] += 1
# yaw 提取方式取决于格式
if results['format'] == 'zxy':
yaw_deg = np.degrees(euler_zxy_to_yaw(rot))
else:
yaw_deg = np.degrees(rot[2]) # XYZ格式,yaw在rot[2]
results['details'].append({
'uid': uid,
'category': cat,
'rot_deg': [np.degrees(r) for r in rot],
'is_pure_yaw': pure,
'yaw_deg': yaw_deg
})
results['unique_uids'] = len(results['unique_uids'])
return results
def normalize_layout(layout, asset_processor: AssetProcessor = None) -> Tuple[dict, dict]:
"""
归一化 layout
将 rot 从 [rz, rx, ry] (ZXY顺序) 转换为 [0, 0, yaw] (只有Z轴旋转)
Returns:
(new_layout, stats)
"""
new_layout = copy.deepcopy(layout)
stats = {
'total': 0,
'converted': 0,
'pure_yaw': 0,
'tilted': 0,
}
# 检测格式
if isinstance(new_layout, list):
# 旧格式
for item in new_layout:
stats['total'] += 1
old_rot = item['bbox'][6:9]
# 提取 yaw
yaw = euler_zxy_to_yaw(old_rot)
# 更新为干净格式 [0, 0, yaw]
item['bbox'][6] = 0.0
item['bbox'][7] = 0.0
item['bbox'][8] = yaw
stats['converted'] += 1
if is_pure_yaw_zxy(old_rot):
stats['pure_yaw'] += 1
else:
stats['tilted'] += 1
else:
# 新格式
for zone in new_layout.get('functional_zones', []):
for asset in zone.get('assets', []):
stats['total'] += 1
old_rot = asset.get('transform', {}).get('rot', [0, 0, 0])
# 提取 yaw
yaw = euler_zxy_to_yaw(old_rot)
# 更新为干净格式
asset['transform']['rot'] = [0.0, 0.0, yaw]
stats['converted'] += 1
if is_pure_yaw_zxy(old_rot):
stats['pure_yaw'] += 1
else:
stats['tilted'] += 1
return new_layout, stats
def collect_unique_uids(input_dir: str) -> set:
"""收集目录下所有layout文件中的唯一uid"""
import glob
uids = set()
layout_files = glob.glob(os.path.join(input_dir, '**/layout.json'), recursive=True)
for layout_path in layout_files:
try:
with open(layout_path, 'r') as f:
layout = json.load(f)
if isinstance(layout, list):
for item in layout:
uid = item.get('model_uid', '')
if uid:
uids.add(uid)
else:
for zone in layout.get('functional_zones', []):
for asset in zone.get('assets', []):
uid = asset.get('model_uid', '')
if uid:
uids.add(uid)
except Exception as e:
print(f"Error reading {layout_path}: {e}")
return uids
# ==================== 命令行接口 ====================
def cmd_analyze(args):
"""分析命令"""
asset_processor = AssetProcessor()
result = analyze_layout(args.layout_path, asset_processor)
print(f"\n{'='*60}")
print(f"Layout 分析: {args.layout_path}")
print(f"{'='*60}")
print(f"检测格式: {result['format'].upper()} (ZXY=原始InternScenes, XYZ=归一化后/3D-FRONT)")
print(f"总资产数: {result['total_assets']}")
print(f"唯一uid数: {result['unique_uids']}")
print(f"纯yaw旋转: {result['pure_yaw']} ({100*result['pure_yaw']/max(1,result['total_assets']):.1f}%)")
print(f"有倾斜: {result['tilted']} ({100*result['tilted']/max(1,result['total_assets']):.1f}%)")
print(f"\n资产来源分布:")
for source, count in sorted(result['sources'].items(), key=lambda x: -x[1]):
print(f" {source}: {count}")
if args.verbose:
print(f"\n{'='*60}")
print("详细信息 (前20个):")
print(f"{'='*60}")
for i, d in enumerate(result['details'][:20]):
status = "→" if d['is_pure_yaw'] else "✗"
print(f" {status} [{i:3d}] {d['category']:15s}")
print(f" rot=[{d['rot_deg'][0]:7.1f}, {d['rot_deg'][1]:7.1f}, {d['rot_deg'][2]:7.1f}] -> yaw={d['yaw_deg']:.1f}°")
def cmd_normalize(args):
"""归一化命令:处理layout文件"""
import glob
layout_files = glob.glob(os.path.join(args.input_dir, '**/layout.json'), recursive=True)
print(f"找到 {len(layout_files)} 个layout文件")
total_stats = {
'files': 0,
'total': 0,
'converted': 0,
'pure_yaw': 0,
'tilted': 0,
}
for layout_path in tqdm(layout_files, desc="处理layout"):
try:
with open(layout_path, 'r') as f:
layout = json.load(f)
new_layout, stats = normalize_layout(layout)
# 计算输出路径
rel_path = os.path.relpath(layout_path, args.input_dir)
output_path = os.path.join(args.output_dir, rel_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w') as f:
json.dump(new_layout, f, indent=2)
total_stats['files'] += 1
total_stats['total'] += stats['total']
total_stats['converted'] += stats['converted']
total_stats['pure_yaw'] += stats['pure_yaw']
total_stats['tilted'] += stats['tilted']
except Exception as e:
print(f"错误处理 {layout_path}: {e}")
print(f"\n{'='*60}")
print(f"Layout 归一化完成")
print(f"{'='*60}")
print(f"处理文件数: {total_stats['files']}")
print(f"总资产数: {total_stats['total']}")
print(f"已转换: {total_stats['converted']} (纯yaw: {total_stats['pure_yaw']}, 有倾斜: {total_stats['tilted']})")
print(f"输出目录: {args.output_dir}")
def cmd_bake_assets(args):
"""烘焙资产命令:处理3D资产"""
import glob
asset_processor = AssetProcessor()
# 收集需要处理的uid
if args.uid:
uids = {args.uid}
else:
print("收集需要处理的uid...")
uids = collect_unique_uids(args.input_dir)
print(f"找到 {len(uids)} 个唯一uid")
# 按来源分组
sources = {}
for uid in uids:
source = uid.split('/')[0] if '/' in uid else 'unknown'
if source not in sources:
sources[source] = []
sources[source].append(uid)
print(f"\n来源分布:")
for source, uid_list in sorted(sources.items(), key=lambda x: -len(x[1])):
print(f" {source}: {len(uid_list)}")
if args.dry_run:
print("\n[Dry run] 不会实际处理资产")
return
# 处理资产
success = 0
failed = 0
skipped = 0
for uid in tqdm(uids, desc="烘焙资产"):
try:
# 检查是否已存在
output_path = os.path.join(args.output_dir, uid + ".glb")
if os.path.exists(output_path) and not args.force:
skipped += 1
continue
# 加载并烘焙
mesh = asset_processor.load_and_bake_mesh(uid, use_texture=args.texture)
if mesh is None:
failed += 1
continue
# 保存
os.makedirs(os.path.dirname(output_path), exist_ok=True)
mesh.export(output_path)
success += 1
except Exception as e:
print(f"错误处理 {uid}: {e}")
failed += 1
print(f"\n{'='*60}")
print(f"资产烘焙完成")
print(f"{'='*60}")
print(f"成功: {success}")
print(f"失败: {failed}")
print(f"跳过(已存在): {skipped}")
print(f"输出目录: {args.output_dir}")
def cmd_full_normalize(args):
"""完整归一化:同时处理layout和资产"""
import glob
print("="*60)
print("InternScenes 完整归一化")
print("="*60)
asset_processor = AssetProcessor()
# Step 1: 收集所有uid
print("\n[Step 1] 收集唯一uid...")
uids = collect_unique_uids(args.input_dir)
print(f"找到 {len(uids)} 个唯一uid")
# Step 2: 烘焙资产(如果指定了资产输出目录)
if args.asset_output_dir:
print(f"\n[Step 2] 烘焙3D资产到 {args.asset_output_dir}...")
success = 0
failed = 0
skipped = 0
for uid in tqdm(uids, desc="烘焙资产"):
try:
output_path = os.path.join(args.asset_output_dir, uid + ".glb")
if os.path.exists(output_path) and not args.force:
skipped += 1
continue
mesh = asset_processor.load_and_bake_mesh(uid, use_texture=False)
if mesh is None:
failed += 1
continue
os.makedirs(os.path.dirname(output_path), exist_ok=True)
mesh.export(output_path)
success += 1
except Exception as e:
failed += 1
print(f" 成功: {success}, 失败: {failed}, 跳过: {skipped}")
# Step 3: 归一化layout
print(f"\n[Step 3] 归一化layout到 {args.output_dir}...")
layout_files = glob.glob(os.path.join(args.input_dir, '**/layout.json'), recursive=True)
total_stats = {'files': 0, 'assets': 0}
for layout_path in tqdm(layout_files, desc="处理layout"):
try:
with open(layout_path, 'r') as f:
layout = json.load(f)
new_layout, stats = normalize_layout(layout)
rel_path = os.path.relpath(layout_path, args.input_dir)
output_path = os.path.join(args.output_dir, rel_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w') as f:
json.dump(new_layout, f, indent=2)
total_stats['files'] += 1
total_stats['assets'] += stats['total']
except Exception as e:
print(f"错误: {layout_path}: {e}")
print(f" 处理了 {total_stats['files']} 个layout文件, {total_stats['assets']} 个资产")
print(f"\n{'='*60}")
print("完成!")
print(f"{'='*60}")
def main():
parser = argparse.ArgumentParser(
description='InternScenes 数据归一化工具',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
# 分析layout
python normalize_internscenes.py analyze layout.json -v
# 归一化layout目录
python normalize_internscenes.py normalize ./scannet --output-dir ./scannet_clean
# 烘焙资产
python normalize_internscenes.py bake-assets ./scannet --output-dir ./baked_assets
# 完整归一化(layout + 资产)
python normalize_internscenes.py full ./scannet --output-dir ./clean --asset-output-dir ./baked
"""
)
subparsers = parser.add_subparsers(dest='command', help='子命令')
# analyze
p_analyze = subparsers.add_parser('analyze', help='分析layout文件')
p_analyze.add_argument('layout_path', help='layout.json路径')
p_analyze.add_argument('-v', '--verbose', action='store_true')
# normalize (只处理layout)
p_normalize = subparsers.add_parser('normalize', help='归一化layout文件')
p_normalize.add_argument('input_dir', help='输入目录')
p_normalize.add_argument('--output-dir', required=True, help='输出目录')
# bake-assets (只处理资产)
p_bake = subparsers.add_parser('bake-assets', help='烘焙3D资产')
p_bake.add_argument('input_dir', help='包含layout的输入目录(用于收集uid)')
p_bake.add_argument('--output-dir', required=True, help='输出目录')
p_bake.add_argument('--uid', help='只处理指定uid')
p_bake.add_argument('--texture', action='store_true', help='保留纹理')
p_bake.add_argument('--force', action='store_true', help='强制覆盖已存在的文件')
p_bake.add_argument('--dry-run', action='store_true', help='只分析不处理')
# full (完整归一化)
p_full = subparsers.add_parser('full', help='完整归一化(layout + 资产)')
p_full.add_argument('input_dir', help='输入目录')
p_full.add_argument('--output-dir', required=True, help='layout输出目录')
p_full.add_argument('--asset-output-dir', help='资产输出目录(可选)')
p_full.add_argument('--force', action='store_true', help='强制覆盖')
args = parser.parse_args()
if args.command == 'analyze':
cmd_analyze(args)
elif args.command == 'normalize':
cmd_normalize(args)
elif args.command == 'bake-assets':
cmd_bake_assets(args)
elif args.command == 'full':
cmd_full_normalize(args)
else:
parser.print_help()
if __name__ == '__main__':
main()