Chao Xu commited on
Commit
3c9a806
1 Parent(s): dc9750a
Files changed (3) hide show
  1. app.py +710 -0
  2. instructions_12345.md +10 -0
  3. requirements.txt +73 -0
app.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ conda activate zero123
3
+ cd stable-diffusion
4
+ python gradio_new.py 0
5
+ '''
6
+ import os, sys
7
+ from huggingface_hub import snapshot_download
8
+ sys.path.append(snapshot_download("One-2-3-45/code", token=os.environ['TOKEN']))
9
+
10
+ import shutil
11
+ import torch
12
+ import fire
13
+ import gradio as gr
14
+ import numpy as np
15
+ # import plotly.express as px
16
+ import plotly.graph_objects as go
17
+ # import rich
18
+ import sys
19
+ from functools import partial
20
+
21
+ from lovely_numpy import lo
22
+ # from omegaconf import OmegaConf
23
+ import cv2
24
+ from PIL import Image
25
+ import trimesh
26
+ import tempfile
27
+ from zero123_utils import init_model, predict_stage1_gradio, zero123_infer
28
+ from sam_utils import sam_init, sam_out, sam_out_nosave
29
+ from utils import image_preprocess_nosave, gen_poses
30
+ from one2345_elev_est.tools.estimate_wild_imgs import estimate_elev
31
+ from rembg import remove
32
+
33
+ _GPU_INDEX = 0
34
+
35
+ _TITLE = 'One-2-3-45: Any Single Image to 3D Mesh in 45 Seconds without Per-Shape Optimization'
36
+
37
+ # This demo allows you to generate novel viewpoints of an object depicted in an input image using a fine-tuned version of Stable Diffusion.
38
+ _DESCRIPTION = '''
39
+ We reconstruct a 3D textured mesh from a single image by initially predicting multi-view images and then lifting them to 3D.
40
+ '''
41
+
42
+ _USER_GUIDE = "Please upload an image in the top left block (or choose an example above) and click **Run Generation**."
43
+ _BBOX_1 = "Predicting bounding box for the input image..."
44
+ _BBOX_2 = "Bounding box adjusted. Continue adjusting or **Run Generation**."
45
+ _BBOX_3 = "Bounding box predicted. Adjust it using sliders or **Run Generation**."
46
+ _SAM = "Preprocessing the input image... (safety check, SAM segmentation, *etc*.)"
47
+ _GEN_1 = "Predicting multi-view images... (may take \~23 seconds) <br> Images will be shown in the bottom right blocks."
48
+ _GEN_2 = "Predicting nearby views and generating mesh... (may take \~48 seconds) <br> Mesh will be shown below."
49
+ _DONE = "Done! Mesh is shown below. <br> If it is not satisfactory, please select **Retry view** checkboxes for inaccurate views and click **Regenerate selected view(s)** at the bottom."
50
+ _REGEN_1 = "Selected view(s) are regenerated. You can click **Regenerate nearby views and mesh**. <br> Alternatively, if the regenerated view(s) are still not satisfactory, you can repeat the previous step (select the view and regenerate)."
51
+ _REGEN_2 = "Regeneration done. <br> Mesh is shown below."
52
+
53
+ class CameraVisualizer:
54
+ def __init__(self, gradio_plot):
55
+ self._gradio_plot = gradio_plot
56
+ self._fig = None
57
+ self._polar = 0.0
58
+ self._azimuth = 0.0
59
+ self._radius = 0.0
60
+ self._raw_image = None
61
+ self._8bit_image = None
62
+ self._image_colorscale = None
63
+
64
+ def polar_change(self, value):
65
+ self._polar = value
66
+ # return self.update_figure()
67
+
68
+ def azimuth_change(self, value):
69
+ self._azimuth = value
70
+ # return self.update_figure()
71
+
72
+ def radius_change(self, value):
73
+ self._radius = value
74
+ # return self.update_figure()
75
+
76
+ def encode_image(self, raw_image, elev=90):
77
+ '''
78
+ :param raw_image (H, W, 3) array of uint8 in [0, 255].
79
+ '''
80
+ # https://stackoverflow.com/questions/60685749/python-plotly-how-to-add-an-image-to-a-3d-scatter-plot
81
+
82
+ dum_img = Image.fromarray(np.ones((3, 3, 3), dtype='uint8')).convert('P', palette='WEB')
83
+ idx_to_color = np.array(dum_img.getpalette()).reshape((-1, 3))
84
+
85
+ self._raw_image = raw_image
86
+ self._8bit_image = Image.fromarray(raw_image).convert('P', palette='WEB', dither=None)
87
+ # self._8bit_image = Image.fromarray(raw_image.clip(0, 254)).convert(
88
+ # 'P', palette='WEB', dither=None)
89
+ self._image_colorscale = [
90
+ [i / 255.0, 'rgb({}, {}, {})'.format(*rgb)] for i, rgb in enumerate(idx_to_color)]
91
+ self._elev = elev
92
+ # return self.update_figure()
93
+
94
+ def update_figure(self):
95
+ fig = go.Figure()
96
+
97
+ if self._raw_image is not None:
98
+ (H, W, C) = self._raw_image.shape
99
+
100
+ x = np.zeros((H, W))
101
+ (y, z) = np.meshgrid(np.linspace(-1.0, 1.0, W), np.linspace(1.0, -1.0, H) * H / W)
102
+
103
+ angle_deg = self._elev-90
104
+ angle = np.radians(90-self._elev)
105
+ rotation_matrix = np.array([
106
+ [np.cos(angle), 0, np.sin(angle)],
107
+ [0, 1, 0],
108
+ [-np.sin(angle), 0, np.cos(angle)]
109
+ ])
110
+ # Assuming x, y, z are the original 3D coordinates of the image
111
+ coordinates = np.stack((x, y, z), axis=-1) # Combine x, y, z into a single array
112
+ # Apply the rotation matrix
113
+ rotated_coordinates = np.matmul(coordinates, rotation_matrix)
114
+ # Extract the new x, y, z coordinates from the rotated coordinates
115
+ x, y, z = rotated_coordinates[..., 0], rotated_coordinates[..., 1], rotated_coordinates[..., 2]
116
+
117
+
118
+ print('x:', lo(x))
119
+ print('y:', lo(y))
120
+ print('z:', lo(z))
121
+
122
+ fig.add_trace(go.Surface(
123
+ x=x, y=y, z=z,
124
+ surfacecolor=self._8bit_image,
125
+ cmin=0,
126
+ cmax=255,
127
+ colorscale=self._image_colorscale,
128
+ showscale=False,
129
+ lighting_diffuse=1.0,
130
+ lighting_ambient=1.0,
131
+ lighting_fresnel=1.0,
132
+ lighting_roughness=1.0,
133
+ lighting_specular=0.3))
134
+
135
+ scene_bounds = 3.5
136
+ base_radius = 2.5
137
+ zoom_scale = 1.5 # Note that input radius offset is in [-0.5, 0.5].
138
+ fov_deg = 50.0
139
+ edges = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4), (4, 1)]
140
+
141
+ input_cone = calc_cam_cone_pts_3d(
142
+ angle_deg, 0.0, base_radius, fov_deg) # (5, 3).
143
+ output_cone = calc_cam_cone_pts_3d(
144
+ self._polar, self._azimuth, base_radius + self._radius * zoom_scale, fov_deg) # (5, 3).
145
+ output_cones = []
146
+ for i in range(1,4):
147
+ output_cones.append(calc_cam_cone_pts_3d(
148
+ angle_deg, i*90, base_radius + self._radius * zoom_scale, fov_deg))
149
+ delta_deg = 30 if angle_deg <= -15 else -30
150
+ for i in range(4):
151
+ output_cones.append(calc_cam_cone_pts_3d(
152
+ angle_deg+delta_deg, 30+i*90, base_radius + self._radius * zoom_scale, fov_deg))
153
+
154
+ cones = [(input_cone, 'rgb(174, 54, 75)', 'Input view (Predicted view 1)')]
155
+ for i in range(len(output_cones)):
156
+ cones.append((output_cones[i], 'rgb(32, 77, 125)', f'Predicted view {i+2}'))
157
+
158
+ for idx, (cone, clr, legend) in enumerate(cones):
159
+
160
+ for (i, edge) in enumerate(edges):
161
+ (x1, x2) = (cone[edge[0], 0], cone[edge[1], 0])
162
+ (y1, y2) = (cone[edge[0], 1], cone[edge[1], 1])
163
+ (z1, z2) = (cone[edge[0], 2], cone[edge[1], 2])
164
+ fig.add_trace(go.Scatter3d(
165
+ x=[x1, x2], y=[y1, y2], z=[z1, z2], mode='lines',
166
+ line=dict(color=clr, width=3),
167
+ name=legend, showlegend=(i == 1) and (idx <= 1)))
168
+
169
+ # Add label.
170
+ if cone[0, 2] <= base_radius / 2.0:
171
+ fig.add_trace(go.Scatter3d(
172
+ x=[cone[0, 0]], y=[cone[0, 1]], z=[cone[0, 2] - 0.05], showlegend=False,
173
+ mode='text', text=legend, textposition='bottom center'))
174
+ else:
175
+ fig.add_trace(go.Scatter3d(
176
+ x=[cone[0, 0]], y=[cone[0, 1]], z=[cone[0, 2] + 0.05], showlegend=False,
177
+ mode='text', text=legend, textposition='top center'))
178
+
179
+ # look at center of scene
180
+ fig.update_layout(
181
+ # width=640,
182
+ # height=480,
183
+ # height=400,
184
+ height=360,
185
+ autosize=True,
186
+ hovermode=False,
187
+ margin=go.layout.Margin(l=0, r=0, b=0, t=0),
188
+ showlegend=False,
189
+ legend=dict(
190
+ yanchor='bottom',
191
+ y=0.01,
192
+ xanchor='right',
193
+ x=0.99,
194
+ ),
195
+ scene=dict(
196
+ aspectmode='manual',
197
+ aspectratio=dict(x=1, y=1, z=1.0),
198
+ camera=dict(
199
+ eye=dict(x=base_radius - 1.6, y=0.0, z=0.6),
200
+ center=dict(x=0.0, y=0.0, z=0.0),
201
+ up=dict(x=0.0, y=0.0, z=1.0)),
202
+ xaxis_title='',
203
+ yaxis_title='',
204
+ zaxis_title='',
205
+ xaxis=dict(
206
+ range=[-scene_bounds, scene_bounds],
207
+ showticklabels=False,
208
+ showgrid=True,
209
+ zeroline=False,
210
+ showbackground=True,
211
+ showspikes=False,
212
+ showline=False,
213
+ ticks=''),
214
+ yaxis=dict(
215
+ range=[-scene_bounds, scene_bounds],
216
+ showticklabels=False,
217
+ showgrid=True,
218
+ zeroline=False,
219
+ showbackground=True,
220
+ showspikes=False,
221
+ showline=False,
222
+ ticks=''),
223
+ zaxis=dict(
224
+ range=[-scene_bounds, scene_bounds],
225
+ showticklabels=False,
226
+ showgrid=True,
227
+ zeroline=False,
228
+ showbackground=True,
229
+ showspikes=False,
230
+ showline=False,
231
+ ticks='')))
232
+
233
+ self._fig = fig
234
+ return fig
235
+
236
+
237
+ def stage1_run(models, device, cam_vis, tmp_dir,
238
+ input_im, scale, ddim_steps, rerun_all=[],
239
+ *btn_retrys):
240
+ is_rerun = True if cam_vis is None else False
241
+
242
+ stage1_dir = os.path.join(tmp_dir, "stage1_8")
243
+ if not is_rerun:
244
+ os.makedirs(stage1_dir, exist_ok=True)
245
+ output_ims = predict_stage1_gradio(models['turncam'], input_im, save_path=stage1_dir, adjust_set=list(range(4)), device=device, ddim_steps=ddim_steps, scale=scale)
246
+ stage2_steps = 50 # ddim_steps
247
+ zero123_infer(models['turncam'], tmp_dir, indices=[0], device=device, ddim_steps=stage2_steps, scale=scale)
248
+ elev_output = estimate_elev(tmp_dir)
249
+ gen_poses(tmp_dir, elev_output)
250
+ show_in_im1 = np.asarray(input_im, dtype=np.uint8)
251
+ cam_vis.encode_image(show_in_im1, elev=elev_output)
252
+ new_fig = cam_vis.update_figure()
253
+
254
+ flag_lower_cam = elev_output <= 75
255
+ if flag_lower_cam:
256
+ output_ims_2 = predict_stage1_gradio(models['turncam'], input_im, save_path=stage1_dir, adjust_set=list(range(4,8)), device=device, ddim_steps=ddim_steps, scale=scale)
257
+ else:
258
+ output_ims_2 = predict_stage1_gradio(models['turncam'], input_im, save_path=stage1_dir, adjust_set=list(range(8,12)), device=device, ddim_steps=ddim_steps, scale=scale)
259
+ return (elev_output, new_fig, *output_ims, *output_ims_2)
260
+ else:
261
+ rerun_idx = [i for i in range(len(btn_retrys)) if btn_retrys[i]]
262
+ elev_output = estimate_elev(tmp_dir)
263
+ if elev_output > 75:
264
+ rerun_idx_in = [i if i < 4 else i+4 for i in rerun_idx]
265
+ else:
266
+ rerun_idx_in = rerun_idx
267
+ for idx in rerun_idx_in:
268
+ if idx not in rerun_all:
269
+ rerun_all.append(idx)
270
+ print("rerun_idx", rerun_all)
271
+ output_ims = predict_stage1_gradio(models['turncam'], input_im, save_path=stage1_dir, adjust_set=rerun_idx_in, device=device, ddim_steps=ddim_steps, scale=scale)
272
+ outputs = [gr.update(visible=True)] * 8
273
+ for idx, view_idx in enumerate(rerun_idx):
274
+ outputs[view_idx] = output_ims[idx]
275
+ reset = [gr.update(value=False)] * 8
276
+ return (rerun_all, *reset, *outputs)
277
+
278
+ def stage2_run(models, device, tmp_dir,
279
+ elev, scale, rerun_all=[], stage2_steps=50):
280
+ # print("elev", elev)
281
+ flag_lower_cam = int(elev["label"]) <= 75
282
+ is_rerun = True if rerun_all else False
283
+ if not is_rerun:
284
+ if flag_lower_cam:
285
+ zero123_infer(models['turncam'], tmp_dir, indices=list(range(1,8)), device=device, ddim_steps=stage2_steps, scale=scale)
286
+ else:
287
+ zero123_infer(models['turncam'], tmp_dir, indices=list(range(1,4))+list(range(8,12)), device=device, ddim_steps=stage2_steps, scale=scale)
288
+ else:
289
+ print("rerun_idx", rerun_all)
290
+ zero123_infer(models['turncam'], tmp_dir, indices=rerun_all, device=device, ddim_steps=stage2_steps, scale=scale)
291
+
292
+ dataset = tmp_dir
293
+ os.chdir('./SparseNeuS_demo_v1/')
294
+
295
+ bash_script = f'CUDA_VISIBLE_DEVICES={_GPU_INDEX} python exp_runner_generic_blender_val.py --specific_dataset_name {dataset} --mode export_mesh --conf confs/one2345_lod0_val_demo.conf --is_continue'
296
+ print(bash_script)
297
+ os.system(bash_script)
298
+ os.chdir("../")
299
+
300
+ ply_path = os.path.join(tmp_dir, f"meshes_val_bg/lod0/mesh_00340000_gradio_lod0.ply")
301
+ mesh_path = os.path.join(tmp_dir, "mesh.obj")
302
+ # Read the textured mesh from .ply file
303
+ mesh = trimesh.load_mesh(ply_path)
304
+ axis = [1, 0, 0]
305
+ angle = np.radians(90)
306
+ rotation_matrix = trimesh.transformations.rotation_matrix(angle, axis)
307
+ mesh.apply_transform(rotation_matrix)
308
+ axis = [0, 0, 1]
309
+ angle = np.radians(180)
310
+ rotation_matrix = trimesh.transformations.rotation_matrix(angle, axis)
311
+ mesh.apply_transform(rotation_matrix)
312
+ # flip x
313
+ mesh.vertices[:, 0] = -mesh.vertices[:, 0]
314
+ mesh.faces = np.fliplr(mesh.faces)
315
+ # Export the mesh as .obj file with colors
316
+ mesh.export(mesh_path, file_type='obj', include_color=True)
317
+
318
+ if not is_rerun:
319
+ return (mesh_path)
320
+ else:
321
+ return (mesh_path, [], gr.update(visible=False), gr.update(visible=False))
322
+
323
+ def nsfw_check(models, raw_im, device='cuda'):
324
+ safety_checker_input = models['clip_fe'](raw_im, return_tensors='pt').to(device)
325
+ (_, has_nsfw_concept) = models['nsfw'](
326
+ images=np.ones((1, 3)), clip_input=safety_checker_input.pixel_values)
327
+ print('has_nsfw_concept:', has_nsfw_concept)
328
+ if np.any(has_nsfw_concept):
329
+ print('NSFW content detected.')
330
+ # Define the image size and background color
331
+ image_width = image_height = 256
332
+ background_color = (255, 255, 255) # White
333
+ # Create a blank image
334
+ image = Image.new("RGB", (image_width, image_height), background_color)
335
+ from PIL import ImageDraw
336
+ draw = ImageDraw.Draw(image)
337
+ text = "Potential NSFW content was detected."
338
+ text_color = (255, 0, 0)
339
+ text_position = (10, 123)
340
+ draw.text(text_position, text, fill=text_color)
341
+ text = "Please try again with a different image."
342
+ text_position = (10, 133)
343
+ draw.text(text_position, text, fill=text_color)
344
+ return image
345
+ else:
346
+ print('Safety check passed.')
347
+ return False
348
+
349
+ def preprocess_run(predictor, models, raw_im, preprocess, *bbox_sliders):
350
+ raw_im.thumbnail([512, 512], Image.Resampling.LANCZOS)
351
+ check_results = nsfw_check(models, raw_im, device=predictor.device)
352
+ if check_results:
353
+ return check_results
354
+ image_sam = sam_out_nosave(predictor, raw_im.convert("RGB"), *bbox_sliders)
355
+ input_256 = image_preprocess_nosave(image_sam, lower_contrast=preprocess, rescale=True)
356
+ return input_256
357
+
358
+ def calc_cam_cone_pts_3d(polar_deg, azimuth_deg, radius_m, fov_deg):
359
+ '''
360
+ :param polar_deg (float).
361
+ :param azimuth_deg (float).
362
+ :param radius_m (float).
363
+ :param fov_deg (float).
364
+ :return (5, 3) array of float with (x, y, z).
365
+ '''
366
+ polar_rad = np.deg2rad(polar_deg)
367
+ azimuth_rad = np.deg2rad(azimuth_deg)
368
+ fov_rad = np.deg2rad(fov_deg)
369
+ polar_rad = -polar_rad # NOTE: Inverse of how used_x relates to x.
370
+
371
+ # Camera pose center:
372
+ cam_x = radius_m * np.cos(azimuth_rad) * np.cos(polar_rad)
373
+ cam_y = radius_m * np.sin(azimuth_rad) * np.cos(polar_rad)
374
+ cam_z = radius_m * np.sin(polar_rad)
375
+
376
+ # Obtain four corners of camera frustum, assuming it is looking at origin.
377
+ # First, obtain camera extrinsics (rotation matrix only):
378
+ camera_R = np.array([[np.cos(azimuth_rad) * np.cos(polar_rad),
379
+ -np.sin(azimuth_rad),
380
+ -np.cos(azimuth_rad) * np.sin(polar_rad)],
381
+ [np.sin(azimuth_rad) * np.cos(polar_rad),
382
+ np.cos(azimuth_rad),
383
+ -np.sin(azimuth_rad) * np.sin(polar_rad)],
384
+ [np.sin(polar_rad),
385
+ 0.0,
386
+ np.cos(polar_rad)]])
387
+ # print('camera_R:', lo(camera_R).v)
388
+
389
+ # Multiply by corners in camera space to obtain go to space:
390
+ corn1 = [-1.0, np.tan(fov_rad / 2.0), np.tan(fov_rad / 2.0)]
391
+ corn2 = [-1.0, -np.tan(fov_rad / 2.0), np.tan(fov_rad / 2.0)]
392
+ corn3 = [-1.0, -np.tan(fov_rad / 2.0), -np.tan(fov_rad / 2.0)]
393
+ corn4 = [-1.0, np.tan(fov_rad / 2.0), -np.tan(fov_rad / 2.0)]
394
+ corn1 = np.dot(camera_R, corn1)
395
+ corn2 = np.dot(camera_R, corn2)
396
+ corn3 = np.dot(camera_R, corn3)
397
+ corn4 = np.dot(camera_R, corn4)
398
+
399
+ # Now attach as offset to actual 3D camera position:
400
+ corn1 = np.array(corn1) / np.linalg.norm(corn1, ord=2)
401
+ corn_x1 = cam_x + corn1[0]
402
+ corn_y1 = cam_y + corn1[1]
403
+ corn_z1 = cam_z + corn1[2]
404
+ corn2 = np.array(corn2) / np.linalg.norm(corn2, ord=2)
405
+ corn_x2 = cam_x + corn2[0]
406
+ corn_y2 = cam_y + corn2[1]
407
+ corn_z2 = cam_z + corn2[2]
408
+ corn3 = np.array(corn3) / np.linalg.norm(corn3, ord=2)
409
+ corn_x3 = cam_x + corn3[0]
410
+ corn_y3 = cam_y + corn3[1]
411
+ corn_z3 = cam_z + corn3[2]
412
+ corn4 = np.array(corn4) / np.linalg.norm(corn4, ord=2)
413
+ corn_x4 = cam_x + corn4[0]
414
+ corn_y4 = cam_y + corn4[1]
415
+ corn_z4 = cam_z + corn4[2]
416
+
417
+ xs = [cam_x, corn_x1, corn_x2, corn_x3, corn_x4]
418
+ ys = [cam_y, corn_y1, corn_y2, corn_y3, corn_y4]
419
+ zs = [cam_z, corn_z1, corn_z2, corn_z3, corn_z4]
420
+
421
+ return np.array([xs, ys, zs]).T
422
+
423
+ def save_bbox(dir, x_min, y_min, x_max, y_max):
424
+ box = np.array([x_min, y_min, x_max, y_max])
425
+ # save the box to a file
426
+ bbox_path = os.path.join(dir, "bbox.txt")
427
+ np.savetxt(bbox_path, box)
428
+
429
+ def on_coords_slider(image, x_min, y_min, x_max, y_max, color=(88, 191, 131, 255)):
430
+ """Draw a bounding box annotation for an image."""
431
+ print("on_coords_slider, drawing bbox...")
432
+ image_size = image.size
433
+ if max(image_size) > 180:
434
+ image.thumbnail([180, 180], Image.Resampling.LANCZOS)
435
+ shrink_ratio = max(image.size) / max(image_size)
436
+ x_min = int(x_min * shrink_ratio)
437
+ y_min = int(y_min * shrink_ratio)
438
+ x_max = int(x_max * shrink_ratio)
439
+ y_max = int(y_max * shrink_ratio)
440
+ print("on_coords_slider, image_size:", np.array(image).shape)
441
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGRA)
442
+ image = cv2.rectangle(image, (x_min, y_min), (x_max, y_max), color, int(max(max(image.shape) / 400*2, 2)))
443
+ return cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA) # image[:, :, ::-1]
444
+
445
+ def save_img(image):
446
+ image.thumbnail([512, 512], Image.Resampling.LANCZOS)
447
+ width, height = image.size
448
+ image_rem = image.convert('RGBA')
449
+ image_nobg = remove(image_rem, alpha_matting=True)
450
+ arr = np.asarray(image_nobg)[:,:,-1]
451
+ x_nonzero = np.nonzero(arr.sum(axis=0))
452
+ y_nonzero = np.nonzero(arr.sum(axis=1))
453
+ x_min = int(x_nonzero[0].min())
454
+ y_min = int(y_nonzero[0].min())
455
+ x_max = int(x_nonzero[0].max())
456
+ y_max = int(y_nonzero[0].max())
457
+ image_mini = image.copy()
458
+ image_mini.thumbnail([180, 180], Image.Resampling.LANCZOS)
459
+ shrink_ratio = max(image_mini.size) / max(width, height)
460
+ x_min_shrink = int(x_min * shrink_ratio)
461
+ y_min_shrink = int(y_min * shrink_ratio)
462
+ x_max_shrink = int(x_max * shrink_ratio)
463
+ y_max_shrink = int(y_max * shrink_ratio)
464
+
465
+ return [on_coords_slider(image_mini, x_min_shrink, y_min_shrink, x_max_shrink, y_max_shrink),
466
+ gr.update(value=x_min, maximum=width),
467
+ gr.update(value=y_min, maximum=height),
468
+ gr.update(value=x_max, maximum=width),
469
+ gr.update(value=y_max, maximum=height)]
470
+
471
+
472
+ def run_demo(
473
+ device_idx=_GPU_INDEX,
474
+ ckpt='zero123-xl.ckpt'):
475
+
476
+ print('sys.argv:', sys.argv)
477
+ if len(sys.argv) > 1:
478
+ print('old device_idx:', device_idx)
479
+ device_idx = int(sys.argv[1])
480
+ print('new device_idx:', device_idx)
481
+
482
+ device = f"cuda:{device_idx}" if torch.cuda.is_available() else "cpu"
483
+ models = init_model(device, ckpt)
484
+ # model = models['turncam']
485
+ # sampler = DDIMSampler(model)
486
+
487
+ # init sam model
488
+ predictor = sam_init(device_idx)
489
+
490
+ with open('instructions_12345.md', 'r') as f:
491
+ article = f.read()
492
+
493
+ # NOTE: Examples must match inputs
494
+ example_folder = os.path.join(os.path.dirname(__file__), 'demo_examples')
495
+ example_fns = os.listdir(example_folder)
496
+ example_fns.sort()
497
+ examples_full = [os.path.join(example_folder, x) for x in example_fns if x.endswith('.png')]
498
+
499
+
500
+ # Compose demo layout & data flow.
501
+ css="#model-3d-out {height: 400px;}"
502
+ with gr.Blocks(title=_TITLE, css=css) as demo:
503
+ gr.Markdown('# ' + _TITLE)
504
+ gr.Markdown(_DESCRIPTION)
505
+
506
+ with gr.Row(variant='panel'):
507
+ with gr.Column(scale=0.85):
508
+ image_block = gr.Image(type='pil', image_mode='RGBA', label='Input image', tool=None)
509
+ with gr.Row():
510
+ bbox_block = gr.Image(type='pil', label="Bounding box", interactive=False).style(height=300)
511
+ sam_block = gr.Image(type='pil', label="SAM output", interactive=False)
512
+ max_width = max_height = 256
513
+ # with gr.Row():
514
+ # gr.Markdown('After uploading the image, a bounding box will be generated automatically. If the result is not satisfactory, you can also use the slider below to manually select the object.')
515
+ with gr.Row():
516
+ x_min_slider = gr.Slider(
517
+ label="X min",
518
+ interactive=True,
519
+ value=0,
520
+ minimum=0,
521
+ maximum=max_width,
522
+ step=1,
523
+ )
524
+ y_min_slider = gr.Slider(
525
+ label="Y min",
526
+ interactive=True,
527
+ value=0,
528
+ minimum=0,
529
+ maximum=max_height,
530
+ step=1,
531
+ )
532
+ with gr.Row():
533
+ x_max_slider = gr.Slider(
534
+ label="X max",
535
+ interactive=True,
536
+ value=max_width,
537
+ minimum=0,
538
+ maximum=max_width,
539
+ step=1,
540
+ )
541
+ y_max_slider = gr.Slider(
542
+ label="Y max",
543
+ interactive=True,
544
+ value=max_height,
545
+ minimum=0,
546
+ maximum=max_height,
547
+ step=1,
548
+ )
549
+ bbox_sliders = [x_min_slider, y_min_slider, x_max_slider, y_max_slider]
550
+
551
+
552
+ with gr.Column(scale=1.15):
553
+ gr.Examples(
554
+ examples=examples_full, # NOTE: elements must match inputs list!
555
+ # fn=save_img,
556
+ fn=lambda x: x,
557
+ inputs=[image_block],
558
+ # outputs=[image_block, bbox_block, *bbox_sliders],
559
+ outputs=[image_block],
560
+ cache_examples=False,
561
+ run_on_click=True,
562
+ label='Examples (click one of the images below to start)',
563
+ )
564
+ preprocess_chk = gr.Checkbox(
565
+ True, label='Reduce image contrast (mitigate shadows on the backside)')
566
+
567
+ with gr.Accordion('Advanced options', open=False):
568
+ scale_slider = gr.Slider(0, 30, value=3, step=1,
569
+ label='Diffusion guidance scale')
570
+ steps_slider = gr.Slider(5, 200, value=75, step=5,
571
+ label='Number of diffusion inference steps')
572
+
573
+ with gr.Row():
574
+ run_btn = gr.Button('Run Generation', variant='primary')
575
+ # guide_title = gr.Markdown(_GUIDE_TITLE, visible=True)
576
+ guide_text = gr.Markdown(_USER_GUIDE, visible=True)
577
+
578
+ with gr.Row():
579
+ # height does not work [a bug]
580
+ mesh_output = gr.Model3D(clear_color=[0.0, 0.0, 0.0, 0.0], label="One-2-3-45's Textured Mesh", elem_id="model-3d-out") #.style(height=800)
581
+
582
+ with gr.Row(variant='panel'):
583
+ with gr.Column(scale=0.85):
584
+ with gr.Row():
585
+ # with gr.Column(scale=8):
586
+ elev_output = gr.Label(label='Estimated elevation / polar angle of the input image (degree, w.r.t. the Z axis)')
587
+ # with gr.Column(scale=1):
588
+ # theta_output = gr.Image(value="./theta_mini.png", interactive=False, show_label=False).style(width=100)
589
+ vis_output = gr.Plot(
590
+ label='Camera poses of the input view (red) and predicted views (blue)')
591
+
592
+ with gr.Column(scale=1.15):
593
+ gr.Markdown('Predicted multi-view images')
594
+ with gr.Row():
595
+ view_1 = gr.Image(interactive=False, show_label=False).style(height=200)
596
+ view_2 = gr.Image(interactive=False, show_label=False).style(height=200)
597
+ view_3 = gr.Image(interactive=False, show_label=False).style(height=200)
598
+ view_4 = gr.Image(interactive=False, show_label=False).style(height=200)
599
+ with gr.Row():
600
+ btn_retry_1 = gr.Checkbox(label='Retry view 1')
601
+ btn_retry_2 = gr.Checkbox(label='Retry view 2')
602
+ btn_retry_3 = gr.Checkbox(label='Retry view 3')
603
+ btn_retry_4 = gr.Checkbox(label='Retry view 4')
604
+ with gr.Row():
605
+ view_5 = gr.Image(interactive=False, show_label=False).style(height=200)
606
+ view_6 = gr.Image(interactive=False, show_label=False).style(height=200)
607
+ view_7 = gr.Image(interactive=False, show_label=False).style(height=200)
608
+ view_8 = gr.Image(interactive=False, show_label=False).style(height=200)
609
+ with gr.Row():
610
+ btn_retry_5 = gr.Checkbox(label='Retry view 5')
611
+ btn_retry_6 = gr.Checkbox(label='Retry view 6')
612
+ btn_retry_7 = gr.Checkbox(label='Retry view 7')
613
+ btn_retry_8 = gr.Checkbox(label='Retry view 8')
614
+ # regen_btn = gr.Button('Regenerate selected views and mesh', variant='secondary', visible=False)
615
+ with gr.Row():
616
+ regen_view_btn = gr.Button('1. Regenerate selected view(s)', variant='secondary', visible=False)
617
+ regen_mesh_btn = gr.Button('2. Regenerate nearby views and mesh', variant='secondary', visible=False)
618
+
619
+ update_guide = lambda GUIDE_TEXT: gr.update(value=GUIDE_TEXT)
620
+
621
+ views = [view_1, view_2, view_3, view_4, view_5, view_6, view_7, view_8]
622
+ btn_retrys = [btn_retry_1, btn_retry_2, btn_retry_3, btn_retry_4, btn_retry_5, btn_retry_6, btn_retry_7, btn_retry_8]
623
+
624
+ rerun_idx = gr.State([])
625
+ tmp_dir = gr.State('./demo_tmp/tmp_dir')
626
+
627
+ def refresh(tmp_dir):
628
+ if os.path.exists(tmp_dir):
629
+ shutil.rmtree(tmp_dir)
630
+ tmp_dir = tempfile.TemporaryDirectory(dir="./demo_tmp")
631
+ print("create tmp_dir", tmp_dir.name)
632
+ clear = [gr.update(value=[])] + [None] * 6 + [gr.update(visible=False)] * 2 + [None] * 8 + [gr.update(value=False)] * 8
633
+ return (tmp_dir.name, *clear)
634
+
635
+ placeholder = gr.Image(visible=False)
636
+ tmp_func = lambda x: False if not x else gr.update(visible=False)
637
+ disable_func = lambda *args: [gr.update(interactive=False)] * len(args)
638
+ enable_func = lambda *args: [gr.update(interactive=True)] * len(args)
639
+ image_block.change(fn=refresh,
640
+ inputs=[tmp_dir],
641
+ outputs=[tmp_dir, rerun_idx, bbox_block, sam_block, elev_output, vis_output, mesh_output, regen_view_btn, regen_mesh_btn, *views, *btn_retrys]
642
+ ).success(disable_func, inputs=[run_btn], outputs=[run_btn]
643
+ ).success(fn=tmp_func, inputs=[image_block], outputs=[placeholder]
644
+ ).success(fn=partial(update_guide, _BBOX_1), outputs=[guide_text]
645
+ ).success(fn=save_img,
646
+ inputs=[image_block],
647
+ outputs=[bbox_block, *bbox_sliders]
648
+ ).success(fn=partial(update_guide, _BBOX_3), outputs=[guide_text]
649
+ ).success(enable_func, inputs=[run_btn], outputs=[run_btn])
650
+
651
+
652
+ for bbox_slider in bbox_sliders:
653
+ bbox_slider.release(fn=on_coords_slider,
654
+ inputs=[image_block, *bbox_sliders],
655
+ outputs=[bbox_block]
656
+ ).success(fn=partial(update_guide, _BBOX_2), outputs=[guide_text])
657
+
658
+ cam_vis = CameraVisualizer(vis_output)
659
+
660
+ gr.Markdown(article)
661
+
662
+ # Define the function to be called when any of the btn_retry buttons are clicked
663
+ def on_retry_button_click(*btn_retrys):
664
+ any_checked = any([btn_retry for btn_retry in btn_retrys])
665
+ print('any_checked:', any_checked, [btn_retry for btn_retry in btn_retrys])
666
+ # return regen_btn.update(visible=any_checked)
667
+ if any_checked:
668
+ return (gr.update(visible=True), gr.update(visible=True))
669
+ else:
670
+ return (gr.update(), gr.update())
671
+ # return regen_view_btn.update(visible=any_checked), regen_mesh_btn.update(visible=any_checked)
672
+ # make regen_btn visible when any of the btn_retry is checked
673
+ for btn_retry in btn_retrys:
674
+ # Add the event handlers to the btn_retry buttons
675
+ # btn_retry.change(fn=on_retry_button_click, inputs=[*btn_retrys], outputs=regen_btn)
676
+ btn_retry.change(fn=on_retry_button_click, inputs=[*btn_retrys], outputs=[regen_view_btn, regen_mesh_btn])
677
+
678
+
679
+
680
+ run_btn.click(fn=partial(update_guide, _SAM), outputs=[guide_text]
681
+ ).success(fn=partial(preprocess_run, predictor, models),
682
+ inputs=[image_block, preprocess_chk, *bbox_sliders],
683
+ outputs=[sam_block]
684
+ ).success(fn=partial(update_guide, _GEN_1), outputs=[guide_text]
685
+ ).success(fn=partial(stage1_run, models, device, cam_vis),
686
+ inputs=[tmp_dir, sam_block, scale_slider, steps_slider],
687
+ outputs=[elev_output, vis_output, *views]
688
+ ).success(fn=partial(update_guide, _GEN_2), outputs=[guide_text]
689
+ ).success(fn=partial(stage2_run, models, device),
690
+ inputs=[tmp_dir, elev_output, scale_slider],
691
+ outputs=[mesh_output]
692
+ ).success(fn=partial(update_guide, _DONE), outputs=[guide_text])
693
+
694
+
695
+ regen_view_btn.click(fn=partial(stage1_run, models, device, None),
696
+ inputs=[tmp_dir, sam_block, scale_slider, steps_slider, rerun_idx, *btn_retrys],
697
+ outputs=[rerun_idx, *btn_retrys, *views]
698
+ ).success(fn=partial(update_guide, _REGEN_1), outputs=[guide_text])
699
+ regen_mesh_btn.click(fn=partial(stage2_run, models, device),
700
+ inputs=[tmp_dir, elev_output, scale_slider, rerun_idx],
701
+ outputs=[mesh_output, rerun_idx, regen_view_btn, regen_mesh_btn]
702
+ ).success(fn=partial(update_guide, _REGEN_2), outputs=[guide_text])
703
+
704
+
705
+ demo.launch(enable_queue=True, share=False, max_threads=80, auth=("admin", "7wQ@>1ga}NNmdLh-N]0*"))
706
+
707
+
708
+ if __name__ == '__main__':
709
+
710
+ fire.Fire(run_demo)
instructions_12345.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Tuning Tips:
2
+
3
+ 1. The multi-view prediction module (Zero123) operates probabilistically. If some of the predicted views are not satisfactory, you may select and regenerate them.
4
+
5
+ 2. In “advanced options”, you can tune two parameters as in other common diffusion models:
6
+ - Diffusion Guidance Scale determines how much you want the model to respect the input information (input image + viewpoints). Increasing the scale typically results in better adherence, less diversity, and also higher image distortion.
7
+
8
+ - Number of diffusion inference steps controls the number of diffusion steps applied to generate each image. Generally, a higher value yields better results but with diminishing returns.
9
+
10
+ Enjoy creating your 3D asset!
requirements.txt ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch>=1.12.1
3
+ torchvision>=0.13.1
4
+ albumentations>=0.4.3
5
+ opencv-python>=4.5.5.64
6
+ pudb>=2019.2
7
+ imageio>=2.9.0
8
+ imageio-ffmpeg>=0.4.2
9
+ pytorch-lightning>=1.4.2
10
+ omegaconf>=2.1.1
11
+ test-tube>=0.7.5
12
+ streamlit>=0.73.1
13
+ einops>=0.3.0
14
+ torch-fidelity>=0.3.0
15
+ transformers>=4.22.2
16
+ kornia>=0.6
17
+ webdataset>=0.2.5
18
+ torchmetrics>=0.6.0
19
+ fire>=0.4.0
20
+ gradio>=3.21.0
21
+ diffusers>=0.12.1
22
+ datasets[vision]>=2.4.0
23
+ carvekit-colab>=4.1.0
24
+ rich>=13.3.2
25
+ lovely-numpy>=0.2.8
26
+ lovely-tensors>=0.1.14
27
+ plotly>=5.13.1
28
+ -e git+https://github.com/CompVis/taming-transformers.git#egg=taming-transformers
29
+ # elev est
30
+ dl_ext
31
+ easydict
32
+ glumpy
33
+ gym
34
+ h5py
35
+ imageio
36
+ loguru
37
+ matplotlib
38
+ # mplib
39
+ multipledispatch
40
+ open3d
41
+ packaging
42
+ Pillow
43
+ pycocotools
44
+ motion-planning
45
+ pyrender
46
+ PyYAML
47
+ scikit_image
48
+ scikit_learn
49
+ scipy
50
+ screeninfo
51
+ setuptools
52
+ tensorboardX
53
+ termcolor
54
+ tqdm
55
+ transforms3d
56
+ trimesh
57
+ yacs
58
+ zarr
59
+ sapien
60
+ pyglet==1.5.27
61
+ wis3d
62
+ git+https://github.com/NVlabs/nvdiffrast.git
63
+ # shap-e
64
+ git+https://github.com/openai/shap-e@8625e7c
65
+ # segment anything
66
+ opencv-python
67
+ pycocotools
68
+ matplotlib
69
+ onnxruntime
70
+ onnx
71
+ git+https://github.com/facebookresearch/segment-anything.git
72
+ # rembg
73
+ rembg