| import argparse |
| import csv |
| import logging |
| import subprocess |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| from image_metrics import CLIPImageMetric, LPIPSMetric, calculate_fid |
|
|
|
|
| SUPPORTED_MODEL_EXTENSIONS = (".obj", ".ply", ".glb", ".gltf", ".fbx", ".stl") |
|
|
|
|
| def configure_logging(output_dir: Path) -> None: |
| output_dir.mkdir(parents=True, exist_ok=True) |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(message)s", |
| handlers=[logging.FileHandler(output_dir / "visual_evaluation.log"), logging.StreamHandler()], |
| ) |
|
|
|
|
| def render_complete(render_dir: Path, num_views: int) -> bool: |
| return all((render_dir / f"{index:03d}.png").exists() for index in range(num_views)) |
|
|
|
|
| def render_model( |
| blender: str, |
| render_script: Path, |
| model_path: Path, |
| output_root: Path, |
| split: str, |
| resolution: int, |
| num_views: int, |
| overwrite: bool, |
| ) -> Path: |
| render_dir = output_root / split / model_path.stem |
| if not overwrite and render_complete(render_dir, num_views): |
| logging.info("Skipping existing render: %s", render_dir) |
| return render_dir |
|
|
| render_dir.mkdir(parents=True, exist_ok=True) |
| command = [ |
| blender, |
| "-b", |
| "-P", |
| str(render_script), |
| "--", |
| "--object", |
| str(model_path), |
| "--output-folder", |
| str(render_dir), |
| "--resolution", |
| str(resolution), |
| "--num-views", |
| str(num_views), |
| ] |
| logging.info("Rendering %s", model_path) |
| subprocess.run(command, check=True) |
| return render_dir |
|
|
|
|
| def compare_render_dirs(gt_dir: Path, pred_dir: Path, lpips_metric: LPIPSMetric, clip_metric: CLIPImageMetric | None, num_views: int) -> dict[str, float]: |
| lpips_values = [] |
| clip_values = [] |
|
|
| for index in range(num_views): |
| gt_image = gt_dir / f"{index:03d}.png" |
| pred_image = pred_dir / f"{index:03d}.png" |
| if not gt_image.exists() or not pred_image.exists(): |
| logging.warning("Missing rendered view %03d for %s or %s", index, gt_dir.name, pred_dir.name) |
| continue |
| lpips_values.append(lpips_metric(gt_image, pred_image)) |
| if clip_metric is not None: |
| clip_values.append(clip_metric(pred_image, gt_image)) |
|
|
| return { |
| "rgb_lpips": float(np.mean(lpips_values)) if lpips_values else np.nan, |
| "clip_score": float(np.mean(clip_values)) if clip_values else np.nan, |
| } |
|
|
|
|
| def find_prediction(gt_path: Path, pred_dir: Path) -> Path | None: |
| for extension in SUPPORTED_MODEL_EXTENSIONS: |
| candidate = pred_dir / f"{gt_path.stem}{extension}" |
| if candidate.exists(): |
| return candidate |
| return None |
|
|
|
|
| def collect_pairs(gt_dir: Path, pred_dir: Path) -> list[tuple[Path, Path]]: |
| pairs = [] |
| for gt_path in sorted(gt_dir.iterdir()): |
| if not gt_path.is_file() or gt_path.suffix.lower() not in SUPPORTED_MODEL_EXTENSIONS: |
| continue |
| pred_path = find_prediction(gt_path, pred_dir) |
| if pred_path is None: |
| logging.warning("No prediction found for %s", gt_path.name) |
| continue |
| pairs.append((gt_path, pred_path)) |
| return pairs |
|
|
|
|
| def save_results(results: list[dict[str, object]], output_dir: Path) -> Path: |
| csv_path = output_dir / "visual_summary.csv" |
| fieldnames = ["model", "prediction", "rgb_lpips", "clip_score", "fid"] |
| with csv_path.open("w", newline="") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) |
| writer.writeheader() |
| for row in results: |
| writer.writerow({key: row.get(key, "") for key in fieldnames}) |
| return csv_path |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| default_render_script = Path(__file__).with_name("render.py") |
| parser = argparse.ArgumentParser(description="Render and evaluate visual similarity between paired 3D models.") |
| parser.add_argument("--gt-dir", type=Path, help="Directory containing ground-truth models.") |
| parser.add_argument("--pred-dir", type=Path, help="Directory containing predicted models with matching stems.") |
| parser.add_argument("--gt-file", type=Path, help="Ground-truth model for single-pair evaluation.") |
| parser.add_argument("--pred-file", type=Path, help="Prediction model for single-pair evaluation.") |
| parser.add_argument("--output-dir", type=Path, required=True, help="Directory for renders and visual_summary.csv.") |
| parser.add_argument("--blender", default="blender", help="Blender executable.") |
| parser.add_argument("--render-script", type=Path, default=default_render_script) |
| parser.add_argument("--resolution", type=int, default=512) |
| parser.add_argument("--num-views", type=int, default=6) |
| parser.add_argument("--lpips-net", choices=("alex", "vgg", "squeeze"), default="alex") |
| parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto") |
| parser.add_argument("--overwrite-renders", action="store_true") |
| parser.add_argument("--skip-clip", action="store_true") |
| parser.add_argument("--skip-fid", action="store_true") |
| parser.add_argument("--fid-batch-size", type=int, default=50) |
| return parser |
|
|
|
|
| def main() -> None: |
| args = build_parser().parse_args() |
| configure_logging(args.output_dir) |
|
|
| if args.gt_dir and args.pred_dir: |
| pairs = collect_pairs(args.gt_dir, args.pred_dir) |
| elif args.gt_file and args.pred_file: |
| pairs = [(args.gt_file, args.pred_file)] |
| else: |
| raise SystemExit("Provide either --gt-dir/--pred-dir or --gt-file/--pred-file.") |
|
|
| if not pairs: |
| raise SystemExit("No valid evaluation pairs were found.") |
|
|
| lpips_metric = LPIPSMetric(net=args.lpips_net, device=args.device) |
| clip_metric = None if args.skip_clip else CLIPImageMetric(device=args.device) |
|
|
| results = [] |
| for gt_path, pred_path in pairs: |
| try: |
| gt_render_dir = render_model( |
| args.blender, |
| args.render_script, |
| gt_path, |
| args.output_dir, |
| "ground_truth", |
| args.resolution, |
| args.num_views, |
| args.overwrite_renders, |
| ) |
| pred_render_dir = render_model( |
| args.blender, |
| args.render_script, |
| pred_path, |
| args.output_dir, |
| "prediction", |
| args.resolution, |
| args.num_views, |
| args.overwrite_renders, |
| ) |
| row = compare_render_dirs(gt_render_dir, pred_render_dir, lpips_metric, clip_metric, args.num_views) |
| row["model"] = gt_path.name |
| row["prediction"] = pred_path.name |
| results.append(row) |
| logging.info("%s: LPIPS=%.6f CLIP=%.6f", gt_path.name, row["rgb_lpips"], row["clip_score"]) |
| except Exception as exc: |
| logging.error("Failed to evaluate %s against %s: %s", gt_path, pred_path, exc) |
|
|
| if not results: |
| raise SystemExit("All visual evaluation pairs failed.") |
|
|
| if not args.skip_fid: |
| fid_value = calculate_fid( |
| args.output_dir / "ground_truth", |
| args.output_dir / "prediction", |
| batch_size=args.fid_batch_size, |
| device=args.device, |
| ) |
| for row in results: |
| row["fid"] = fid_value |
|
|
| csv_path = save_results(results, args.output_dir) |
| logging.info("Results saved to %s", csv_path) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|