File size: 6,762 Bytes
b004d6f | 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 | # -*- coding: utf-8 -*-
"""
将标注文件 (semantic.npy) 转换为带语义标签的PLY点云真值
基于 visualize_semantic_labels.py 的标注逻辑
"""
import os
import glob
import numpy as np
import cv2
import yaml
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
import multiprocessing
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
def load_config(config_path=None):
if config_path is None:
config_path = os.path.join(SCRIPT_DIR, 'config.yaml')
with open(config_path, 'r', encoding='utf-8') as f:
return yaml.safe_load(f)
CONFIG = load_config()
# 相机和深度参数
IMG_H, IMG_W = 192, 256
BIN_TO_M = 299_792_458.0 * CONFIG['common']['dt_ps'] * 1e-12 / 2.0
def save_ply_with_label(pts, path):
"""保存带语义标签的PLY文件: x y z label"""
with open(path, "wb") as f:
header = f"ply\nformat ascii 1.0\nelement vertex {len(pts)}\n"
header += "property float x\nproperty float y\nproperty float z\nproperty int label\nend_header\n"
f.write(header.encode())
np.savetxt(f, pts, fmt='%.6f %.6f %.6f %d')
def process_single_ann(args):
"""处理单个标注文件,转换为PLY点云"""
npy_path, cam_config, out_dir = args
# 从文件名提取基础名 (去掉 _semantic.npy)
basename = os.path.basename(npy_path)
if basename.endswith('_semantic.npy'):
basename = basename[:-13] # 去掉 '_semantic.npy'
out_path = os.path.join(out_dir, f"{basename}_gt.ply")
try:
# 加载标注数据 (H*W, num_bins)
sem_bins = np.load(npy_path)
num_pos, num_bins = sem_bins.shape
# 预计算相机参数
K = np.array([[cam_config['fx'], 0, cam_config['cx']],
[0, cam_config['fy'], cam_config['cy']],
[0, 0, 1]], dtype=np.float64)
D = np.array([cam_config['k1'], cam_config['k2'], cam_config['p1'], cam_config['p2']], dtype=np.float64)
points = []
# 遍历每个像素,提取标注的峰值
for idx in range(num_pos):
row = sem_bins[idx]
nz = np.flatnonzero(row > 0) # 找到有标注的bin
if nz.size == 0:
continue
# 找到连续的标注段
breaks = np.flatnonzero(np.diff(nz) != 1)
run_starts = np.concatenate(([0], breaks + 1))
run_ends = np.concatenate((breaks, [nz.size - 1]))
for rs, re in zip(run_starts, run_ends):
b0 = int(nz[rs])
b1 = int(nz[re])
cid = int(row[b0]) # 语义类别
if cid <= 0:
continue
# 使用标注段的中心bin作为深度
peak_bin = (b0 + b1) // 2
depth = peak_bin * BIN_TO_M
# 深度范围过滤
if depth < CONFIG['common']['min_range_m'] or depth > CONFIG['common']['max_range_m']:
continue
# 计算3D坐标
v, u = idx // IMG_W, idx % IMG_W
if CONFIG['common']['undistort']:
uv = np.array([[[u, v]]], dtype=np.float32)
uv_norm = cv2.undistortPoints(uv, K, D)
x_n, y_n = uv_norm[0, 0, 0], uv_norm[0, 0, 1]
else:
x_n = (u - cam_config['cx']) / cam_config['fx']
y_n = (v - cam_config['cy']) / cam_config['fy']
if CONFIG['common']['depth_is_range']:
ray = np.array([x_n, y_n, 1.0])
ray_unit = ray / np.linalg.norm(ray)
xyz = ray_unit * depth
else:
xyz = np.array([x_n * depth, y_n * depth, depth])
points.append([xyz[0], xyz[1], xyz[2], cid])
if len(points) == 0:
return basename, False, 0
pts = np.array(points, dtype=np.float32)
pts[:, 3] = pts[:, 3].astype(np.int32) # 确保label是整数
save_ply_with_label(pts, out_path)
return basename, True, len(pts)
except Exception as e:
print(f"Error processing {npy_path}: {e}")
return basename, False, 0
def main():
config = load_config()
datasets = config['datasets']
ann_root = os.path.join(SCRIPT_DIR, 'ann')
output_root = os.path.join(SCRIPT_DIR, 'output_denoised', 'gt')
num_workers = min(config['common'].get('num_workers', 8), multiprocessing.cpu_count())
print(f"[INFO] Converting annotations to PLY ground truth")
print(f"[INFO] Ann root: {ann_root}")
print(f"[INFO] Output root: {output_root}")
print(f"[INFO] Workers: {num_workers}")
# 遍历数据集 (p1, p2)
for dataset_name, cam_config in datasets.items():
dataset_ann_path = os.path.join(ann_root, dataset_name)
if not os.path.isdir(dataset_ann_path):
print(f"[Skip] {dataset_name} not found in ann/")
continue
print(f"\n[Dataset] {dataset_name}")
# 遍历序列目录
seq_dirs = [d for d in os.listdir(dataset_ann_path)
if os.path.isdir(os.path.join(dataset_ann_path, d))]
for seq_name in seq_dirs:
seq_path = os.path.join(dataset_ann_path, seq_name)
out_dir = os.path.join(output_root, seq_name)
os.makedirs(out_dir, exist_ok=True)
# 查找所有标注文件
npy_files = sorted(glob.glob(os.path.join(seq_path, "*_semantic.npy")))
if not npy_files:
continue
# 准备任务
tasks = [(f, cam_config, out_dir) for f in npy_files]
success_count = 0
total_pts = 0
with ProcessPoolExecutor(max_workers=num_workers) as executor:
futures = [executor.submit(process_single_ann, t) for t in tasks]
pbar = tqdm(as_completed(futures), total=len(npy_files),
desc=f" {seq_name}", leave=False)
for future in pbar:
basename, ok, pts_count = future.result()
if ok:
success_count += 1
total_pts += pts_count
print(f" {seq_name}: {success_count}/{len(npy_files)} files, {total_pts:,} pts")
print(f"\n[Done] Ground truth PLY saved to: {output_root}")
if __name__ == "__main__":
main()
|