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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy
|
| 2 |
+
import trimesh
|
| 3 |
+
import trimesh.sample
|
| 4 |
+
import trimesh.visual
|
| 5 |
+
import trimesh.proximity
|
| 6 |
+
import objaverse
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import matplotlib.pyplot as plotlib
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_bytes(x: str):
|
| 13 |
+
import io, requests
|
| 14 |
+
return io.BytesIO(requests.get(x).content)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_image(x: str):
|
| 18 |
+
try:
|
| 19 |
+
return plotlib.imread(get_bytes(x), 'auto')
|
| 20 |
+
except Exception:
|
| 21 |
+
raise ValueError("Invalid image", x)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def model_to_pc(mesh: trimesh.Trimesh, n_sample_points=10000):
|
| 25 |
+
f32 = numpy.float32
|
| 26 |
+
rad = numpy.sqrt(mesh.area / (3 * n_sample_points))
|
| 27 |
+
for _ in range(24):
|
| 28 |
+
pcd, face_idx = trimesh.sample.sample_surface_even(mesh, n_sample_points, rad)
|
| 29 |
+
rad *= 0.85
|
| 30 |
+
if len(pcd) == n_sample_points:
|
| 31 |
+
break
|
| 32 |
+
else:
|
| 33 |
+
raise ValueError("Bad geometry, cannot finish sampling.", mesh.area)
|
| 34 |
+
if isinstance(mesh.visual, trimesh.visual.ColorVisuals):
|
| 35 |
+
rgba = mesh.visual.face_colors[face_idx]
|
| 36 |
+
elif isinstance(mesh.visual, trimesh.visual.TextureVisuals):
|
| 37 |
+
bc = trimesh.proximity.points_to_barycentric(mesh.triangles[face_idx], pcd)
|
| 38 |
+
if mesh.visual.uv is None or len(mesh.visual.uv) < mesh.faces[face_idx].max():
|
| 39 |
+
uv = numpy.zeros([len(bc), 2])
|
| 40 |
+
st.warning("Invalid UV, filling with zeroes")
|
| 41 |
+
else:
|
| 42 |
+
uv = numpy.einsum('ntc,nt->nc', mesh.visual.uv[mesh.faces[face_idx]], bc)
|
| 43 |
+
material = mesh.visual.material
|
| 44 |
+
if hasattr(material, 'materials'):
|
| 45 |
+
if len(material.materials) == 0:
|
| 46 |
+
rgba = numpy.ones_like(pcd) * 0.8
|
| 47 |
+
texture = None
|
| 48 |
+
st.warning("Empty MultiMaterial found, falling back to light grey")
|
| 49 |
+
else:
|
| 50 |
+
material = material.materials[0]
|
| 51 |
+
if hasattr(material, 'image'):
|
| 52 |
+
texture = material.image
|
| 53 |
+
if texture is None:
|
| 54 |
+
rgba = numpy.zeros([len(uv), len(material.main_color)]) + material.main_color
|
| 55 |
+
elif hasattr(material, 'baseColorTexture'):
|
| 56 |
+
texture = material.baseColorTexture
|
| 57 |
+
if texture is None:
|
| 58 |
+
rgba = numpy.zeros([len(uv), len(material.main_color)]) + material.main_color
|
| 59 |
+
else:
|
| 60 |
+
texture = None
|
| 61 |
+
rgba = numpy.ones_like(pcd) * 0.8
|
| 62 |
+
st.warning("Unknown material, falling back to light grey")
|
| 63 |
+
if texture is not None:
|
| 64 |
+
rgba = trimesh.visual.uv_to_interpolated_color(uv, texture)
|
| 65 |
+
if rgba.max() > 1:
|
| 66 |
+
if rgba.max() > 255:
|
| 67 |
+
rgba = rgba.astype(f32) / rgba.max()
|
| 68 |
+
else:
|
| 69 |
+
rgba = rgba.astype(f32) / 255.0
|
| 70 |
+
return numpy.concatenate([numpy.array(pcd, f32), numpy.array(rgba, f32)[:, :3]], axis=-1)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def trimesh_to_pc(scene_or_mesh):
|
| 74 |
+
if isinstance(scene_or_mesh, trimesh.Scene):
|
| 75 |
+
meshes = []
|
| 76 |
+
for node_name in scene_or_mesh.graph.nodes_geometry:
|
| 77 |
+
# which geometry does this node refer to
|
| 78 |
+
transform, geometry_name = scene_or_mesh.graph[node_name]
|
| 79 |
+
|
| 80 |
+
# get the actual potential mesh instance
|
| 81 |
+
geometry = scene_or_mesh.geometry[geometry_name].copy()
|
| 82 |
+
if not hasattr(geometry, 'triangles'):
|
| 83 |
+
continue
|
| 84 |
+
geometry: trimesh.Trimesh
|
| 85 |
+
geometry = geometry.apply_transform(transform)
|
| 86 |
+
meshes.append(geometry)
|
| 87 |
+
total_area = sum(geometry.area for geometry in meshes)
|
| 88 |
+
if total_area < 1e-6:
|
| 89 |
+
raise ValueError("Bad geometry: total area too small (< 1e-6)")
|
| 90 |
+
pcs = []
|
| 91 |
+
for geometry in meshes:
|
| 92 |
+
pcs.append(model_to_pc(geometry, max(1, round(geometry.area / total_area * 10000))))
|
| 93 |
+
if not len(pcs):
|
| 94 |
+
raise ValueError("Unsupported mesh object: no triangles found")
|
| 95 |
+
return numpy.concatenate(pcs)
|
| 96 |
+
else:
|
| 97 |
+
assert isinstance(scene_or_mesh, trimesh.Trimesh)
|
| 98 |
+
return model_to_pc(scene_or_mesh, 10000)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def input_3d_shape(key=None):
|
| 102 |
+
if key is None:
|
| 103 |
+
objaid_key = model_key = npy_key = swap_key = None
|
| 104 |
+
else:
|
| 105 |
+
objaid_key = key + "_objaid"
|
| 106 |
+
model_key = key + "_model"
|
| 107 |
+
npy_key = key + "_npy"
|
| 108 |
+
swap_key = key + "_swap"
|
| 109 |
+
objaid = st.text_input("Enter an Objaverse ID", key=objaid_key)
|
| 110 |
+
model = st.file_uploader("Or upload a model (.glb/.obj/.ply)", key=model_key)
|
| 111 |
+
npy = st.file_uploader("Or upload a point cloud numpy array (.npy of Nx3 XYZ or Nx6 XYZRGB)", key=npy_key)
|
| 112 |
+
swap_yz_axes = st.radio("Gravity", ["Y is up (for most Objaverse shapes)", "Z is up"], key=swap_key) == "Z is up"
|
| 113 |
+
f32 = numpy.float32
|
| 114 |
+
|
| 115 |
+
def load_data(prog):
|
| 116 |
+
# load the model
|
| 117 |
+
prog.progress(0.05, "Preparing Point Cloud")
|
| 118 |
+
if npy is not None:
|
| 119 |
+
pc: numpy.ndarray = numpy.load(npy)
|
| 120 |
+
elif model is not None:
|
| 121 |
+
pc = trimesh_to_pc(trimesh.load(model, model.name.split(".")[-1]))
|
| 122 |
+
elif objaid:
|
| 123 |
+
prog.progress(0.1, "Downloading Objaverse Object")
|
| 124 |
+
objamodel = objaverse.load_objects([objaid])[objaid]
|
| 125 |
+
prog.progress(0.2, "Preparing Point Cloud")
|
| 126 |
+
pc = trimesh_to_pc(trimesh.load(objamodel))
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError("You have to supply 3D input!")
|
| 129 |
+
prog.progress(0.25, "Preprocessing Point Cloud")
|
| 130 |
+
assert pc.ndim == 2, "invalid pc shape: ndim = %d != 2" % pc.ndim
|
| 131 |
+
assert pc.shape[1] in [3, 6], "invalid pc shape: should have 3/6 channels, got %d" % pc.shape[1]
|
| 132 |
+
pc = pc.astype(f32)
|
| 133 |
+
if swap_yz_axes:
|
| 134 |
+
pc[:, [1, 2]] = pc[:, [2, 1]]
|
| 135 |
+
pc[:, :3] = pc[:, :3] - numpy.mean(pc[:, :3], axis=0)
|
| 136 |
+
pc[:, :3] = pc[:, :3] / numpy.linalg.norm(pc[:, :3], axis=-1).max()
|
| 137 |
+
if pc.shape[1] == 3:
|
| 138 |
+
pc = numpy.concatenate([pc, numpy.ones_like(pc) * 0.4], axis=-1)
|
| 139 |
+
prog.progress(0.27, "Normalized Point Cloud")
|
| 140 |
+
if pc.shape[0] >= 10000:
|
| 141 |
+
pc = pc[numpy.random.permutation(len(pc))[:10000]]
|
| 142 |
+
elif pc.shape[0] == 0:
|
| 143 |
+
raise ValueError("Got empty point cloud!")
|
| 144 |
+
elif pc.shape[0] < 10000:
|
| 145 |
+
pc = numpy.concatenate([pc, pc[numpy.random.randint(len(pc), size=[10000 - len(pc)])]])
|
| 146 |
+
prog.progress(0.3, "Preprocessed Point Cloud")
|
| 147 |
+
return pc.astype(f32)
|
| 148 |
+
|
| 149 |
+
return load_data
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def render_pc(pc):
|
| 153 |
+
rand = numpy.random.permutation(len(pc))[:2048]
|
| 154 |
+
pc = pc[rand]
|
| 155 |
+
rgb = (pc[:, 3:] * 255).astype(numpy.uint8)
|
| 156 |
+
g = go.Scatter3d(
|
| 157 |
+
x=pc[:, 0], y=pc[:, 1], z=pc[:, 2],
|
| 158 |
+
mode='markers',
|
| 159 |
+
marker=dict(size=2, color=[f'rgb({rgb[i, 0]}, {rgb[i, 1]}, {rgb[i, 2]})' for i in range(len(pc))]),
|
| 160 |
+
)
|
| 161 |
+
fig = go.Figure(data=[g])
|
| 162 |
+
fig.update_layout(scene_camera=dict(up=dict(x=0, y=1, z=0)))
|
| 163 |
+
fig.update_scenes(aspectmode="data")
|
| 164 |
+
col1, col2 = st.columns(2)
|
| 165 |
+
with col1:
|
| 166 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 167 |
+
# st.caption("Point Cloud Preview")
|
| 168 |
+
return col2
|