Spaces:
Running
on
Zero
Running
on
Zero
Upload 3 files
Browse files- app.py +275 -277
- main.py +17 -22
- mesh_to_pc.py +2 -2
app.py
CHANGED
@@ -1,278 +1,276 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
import
|
10 |
-
import
|
11 |
-
import
|
12 |
-
from
|
13 |
-
from
|
14 |
-
import
|
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 |
-
ax.
|
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 |
-
combined_image
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
vertices =
|
112 |
-
|
113 |
-
pc_coor =
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
mesh.
|
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 |
-
artist_mesh
|
157 |
-
|
158 |
-
artist_mesh.
|
159 |
-
|
160 |
-
artist_mesh.
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
face_colors =
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
-
|
192 |
-
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
""
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
)
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
)
|
224 |
-
with
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
],
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
with gr.Row():
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
with gr.Row():
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
gr.
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
)
|
277 |
-
|
278 |
demo.launch(share=True)
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import trimesh
|
4 |
+
from accelerate.utils import set_seed
|
5 |
+
from accelerate import Accelerator
|
6 |
+
import numpy as np
|
7 |
+
import gradio as gr
|
8 |
+
from main import load_v2
|
9 |
+
from mesh_to_pc import process_mesh_to_pc
|
10 |
+
import time
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
|
13 |
+
from PIL import Image
|
14 |
+
import io
|
15 |
+
|
16 |
+
model = load_v2()
|
17 |
+
|
18 |
+
device = torch.device('cuda')
|
19 |
+
accelerator = Accelerator(
|
20 |
+
mixed_precision="fp16",
|
21 |
+
)
|
22 |
+
model = accelerator.prepare(model)
|
23 |
+
model.eval()
|
24 |
+
print("Model loaded to device")
|
25 |
+
|
26 |
+
def wireframe_render(mesh):
|
27 |
+
views = [
|
28 |
+
(90, 20), (270, 20)
|
29 |
+
]
|
30 |
+
mesh.vertices = mesh.vertices[:, [0, 2, 1]]
|
31 |
+
|
32 |
+
bounding_box = mesh.bounds
|
33 |
+
center = mesh.centroid
|
34 |
+
scale = np.ptp(bounding_box, axis=0).max()
|
35 |
+
|
36 |
+
fig = plt.figure(figsize=(10, 10))
|
37 |
+
|
38 |
+
# Function to render and return each view as an image
|
39 |
+
def render_view(mesh, azimuth, elevation):
|
40 |
+
ax = fig.add_subplot(111, projection='3d')
|
41 |
+
ax.set_axis_off()
|
42 |
+
|
43 |
+
# Extract vertices and faces for plotting
|
44 |
+
vertices = mesh.vertices
|
45 |
+
faces = mesh.faces
|
46 |
+
|
47 |
+
# Plot faces
|
48 |
+
ax.add_collection3d(Poly3DCollection(
|
49 |
+
vertices[faces],
|
50 |
+
facecolors=(0.8, 0.5, 0.2, 1.0), # Brownish yellow
|
51 |
+
edgecolors='k',
|
52 |
+
linewidths=0.5,
|
53 |
+
))
|
54 |
+
|
55 |
+
# Set limits and center the view on the object
|
56 |
+
ax.set_xlim(center[0] - scale / 2, center[0] + scale / 2)
|
57 |
+
ax.set_ylim(center[1] - scale / 2, center[1] + scale / 2)
|
58 |
+
ax.set_zlim(center[2] - scale / 2, center[2] + scale / 2)
|
59 |
+
|
60 |
+
# Set view angle
|
61 |
+
ax.view_init(elev=elevation, azim=azimuth)
|
62 |
+
|
63 |
+
# Save the figure to a buffer
|
64 |
+
buf = io.BytesIO()
|
65 |
+
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0, dpi=300)
|
66 |
+
plt.clf()
|
67 |
+
buf.seek(0)
|
68 |
+
|
69 |
+
return Image.open(buf)
|
70 |
+
|
71 |
+
# Render each view and store in a list
|
72 |
+
images = [render_view(mesh, az, el) for az, el in views]
|
73 |
+
|
74 |
+
# Combine images horizontally
|
75 |
+
widths, heights = zip(*(i.size for i in images))
|
76 |
+
total_width = sum(widths)
|
77 |
+
max_height = max(heights)
|
78 |
+
|
79 |
+
combined_image = Image.new('RGBA', (total_width, max_height))
|
80 |
+
|
81 |
+
x_offset = 0
|
82 |
+
for img in images:
|
83 |
+
combined_image.paste(img, (x_offset, 0))
|
84 |
+
x_offset += img.width
|
85 |
+
|
86 |
+
# Save the combined image
|
87 |
+
save_path = f"combined_mesh_view_{int(time.time())}.png"
|
88 |
+
combined_image.save(save_path)
|
89 |
+
|
90 |
+
plt.close(fig)
|
91 |
+
return save_path
|
92 |
+
|
93 |
+
@torch.no_grad()
|
94 |
+
def do_inference(input_3d, sample_seed=0, do_sampling=False, do_marching_cubes=False):
|
95 |
+
set_seed(sample_seed)
|
96 |
+
print("Seed value:", sample_seed)
|
97 |
+
|
98 |
+
input_mesh = trimesh.load(input_3d)
|
99 |
+
pc_list, mesh_list = process_mesh_to_pc([input_mesh], marching_cubes = do_marching_cubes)
|
100 |
+
pc_normal = pc_list[0] # 4096, 6
|
101 |
+
mesh = mesh_list[0]
|
102 |
+
vertices = mesh.vertices
|
103 |
+
|
104 |
+
pc_coor = pc_normal[:, :3]
|
105 |
+
normals = pc_normal[:, 3:]
|
106 |
+
|
107 |
+
bounds = np.array([vertices.min(axis=0), vertices.max(axis=0)])
|
108 |
+
# scale mesh and pc
|
109 |
+
vertices = vertices - (bounds[0] + bounds[1])[None, :] / 2
|
110 |
+
vertices = vertices / (bounds[1] - bounds[0]).max()
|
111 |
+
mesh.vertices = vertices
|
112 |
+
pc_coor = pc_coor - (bounds[0] + bounds[1])[None, :] / 2
|
113 |
+
pc_coor = pc_coor / (bounds[1] - bounds[0]).max()
|
114 |
+
|
115 |
+
mesh.merge_vertices()
|
116 |
+
mesh.update_faces(mesh.nondegenerate_faces())
|
117 |
+
mesh.update_faces(mesh.unique_faces())
|
118 |
+
mesh.remove_unreferenced_vertices()
|
119 |
+
mesh.fix_normals()
|
120 |
+
if mesh.visual.vertex_colors is not None:
|
121 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
122 |
+
|
123 |
+
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
|
124 |
+
else:
|
125 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
126 |
+
mesh.visual.vertex_colors = np.tile(orange_color, (mesh.vertices.shape[0], 1))
|
127 |
+
input_save_name = f"processed_input_{int(time.time())}.obj"
|
128 |
+
mesh.export(input_save_name)
|
129 |
+
input_render_res = wireframe_render(mesh)
|
130 |
+
|
131 |
+
pc_coor = pc_coor / np.abs(pc_coor).max() * 0.99 # input should be from -1 to 1
|
132 |
+
|
133 |
+
assert (np.linalg.norm(normals, axis=-1) > 0.99).all(), "normals should be unit vectors, something wrong"
|
134 |
+
normalized_pc_normal = np.concatenate([pc_coor, normals], axis=-1, dtype=np.float16)
|
135 |
+
|
136 |
+
input = torch.tensor(normalized_pc_normal, dtype=torch.float16, device=device)[None]
|
137 |
+
print("Data loaded")
|
138 |
+
|
139 |
+
# with accelerator.autocast():
|
140 |
+
with accelerator.autocast():
|
141 |
+
outputs = model(input, do_sampling)
|
142 |
+
print("Model inference done")
|
143 |
+
recon_mesh = outputs[0]
|
144 |
+
|
145 |
+
valid_mask = torch.all(~torch.isnan(recon_mesh.reshape((-1, 9))), dim=1)
|
146 |
+
recon_mesh = recon_mesh[valid_mask] # nvalid_face x 3 x 3
|
147 |
+
vertices = recon_mesh.reshape(-1, 3).cpu()
|
148 |
+
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
|
149 |
+
triangles = vertices_index.reshape(-1, 3)
|
150 |
+
|
151 |
+
artist_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
|
152 |
+
merge_primitives=True)
|
153 |
+
|
154 |
+
artist_mesh.merge_vertices()
|
155 |
+
artist_mesh.update_faces(artist_mesh.nondegenerate_faces())
|
156 |
+
artist_mesh.update_faces(artist_mesh.unique_faces())
|
157 |
+
artist_mesh.remove_unreferenced_vertices()
|
158 |
+
artist_mesh.fix_normals()
|
159 |
+
|
160 |
+
if artist_mesh.visual.vertex_colors is not None:
|
161 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
162 |
+
|
163 |
+
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
|
164 |
+
else:
|
165 |
+
orange_color = np.array([255, 165, 0, 255], dtype=np.uint8)
|
166 |
+
artist_mesh.visual.vertex_colors = np.tile(orange_color, (artist_mesh.vertices.shape[0], 1))
|
167 |
+
|
168 |
+
num_faces = len(artist_mesh.faces)
|
169 |
+
|
170 |
+
brown_color = np.array([165, 42, 42, 255], dtype=np.uint8)
|
171 |
+
face_colors = np.tile(brown_color, (num_faces, 1))
|
172 |
+
|
173 |
+
artist_mesh.visual.face_colors = face_colors
|
174 |
+
# add time stamp to avoid cache
|
175 |
+
save_name = f"output_{int(time.time())}.obj"
|
176 |
+
artist_mesh.export(save_name)
|
177 |
+
output_render = wireframe_render(artist_mesh)
|
178 |
+
return input_save_name, input_render_res, save_name, output_render
|
179 |
+
|
180 |
+
|
181 |
+
_HEADER_ = '''
|
182 |
+
<h2><b>Official ? Gradio Demo</b></h2><h2><a href='https://github.com/buaacyw/MeshAnything' target='_blank'><b>MeshAnything V2: Artist-Created Mesh Generation With Adjacent Mesh Tokenization</b></a></h2>
|
183 |
+
|
184 |
+
**MeshAnything** converts any 3D representation into meshes created by human artists, i.e., Artist-Created Meshes (AMs).
|
185 |
+
|
186 |
+
Code: <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>. Arxiv Paper: <a href='https://arxiv.org/abs/2406.10163' target='_blank'>ArXiv</a>.
|
187 |
+
|
188 |
+
??????**Important Notes:**
|
189 |
+
- Gradio doesn't support interactive wireframe rendering currently. For interactive mesh visualization, please use download the obj file and open it with MeshLab or https://3dviewer.net/.
|
190 |
+
- The input mesh will be normalized to a unit bounding box. The up vector of the input mesh should be +Y for better results. Click **Preprocess with Marching Cubes** if the input mesh is a manually created mesh.
|
191 |
+
- Limited by computational resources, MeshAnything is trained on meshes with fewer than 800 faces and cannot generate meshes with more than 800 faces. The shape of the input mesh should be sharp enough; otherwise, it will be challenging to represent it with only 800 faces. Thus, feed-forward image-to-3D methods may often produce bad results due to insufficient shape quality.
|
192 |
+
- For point cloud input, please refer to our github repo <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>GitHub</a>.
|
193 |
+
'''
|
194 |
+
|
195 |
+
|
196 |
+
_CITE_ = r"""
|
197 |
+
If MeshAnything is helpful, please help to ? the <a href='https://github.com/buaacyw/MeshAnything' target='_blank'>Github Repo</a>. Thanks!
|
198 |
+
---
|
199 |
+
? **License**
|
200 |
+
|
201 |
+
S-Lab-1.0 LICENSE. Please refer to the [LICENSE file](https://github.com/buaacyw/GaussianEditor/blob/master/LICENSE.txt) for details.
|
202 |
+
|
203 |
+
? **Contact**
|
204 |
+
|
205 |
+
If you have any questions, feel free to open a discussion or contact us at <b>yiwen002@e.ntu.edu.sg</b>.
|
206 |
+
|
207 |
+
"""
|
208 |
+
output_model_obj = gr.Model3D(
|
209 |
+
label="Generated Mesh (OBJ Format)",
|
210 |
+
clear_color=[1, 1, 1, 1],
|
211 |
+
)
|
212 |
+
preprocess_model_obj = gr.Model3D(
|
213 |
+
label="Processed Input Mesh (OBJ Format)",
|
214 |
+
clear_color=[1, 1, 1, 1],
|
215 |
+
)
|
216 |
+
input_image_render = gr.Image(
|
217 |
+
label="Wireframe Render of Processed Input Mesh",
|
218 |
+
)
|
219 |
+
output_image_render = gr.Image(
|
220 |
+
label="Wireframe Render of Generated Mesh",
|
221 |
+
)
|
222 |
+
with (gr.Blocks() as demo):
|
223 |
+
gr.Markdown(_HEADER_)
|
224 |
+
with gr.Row(variant="panel"):
|
225 |
+
with gr.Column():
|
226 |
+
with gr.Row():
|
227 |
+
input_3d = gr.Model3D(
|
228 |
+
label="Input Mesh",
|
229 |
+
clear_color=[1,1,1,1],
|
230 |
+
)
|
231 |
+
|
232 |
+
with gr.Row():
|
233 |
+
with gr.Group():
|
234 |
+
do_marching_cubes = gr.Checkbox(label="Preprocess with Marching Cubes", value=False)
|
235 |
+
do_sampling = gr.Checkbox(label="Random Sampling", value=False)
|
236 |
+
sample_seed = gr.Number(value=0, label="Seed Value", precision=0)
|
237 |
+
|
238 |
+
with gr.Row():
|
239 |
+
submit = gr.Button("Generate", elem_id="generate", variant="primary")
|
240 |
+
|
241 |
+
with gr.Row(variant="panel"):
|
242 |
+
mesh_examples = gr.Examples(
|
243 |
+
examples=[
|
244 |
+
os.path.join("examples", img_name) for img_name in sorted(os.listdir("examples"))
|
245 |
+
],
|
246 |
+
inputs=input_3d,
|
247 |
+
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
|
248 |
+
fn=do_inference,
|
249 |
+
cache_examples = False,
|
250 |
+
examples_per_page=10
|
251 |
+
)
|
252 |
+
with gr.Column():
|
253 |
+
with gr.Row():
|
254 |
+
input_image_render.render()
|
255 |
+
with gr.Row():
|
256 |
+
with gr.Tab("OBJ"):
|
257 |
+
preprocess_model_obj.render()
|
258 |
+
with gr.Row():
|
259 |
+
output_image_render.render()
|
260 |
+
with gr.Row():
|
261 |
+
with gr.Tab("OBJ"):
|
262 |
+
output_model_obj.render()
|
263 |
+
with gr.Row():
|
264 |
+
gr.Markdown('''Try click random sampling and different <b>Seed Value</b> if the result is unsatisfying''')
|
265 |
+
|
266 |
+
gr.Markdown(_CITE_)
|
267 |
+
|
268 |
+
mv_images = gr.State()
|
269 |
+
|
270 |
+
submit.click(
|
271 |
+
fn=do_inference,
|
272 |
+
inputs=[input_3d, sample_seed, do_sampling, do_marching_cubes],
|
273 |
+
outputs=[preprocess_model_obj, input_image_render, output_model_obj, output_image_render],
|
274 |
+
)
|
275 |
+
|
|
|
|
|
276 |
demo.launch(share=True)
|
main.py
CHANGED
@@ -3,12 +3,13 @@ import torch
|
|
3 |
import time
|
4 |
import trimesh
|
5 |
import numpy as np
|
6 |
-
from MeshAnything.models.
|
7 |
import datetime
|
8 |
from accelerate import Accelerator
|
9 |
from accelerate.utils import set_seed
|
10 |
from accelerate.utils import DistributedDataParallelKwargs
|
11 |
-
from safetensors import
|
|
|
12 |
from mesh_to_pc import process_mesh_to_pc
|
13 |
from huggingface_hub import hf_hub_download
|
14 |
|
@@ -21,8 +22,8 @@ class Dataset:
|
|
21 |
# load npy
|
22 |
cur_data = np.load(input_path)
|
23 |
# sample 4096
|
24 |
-
assert cur_data.shape[0] >=
|
25 |
-
idx = np.random.choice(cur_data.shape[0],
|
26 |
cur_data = cur_data[idx]
|
27 |
self.data.append({'pc_normal': cur_data, 'uid': input_path.split('/')[-1].split('.')[0]})
|
28 |
|
@@ -60,12 +61,10 @@ class Dataset:
|
|
60 |
def get_args():
|
61 |
parser = argparse.ArgumentParser("MeshAnything", add_help=False)
|
62 |
|
63 |
-
parser.add_argument('--llm', default="facebook/opt-350m", type=str)
|
64 |
parser.add_argument('--input_dir', default=None, type=str)
|
65 |
parser.add_argument('--input_path', default=None, type=str)
|
66 |
|
67 |
parser.add_argument('--out_dir', default="inference_out", type=str)
|
68 |
-
parser.add_argument('--pretrained_weights', default="MeshAnything_350m.pth", type=str)
|
69 |
|
70 |
parser.add_argument(
|
71 |
'--input_type',
|
@@ -74,11 +73,6 @@ def get_args():
|
|
74 |
help="Type of the asset to process (default: pc)"
|
75 |
)
|
76 |
|
77 |
-
parser.add_argument("--codebook_size", default=8192, type=int)
|
78 |
-
parser.add_argument("--codebook_dim", default=1024, type=int)
|
79 |
-
|
80 |
-
parser.add_argument("--n_max_triangles", default=800, type=int)
|
81 |
-
|
82 |
parser.add_argument("--batchsize_per_gpu", default=1, type=int)
|
83 |
parser.add_argument("--seed", default=0, type=int)
|
84 |
|
@@ -88,20 +82,17 @@ def get_args():
|
|
88 |
args = parser.parse_args()
|
89 |
return args
|
90 |
|
91 |
-
def
|
92 |
-
model =
|
93 |
print("load model over!!!")
|
94 |
|
95 |
ckpt_path = hf_hub_download(
|
96 |
-
repo_id="Yiwen-ntu/
|
97 |
-
filename="
|
98 |
)
|
99 |
-
tensors = {}
|
100 |
-
with safe_open(ckpt_path, framework="pt", device=0) as f:
|
101 |
-
for k in f.keys():
|
102 |
-
tensors[k] = f.get_tensor(k)
|
103 |
|
104 |
-
model
|
|
|
105 |
print("load weights over!!!")
|
106 |
return model
|
107 |
if __name__ == "__main__":
|
@@ -117,7 +108,7 @@ if __name__ == "__main__":
|
|
117 |
kwargs_handlers=[kwargs]
|
118 |
)
|
119 |
|
120 |
-
model =
|
121 |
# create dataset
|
122 |
if args.input_dir is not None:
|
123 |
input_list = sorted(os.listdir(args.input_dir))
|
@@ -155,7 +146,9 @@ if __name__ == "__main__":
|
|
155 |
|
156 |
for batch_id in range(batch_size):
|
157 |
recon_mesh = outputs[batch_id]
|
158 |
-
|
|
|
|
|
159 |
vertices = recon_mesh.reshape(-1, 3).cpu()
|
160 |
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
|
161 |
triangles = vertices_index.reshape(-1, 3)
|
@@ -163,7 +156,9 @@ if __name__ == "__main__":
|
|
163 |
scene_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
|
164 |
merge_primitives=True)
|
165 |
scene_mesh.merge_vertices()
|
|
|
166 |
scene_mesh.update_faces(scene_mesh.unique_faces())
|
|
|
167 |
scene_mesh.fix_normals()
|
168 |
save_path = os.path.join(checkpoint_dir, f'{batch_data_label["uid"][batch_id]}_gen.obj')
|
169 |
num_faces = len(scene_mesh.faces)
|
|
|
3 |
import time
|
4 |
import trimesh
|
5 |
import numpy as np
|
6 |
+
from MeshAnything.models.meshanything_v2 import MeshAnythingV2
|
7 |
import datetime
|
8 |
from accelerate import Accelerator
|
9 |
from accelerate.utils import set_seed
|
10 |
from accelerate.utils import DistributedDataParallelKwargs
|
11 |
+
from safetensors.torch import load_model
|
12 |
+
|
13 |
from mesh_to_pc import process_mesh_to_pc
|
14 |
from huggingface_hub import hf_hub_download
|
15 |
|
|
|
22 |
# load npy
|
23 |
cur_data = np.load(input_path)
|
24 |
# sample 4096
|
25 |
+
assert cur_data.shape[0] >= 8192, "input pc_normal should have at least 4096 points"
|
26 |
+
idx = np.random.choice(cur_data.shape[0], 8192, replace=False)
|
27 |
cur_data = cur_data[idx]
|
28 |
self.data.append({'pc_normal': cur_data, 'uid': input_path.split('/')[-1].split('.')[0]})
|
29 |
|
|
|
61 |
def get_args():
|
62 |
parser = argparse.ArgumentParser("MeshAnything", add_help=False)
|
63 |
|
|
|
64 |
parser.add_argument('--input_dir', default=None, type=str)
|
65 |
parser.add_argument('--input_path', default=None, type=str)
|
66 |
|
67 |
parser.add_argument('--out_dir', default="inference_out", type=str)
|
|
|
68 |
|
69 |
parser.add_argument(
|
70 |
'--input_type',
|
|
|
73 |
help="Type of the asset to process (default: pc)"
|
74 |
)
|
75 |
|
|
|
|
|
|
|
|
|
|
|
76 |
parser.add_argument("--batchsize_per_gpu", default=1, type=int)
|
77 |
parser.add_argument("--seed", default=0, type=int)
|
78 |
|
|
|
82 |
args = parser.parse_args()
|
83 |
return args
|
84 |
|
85 |
+
def load_v2():
|
86 |
+
model = MeshAnythingV2()
|
87 |
print("load model over!!!")
|
88 |
|
89 |
ckpt_path = hf_hub_download(
|
90 |
+
repo_id="Yiwen-ntu/MeshAnythingV2",
|
91 |
+
filename="350m.pth",
|
92 |
)
|
|
|
|
|
|
|
|
|
93 |
|
94 |
+
load_model(model, ckpt_path)
|
95 |
+
|
96 |
print("load weights over!!!")
|
97 |
return model
|
98 |
if __name__ == "__main__":
|
|
|
108 |
kwargs_handlers=[kwargs]
|
109 |
)
|
110 |
|
111 |
+
model = load_v2()
|
112 |
# create dataset
|
113 |
if args.input_dir is not None:
|
114 |
input_list = sorted(os.listdir(args.input_dir))
|
|
|
146 |
|
147 |
for batch_id in range(batch_size):
|
148 |
recon_mesh = outputs[batch_id]
|
149 |
+
valid_mask = torch.all(~torch.isnan(recon_mesh.reshape((-1, 9))), dim=1)
|
150 |
+
recon_mesh = recon_mesh[valid_mask] # nvalid_face x 3 x 3
|
151 |
+
|
152 |
vertices = recon_mesh.reshape(-1, 3).cpu()
|
153 |
vertices_index = np.arange(len(vertices)) # 0, 1, ..., 3 x face
|
154 |
triangles = vertices_index.reshape(-1, 3)
|
|
|
156 |
scene_mesh = trimesh.Trimesh(vertices=vertices, faces=triangles, force="mesh",
|
157 |
merge_primitives=True)
|
158 |
scene_mesh.merge_vertices()
|
159 |
+
scene_mesh.update_faces(scene_mesh.nondegenerate_faces())
|
160 |
scene_mesh.update_faces(scene_mesh.unique_faces())
|
161 |
+
scene_mesh.remove_unreferenced_vertices()
|
162 |
scene_mesh.fix_normals()
|
163 |
save_path = os.path.join(checkpoint_dir, f'{batch_data_label["uid"][batch_id]}_gen.obj')
|
164 |
num_faces = len(scene_mesh.faces)
|
mesh_to_pc.py
CHANGED
@@ -3,7 +3,7 @@ import numpy as np
|
|
3 |
import skimage.measure
|
4 |
import trimesh
|
5 |
|
6 |
-
def normalize_vertices(vertices, scale=0.
|
7 |
bbmin, bbmax = vertices.min(0), vertices.max(0)
|
8 |
center = (bbmin + bbmax) * 0.5
|
9 |
scale = 2.0 * scale / (bbmax - bbmin).max()
|
@@ -39,7 +39,7 @@ def export_to_watertight(normalized_mesh, octree_depth: int = 7):
|
|
39 |
|
40 |
return mesh
|
41 |
|
42 |
-
def process_mesh_to_pc(mesh_list, marching_cubes = False, sample_num =
|
43 |
# mesh_list : list of trimesh
|
44 |
pc_normal_list = []
|
45 |
return_mesh_list = []
|
|
|
3 |
import skimage.measure
|
4 |
import trimesh
|
5 |
|
6 |
+
def normalize_vertices(vertices, scale=0.95):
|
7 |
bbmin, bbmax = vertices.min(0), vertices.max(0)
|
8 |
center = (bbmin + bbmax) * 0.5
|
9 |
scale = 2.0 * scale / (bbmax - bbmin).max()
|
|
|
39 |
|
40 |
return mesh
|
41 |
|
42 |
+
def process_mesh_to_pc(mesh_list, marching_cubes = False, sample_num = 8192):
|
43 |
# mesh_list : list of trimesh
|
44 |
pc_normal_list = []
|
45 |
return_mesh_list = []
|