File size: 6,305 Bytes
08bae87 | 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 | """
Render preview images of point clouds and meshes using matplotlib (no GLU needed).
Creates multi-view renders (front, side, top, iso) for each part.
"""
import os
import sys
import glob
import numpy as np
import trimesh
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
RESULTS_DIR = "data/mast3r_results"
PREVIEW_ANGLES = [
("front", 30, -60),
("side", 30, 30),
("top", 90, 0),
("iso", 20, 45),
]
def render_pointcloud(ax, pts, colors, title=""):
"""Render a point cloud on a 3D matplotlib axis."""
# Subsample if too many points
n = len(pts)
if n > 50000:
idx = np.random.RandomState(42).choice(n, 50000, replace=False)
pts = pts[idx]
colors = colors[idx]
ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2],
c=colors / 255.0, s=0.1, marker=".")
ax.set_title(title, fontsize=8)
def render_mesh(ax, verts, faces, title=""):
"""Render a mesh on a 3D matplotlib axis using Poly3DCollection."""
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# Subsample faces if too many
if len(faces) > 20000:
idx = np.random.RandomState(42).choice(len(faces), 20000, replace=False)
faces = faces[idx]
triangles = verts[faces]
collection = Poly3DCollection(triangles, alpha=0.8, linewidths=0)
collection.set_facecolor([0.7, 0.7, 0.75, 0.9])
collection.set_edgecolor([0.3, 0.3, 0.35, 0.3])
ax.add_collection3d(collection)
ax.set_title(title, fontsize=8)
def setup_ax(ax, verts, elev, azim):
"""Configure 3D axis bounds and view angle."""
mins = verts.min(0)
maxs = verts.max(0)
center = (mins + maxs) / 2
extent = (maxs - mins).max() / 2 * 1.1
ax.set_xlim(center[0] - extent, center[0] + extent)
ax.set_ylim(center[1] - extent, center[1] + extent)
ax.set_zlim(center[2] - extent, center[2] + extent)
ax.view_init(elev=elev, azim=azim)
ax.set_box_aspect([1, 1, 1])
ax.set_axis_off()
def render_part_previews(part):
part_dir = os.path.join(RESULTS_DIR, part)
if not os.path.isdir(part_dir):
return
preview_dir = os.path.join(part_dir, "previews")
os.makedirs(preview_dir, exist_ok=True)
print(f"\n=== Rendering previews for {part} ===")
# Load point cloud
pc_path = os.path.join(part_dir, "pointcloud.ply")
pc = None
if os.path.exists(pc_path):
pc = trimesh.load(pc_path)
print(f" Point cloud: {len(pc.vertices)} points")
# Load meshes
meshes = {}
for f in sorted(os.listdir(part_dir)):
if f.endswith("_poisson.ply"):
m = trimesh.load(os.path.join(part_dir, f))
meshes["poisson"] = m
print(f" Poisson mesh: {len(m.vertices)} verts, {len(m.faces)} faces")
elif f.endswith("_ballpivoting.ply"):
m = trimesh.load(os.path.join(part_dir, f))
meshes["ballpivoting"] = m
print(f" Ball-pivoting mesh: {len(m.vertices)} verts, {len(m.faces)} faces")
# --- Render point cloud from 4 angles ---
if pc is not None:
fig = plt.figure(figsize=(16, 4), dpi=100)
for i, (name, elev, azim) in enumerate(PREVIEW_ANGLES):
ax = fig.add_subplot(1, 4, i + 1, projection="3d")
colors = pc.colors if hasattr(pc, "colors") and pc.colors is not None else np.tile([128, 128, 128], (len(pc.vertices), 1))
render_pointcloud(ax, np.array(pc.vertices), np.array(colors), f"PC - {name}")
setup_ax(ax, np.array(pc.vertices), elev, azim)
plt.suptitle(f"{part} - Point Cloud (MASt3R reconstruction)", fontsize=12)
plt.tight_layout()
path = os.path.join(preview_dir, f"{part}_pointcloud_all.png")
plt.savefig(path, bbox_inches="tight", facecolor="white")
plt.close()
print(f" Saved: {path}")
# Individual views
for name, elev, azim in PREVIEW_ANGLES:
fig = plt.figure(figsize=(6, 5), dpi=100)
ax = fig.add_subplot(111, projection="3d")
colors = pc.colors if hasattr(pc, "colors") and pc.colors is not None else np.tile([128, 128, 128], (len(pc.vertices), 1))
render_pointcloud(ax, np.array(pc.vertices), np.array(colors), f"{name}")
setup_ax(ax, np.array(pc.vertices), elev, azim)
plt.tight_layout()
path = os.path.join(preview_dir, f"{part}_pc_{name}.png")
plt.savefig(path, bbox_inches="tight", facecolor="white")
plt.close()
print(f" Saved: {path}")
# --- Render meshes from 4 angles ---
for mesh_name, mesh in meshes.items():
verts = np.array(mesh.vertices)
faces = np.array(mesh.faces)
# Combined 4-view
fig = plt.figure(figsize=(16, 4), dpi=100)
for i, (name, elev, azim) in enumerate(PREVIEW_ANGLES):
ax = fig.add_subplot(1, 4, i + 1, projection="3d")
render_mesh(ax, verts, faces, f"{mesh_name} - {name}")
setup_ax(ax, verts, elev, azim)
plt.suptitle(f"{part} - {mesh_name} Mesh", fontsize=12)
plt.tight_layout()
path = os.path.join(preview_dir, f"{part}_{mesh_name}_all.png")
plt.savefig(path, bbox_inches="tight", facecolor="white")
plt.close()
print(f" Saved: {path}")
# Individual views
for name, elev, azim in PREVIEW_ANGLES:
fig = plt.figure(figsize=(6, 5), dpi=100)
ax = fig.add_subplot(111, projection="3d")
render_mesh(ax, verts, faces, f"{mesh_name} - {name}")
setup_ax(ax, verts, elev, azim)
plt.tight_layout()
path = os.path.join(preview_dir, f"{part}_{mesh_name}_{name}.png")
plt.savefig(path, bbox_inches="tight", facecolor="white")
plt.close()
print(f" Saved: {path}")
def main():
parts = sorted([d for d in os.listdir(RESULTS_DIR) if os.path.isdir(os.path.join(RESULTS_DIR, d))])
for part in parts:
try:
render_part_previews(part)
except Exception as e:
import traceback
traceback.print_exc()
print(f" FAILED for {part}: {e}")
print("\nDone rendering previews.")
if __name__ == "__main__":
main()
|