""" Postprocess 可见体素投影结果。 Usage 示例: # 后处理并可视化生成视频 python postprocess.py \ --data-dir "blender_projects/Hip Hop Dancing/voxel_export_data" \ --visualize 常用参数: --data-dir 包含 metadata.json 和 rendered/visible_voxel_ids.npz 的目录(必填) --visible-npz 可见体素 npz 路径(默认:/rendered/visible_voxel_ids.npz) --output 输出的 postprocess 结果 .npy 路径(默认:/processed/visible_voxels.npy) --visualize 是否根据 .npy 渲染视频 --output-video 输出视频路径(默认:/processed/visible_voxels.mp4) --fps 视频帧率(默认:24) """ import argparse import json import math from pathlib import Path import imageio.v3 as iio import numpy as np WORLD_RADIUS_MODE = "half_size" # or "half_diagonal" USE_DEPTH_OCCLUSION = True MIN_DRAW_RADIUS = 1 MAX_DRAW_RADIUS = 100 FIRST_FRAME_COLOR_VALID_DEPTH_EPS = 1e-6 def parse_args(): p = argparse.ArgumentParser(description="Postprocess visible voxel data into screen-space representation") p.add_argument("--data-dir", type=str, required=True, help="Directory containing metadata.json and voxel data") p.add_argument("--visible-npz", type=str, default=None, help="Path to visible_voxel_ids .npz (default: /rendered/visible_voxel_ids.npz)") p.add_argument("--output", type=str, default=None, help="Output .npy path (default: /rendered/visible_voxels.npy)") p.add_argument("--visualize", action="store_true", help="Render visualization video after postprocessing") p.add_argument("--output-video", type=str, default=None, help="Output video path (default: /rendered/visible_voxels.mp4)") p.add_argument("--fps", type=int, default=24, help="Video frame rate (default: 24)") return p.parse_args() # --------------------------- camera / metadata --------------------------- def compute_intrinsics(intr: dict): focal = intr["focal_length"] sw, sh = intr["sensor_width"], intr["sensor_height"] res_x, res_y = intr["resolution_x"], intr["resolution_y"] fit = intr.get("sensor_fit", "AUTO") if fit == "VERTICAL": fpx = focal / sh * res_y elif fit == "HORIZONTAL": fpx = focal / sw * res_x else: fpx = focal / sw * res_x if res_x >= res_y else focal / sh * res_y fx = fy = float(fpx) cx = float(res_x) / 2.0 cy = float(res_y) / 2.0 return fx, fy, cx, cy def normalize_camera_extrinsics(cam_extrinsics): cam_mat = np.array(cam_extrinsics, dtype=np.float32) scale = np.linalg.norm(cam_mat[:3, 0]) if abs(scale - 1.0) > 1e-6: cam_mat[:3, :3] /= scale return cam_mat def load_metadata(data_dir: Path): with open(data_dir / "metadata.json", "r", encoding="utf-8") as f: return json.load(f) def load_camera_list(metadata): cams = [] for fr in metadata["frames"]: intr = fr["camera_intrinsics"] fx, fy, cx, cy = compute_intrinsics(intr) cam_mat = normalize_camera_extrinsics(fr["camera_extrinsics"]) cams.append((cam_mat, fx, fy, cx, cy)) return cams # --------------------------- id / radius helpers --------------------------- def build_object_id_ranges(metadata, data_dir: Path): obj_info = metadata["objects_info"] obj_names = list(obj_info.keys()) static_path = data_dir / metadata.get("static_data_file", "static.npz") static_npz = np.load(static_path) if static_path.exists() else None frame0_path = data_dir / metadata["frames"][0]["data_file"] frame0_npz = np.load(frame0_path) object_ranges = {} next_id = 1 for name in obj_names: if static_npz is not None and name in static_npz: n = int(static_npz[name].shape[0]) elif name in frame0_npz: n = int(frame0_npz[name].shape[0]) else: n = 0 start_id = next_id end_id = next_id + n - 1 object_ranges[name] = { "start_id": start_id, "end_id": end_id, "count": n, "voxel_size": float(obj_info[name]["voxel_size"]), } next_id += n if static_npz is not None: static_npz.close() frame0_npz.close() return object_ranges, next_id - 1 def build_id_to_radius_world(object_ranges, max_id): id_to_radius = np.zeros(max_id + 1, dtype=np.float32) for _, info in object_ranges.items(): s = int(info["start_id"]) e = int(info["end_id"]) if e < s: continue voxel_size = float(info["voxel_size"]) if WORLD_RADIUS_MODE == "half_diagonal": r_world = 0.5 * math.sqrt(3.0) * voxel_size else: r_world = 0.5 * voxel_size id_to_radius[s:e + 1] = r_world return id_to_radius # --------------------------- geometry / projection --------------------------- def world_to_camera(points_world, cam_extrinsics): view_mat = np.linalg.inv(cam_extrinsics) pts_h = np.concatenate( [points_world.astype(np.float32), np.ones((len(points_world), 1), dtype=np.float32)], axis=1, ) pos_view = (view_mat @ pts_h.T).T[:, :3] return pos_view def project_frame(points_world, cam_extrinsics, fx, fy, cx, cy): pos_view = world_to_camera(points_world, cam_extrinsics) z = -pos_view[:, 2] px_x = fx * pos_view[:, 0] / z + cx px_y = cy - fy * pos_view[:, 1] / z return px_x, px_y, z # --------------------------- color helpers --------------------------- def hsv_to_bgr_uint8(h, s=0.85, v=0.95): h = float(h % 1.0) s = float(np.clip(s, 0.0, 1.0)) v = float(np.clip(v, 0.0, 1.0)) i = int(h * 6.0) f = h * 6.0 - i p = v * (1.0 - s) q = v * (1.0 - f * s) t = v * (1.0 - (1.0 - f) * s) i = i % 6 if i == 0: r, g, b = v, t, p elif i == 1: r, g, b = q, v, p elif i == 2: r, g, b = p, v, t elif i == 3: r, g, b = p, q, v elif i == 4: r, g, b = t, p, v else: r, g, b = v, p, q return np.array([b, g, r], dtype=np.float32) * 255.0 def build_colors_from_first_frame(voxels, visibility): """ Assign a fixed BGR color to every compact voxel index based on its first-frame (x, y, z). The first frame here means t=0. If a voxel is not visible in frame 0, keep it black. """ T, N, _ = voxels.shape colors = np.zeros((N, 3), dtype=np.uint8) base_pts = voxels[0].copy() valid = visibility[0] > 0 if not np.any(valid): return colors pts = base_pts[valid] x = pts[:, 0] y = pts[:, 1] z = pts[:, 2] def normalize(arr): amin = float(arr.min()) amax = float(arr.max()) if amax - amin < 1e-8: return np.zeros_like(arr, dtype=np.float32) return ((arr - amin) / (amax - amin)).astype(np.float32) xn = normalize(x) yn = normalize(y) zn = normalize(z) hue = (0.55 * xn + 0.30 * yn + 0.15 * zn) % 1.0 sat = 0.65 + 0.30 * (1.0 - zn) val = 0.75 + 0.20 * yn valid_idx = np.where(valid)[0] for local_i, global_i in enumerate(valid_idx): bgr = hsv_to_bgr_uint8(hue[local_i], sat[local_i], val[local_i]) colors[global_i] = np.clip(np.round(bgr), 0, 255).astype(np.uint8) return colors def build_colors_from_seg(voxels_segIDs): """ Assign one stable random BGR color per segment id. seg id 0 is reserved as unknown/background and stays black. """ seg_ids = np.asarray(voxels_segIDs, dtype=np.uint32).reshape(-1) colors = np.zeros((len(seg_ids), 3), dtype=np.uint8) if len(seg_ids) == 0: return colors unique_seg = np.unique(seg_ids) for seg in unique_seg: # Stable random per segment id, independent of global RNG state. rng = np.random.default_rng(int(seg)) colors[seg_ids == seg] = rng.integers(0, 256, size=3, dtype=np.uint8) return colors # --------------------------- postprocess --------------------------- def postprocess_visible_voxels(data_dir, visible_npz_path, out_path, verbose=False): data_dir = Path(data_dir) visible_npz_path = Path(visible_npz_path) out_path = Path(out_path) metadata = load_metadata(data_dir) cams = load_camera_list(metadata) T = len(cams) vis_npz = np.load(visible_npz_path, allow_pickle=False) frame_ids_keys = sorted(k for k in vis_npz.files if k.endswith("_ids")) frame_pos_keys = sorted(k for k in vis_npz.files if k.endswith("_pos")) if len(frame_ids_keys) != T or len(frame_pos_keys) != T: raise RuntimeError( f"Mismatch: metadata has {T} frames, but npz has {len(frame_ids_keys)} id frames and {len(frame_pos_keys)} pos frames." ) all_ids = np.unique(np.concatenate([vis_npz[k].astype(np.uint32) for k in frame_ids_keys], axis=0)).astype(np.uint32) N = len(all_ids) id_to_compact = {int(raw_id): i for i, raw_id in enumerate(all_ids.tolist())} object_ranges, max_id = build_object_id_ranges(metadata, data_dir) id_to_radius_world = build_id_to_radius_world(object_ranges, max_id) # voxels stores screen coordinates (x, y, z_depth), not world coordinates. voxels = np.zeros((T, N, 3), dtype=np.float32) visibility = np.zeros((T, N), dtype=np.float32) voxels_radius = np.zeros((T, N), dtype=np.float32) voxels_segIDs = np.zeros(N, dtype=np.uint32) for t in range(T): frame_tag = f"frame_{t+1:04d}" ids = vis_npz[f"{frame_tag}_ids"].astype(np.uint32) pos_world = vis_npz[f"{frame_tag}_pos"].astype(np.float32) seg_key = f"{frame_tag}_segment" seg_ids = vis_npz[seg_key].astype(np.uint32) if seg_key in vis_npz.files else None if len(ids) != len(pos_world): raise RuntimeError(f"{frame_tag}: ids len {len(ids)} != pos len {len(pos_world)}") if seg_ids is not None and len(seg_ids) != len(ids): raise RuntimeError(f"{frame_tag}: segment len {len(seg_ids)} != ids len {len(ids)}") if len(ids) == 0: continue compact_idx = np.array([id_to_compact[int(i)] for i in ids], dtype=np.int64) visibility[t, compact_idx] = 1.0 if seg_ids is not None: prev = voxels_segIDs[compact_idx] # Keep a stable per-voxel segment id across frames; fill unknown slots first. voxels_segIDs[compact_idx] = np.where(prev == 0, seg_ids, prev).astype(np.uint32) cam_mat, fx, fy, cx, cy = cams[t] px_x, px_y, z = project_frame(pos_world, cam_mat, fx, fy, cx, cy) z = np.maximum(z, FIRST_FRAME_COLOR_VALID_DEPTH_EPS) voxels[t, compact_idx, 0] = px_x.astype(np.float32) voxels[t, compact_idx, 1] = px_y.astype(np.float32) voxels[t, compact_idx, 2] = z.astype(np.float32) r_world = id_to_radius_world[ids] r_px = fy * r_world / z voxels_radius[t, compact_idx] = np.maximum(r_px, 0.0).astype(np.float32) if verbose: print(f"[frame {t+1:04d}] visible={len(ids)}") point_colors_bgr = build_colors_from_first_frame(voxels, visibility) result = { "voxels": voxels, "visibility": visibility, "voxels_radius": voxels_radius, "voxels_segIDs": voxels_segIDs, } out_path.parent.mkdir(parents=True, exist_ok=True) np.save(out_path, result) vis_per_frame = visibility.sum(axis=1) r_vis = voxels_radius[visibility > 0] if verbose: print(f"[done] saved -> {out_path}") print(f" voxels : {voxels.shape} (screen x, y, z)") print(f" visibility : {visibility.shape}") print(f" voxels_radius : {voxels_radius.shape}") print(f" voxels_segIDs : {voxels_segIDs.shape}") print(f" point_colors_bgr : {point_colors_bgr.shape}") print(f" all_ids : {all_ids.shape}, min={all_ids.min()}, max={all_ids.max()}") print(f" visible/frame : min={vis_per_frame.min():.0f} max={vis_per_frame.max():.0f} mean={vis_per_frame.mean():.1f}") if r_vis.size: print(f" radius px : min={r_vis.min():.2f} max={r_vis.max():.2f} mean={r_vis.mean():.2f}") vis_npz.close() return result # --------------------------- visualization --------------------------- def rasterize_disks(xs, ys, depths, radii, colors_bgr, W, H, use_depth=USE_DEPTH_OCCLUSION): canvas = np.zeros((H, W, 3), dtype=np.uint8) if len(xs) == 0: return canvas if use_depth: occ = np.full((H, W), np.inf, dtype=np.float32) order = np.argsort(depths)[::-1] # far -> near else: occ = None order = range(len(xs)) yy_grid_cache = {} xx_grid_cache = {} for idx in order: x = int(round(float(xs[idx]))) y = int(round(float(ys[idx]))) d = float(depths[idx]) r = int(max(MIN_DRAW_RADIUS, min(MAX_DRAW_RADIUS, round(float(radii[idx]))))) if d <= 0: continue x0 = max(x - r, 0) x1 = min(x + r + 1, W) y0 = max(y - r, 0) y1 = min(y + r + 1, H) if x0 >= x1 or y0 >= y1: continue h = y1 - y0 w = x1 - x0 key = (h, w) if key not in yy_grid_cache: yy, xx = np.ogrid[:h, :w] yy_grid_cache[key] = yy xx_grid_cache[key] = xx yy = yy_grid_cache[key] xx = xx_grid_cache[key] mask = (xx + x0 - x) ** 2 + (yy + y0 - y) ** 2 <= r * r if use_depth: sub_occ = occ[y0:y1, x0:x1] update = mask & (d < sub_occ) if not np.any(update): continue sub_canvas = canvas[y0:y1, x0:x1] sub_canvas[update] = colors_bgr[idx] sub_occ[update] = d else: sub_canvas = canvas[y0:y1, x0:x1] sub_canvas[mask] = colors_bgr[idx] return canvas def render_video_from_postprocessed( postprocessed, metadata_path, out_video, fps=24, mode="first_color", use_depth=USE_DEPTH_OCCLUSION, ): if isinstance(postprocessed, (str, Path)): pp = np.load(postprocessed, allow_pickle=True).item() else: pp = postprocessed voxels = pp["voxels"] visibility = pp["visibility"] voxels_radius = pp["voxels_radius"] voxels_segIDs = pp["voxels_segIDs"] if mode == "first_color": point_colors_bgr = build_colors_from_first_frame(voxels, visibility) else: point_colors_bgr = build_colors_from_seg(voxels_segIDs) with open(metadata_path, "r", encoding="utf-8") as f: metadata = json.load(f) frames = metadata["frames"] W = int(frames[0]["camera_intrinsics"]["resolution_x"]) H = int(frames[0]["camera_intrinsics"]["resolution_y"]) T = len(frames) if voxels.shape[0] != T: raise RuntimeError(f"postprocessed T={voxels.shape[0]} but metadata T={T}") out_video = Path(out_video) out_video.parent.mkdir(parents=True, exist_ok=True) frames_list = [] for t in range(T): vis_mask = visibility[t] > 0 pts = voxels[t, vis_mask] # already screen x,y,z rad = voxels_radius[t, vis_mask] cols = point_colors_bgr[vis_mask] if len(pts) == 0: canvas = np.zeros((H, W, 3), dtype=np.uint8) frames_list.append(canvas) print(f"[frame {t+1:04d}] 0 visible voxels") continue px_x = pts[:, 0] px_y = pts[:, 1] depth = pts[:, 2] valid = ( (depth > 0) & (px_x >= 0) & (px_x < W) & (px_y >= 0) & (px_y < H) & (rad > 0) ) canvas = rasterize_disks( px_x[valid], px_y[valid], depth[valid].astype(np.float32), rad[valid].astype(np.float32), cols[valid], W, H, use_depth=use_depth, ) frames_list.append(canvas) print(f"[frame {t+1:04d}] plotted={int(valid.sum())}") if frames_list: stack = np.stack(frames_list, axis=0) iio.imwrite(str(out_video), stack, fps=fps) print(f"[done] saved video -> {out_video}") # --------------------------- CLI --------------------------- def main(): args = parse_args() data_dir = Path(args.data_dir) rendered_dir = data_dir / "rendered" processed_dir = data_dir / "processed" visible_npz = Path(args.visible_npz) if args.visible_npz else rendered_dir / "visible_voxel_ids.npz" out_npy = Path(args.output) if args.output else processed_dir / "visible_voxels.npy" out_video = Path(args.output_video) if args.output_video else processed_dir / "visible_voxels.mp4" result = postprocess_visible_voxels(data_dir, visible_npz, out_npy) if args.visualize: render_video_from_postprocessed( result, metadata_path=data_dir / "metadata.json", out_video=out_video, fps=args.fps, # mode="seg" ) if __name__ == "__main__": main()