| |
| """ |
| 将标注文件 (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 |
| |
| |
| basename = os.path.basename(npy_path) |
| if basename.endswith('_semantic.npy'): |
| basename = basename[:-13] |
| |
| out_path = os.path.join(out_dir, f"{basename}_gt.ply") |
| |
| try: |
| |
| 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) |
| 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 |
| |
| |
| 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 |
| |
| |
| 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) |
| 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}") |
| |
| |
| 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() |
|
|