JunlinHan commited on
Commit
0816d86
1 Parent(s): b24d622

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -51
app.py CHANGED
@@ -1,9 +1,11 @@
 
1
  import torch
2
  import gradio as gr
3
  import os
4
  import numpy as np
5
  import trimesh
6
  import mcubes
 
7
  from torchvision.utils import save_image
8
  from PIL import Image
9
  from transformers import AutoModel, AutoConfig
@@ -11,13 +13,13 @@ from rembg import remove, new_session
11
  from functools import partial
12
  from kiui.op import recenter
13
  import kiui
14
-
15
 
16
  # we load the pre-trained model from HF
17
  class LRMGeneratorWrapper:
18
  def __init__(self):
19
- self.config = AutoConfig.from_pretrained("jadechoghari/custom-llrm", trust_remote_code=True)
20
- self.model = AutoModel.from_pretrained("jadechoghari/custom-llrm", trust_remote_code=True)
21
  self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
22
  self.model.to(self.device)
23
  self.model.eval()
@@ -27,7 +29,7 @@ class LRMGeneratorWrapper:
27
 
28
  model_wrapper = LRMGeneratorWrapper()
29
 
30
-
31
  def preprocess_image(image, source_size):
32
  session = new_session("isnet-general-use")
33
  rembg_remove = partial(remove, session=session)
@@ -42,11 +44,9 @@ def preprocess_image(image, source_size):
42
  image = torch.clamp(image, 0, 1)
43
  return image
44
 
 
 
45
  def get_normalized_camera_intrinsics(intrinsics: torch.Tensor):
46
- """
47
- intrinsics: (N, 3, 2), [[fx, fy], [cx, cy], [width, height]]
48
- Return batched fx, fy, cx, cy
49
- """
50
  fx, fy = intrinsics[:, 0, 0], intrinsics[:, 0, 1]
51
  cx, cy = intrinsics[:, 1, 0], intrinsics[:, 1, 1]
52
  width, height = intrinsics[:, 2, 0], intrinsics[:, 2, 1]
@@ -54,52 +54,112 @@ def get_normalized_camera_intrinsics(intrinsics: torch.Tensor):
54
  cx, cy = cx / width, cy / height
55
  return fx, fy, cx, cy
56
 
57
-
58
  def build_camera_principle(RT: torch.Tensor, intrinsics: torch.Tensor):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  """
60
  RT: (N, 3, 4)
61
  intrinsics: (N, 3, 2), [[fx, fy], [cx, cy], [width, height]]
62
  """
 
63
  fx, fy, cx, cy = get_normalized_camera_intrinsics(intrinsics)
 
 
 
 
 
64
  return torch.cat([
65
- RT.reshape(-1, 12),
66
- fx.unsqueeze(-1), fy.unsqueeze(-1), cx.unsqueeze(-1), cy.unsqueeze(-1),
67
  ], dim=-1)
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- def _default_intrinsics():
71
- fx = fy = 384
72
- cx = cy = 256
73
- w = h = 512
74
- intrinsics = torch.tensor([
75
- [fx, fy],
76
- [cx, cy],
77
- [w, h],
78
- ], dtype=torch.float32)
79
- return intrinsics
80
 
81
- def _default_source_camera(batch_size: int = 1):
82
- dist_to_center = 1.5
83
- canonical_camera_extrinsics = torch.tensor([[
84
- [0, 0, 1, 1],
85
- [1, 0, 0, 0],
86
- [0, 1, 0, 0],
87
- ]], dtype=torch.float32)
88
- canonical_camera_intrinsics = _default_intrinsics().unsqueeze(0)
89
- source_camera = build_camera_principle(canonical_camera_extrinsics, canonical_camera_intrinsics)
90
- return source_camera.repeat(batch_size, 1)
91
-
92
-
93
- #Ref: https://github.com/jadechoghari/vfusion3d/blob/main/lrm/inferrer.py
94
- def generate_mesh(image, source_size=512, render_size=384, mesh_size=512, export_mesh=True):
95
  image = preprocess_image(image, source_size).to(model_wrapper.device)
96
  source_camera = _default_source_camera(batch_size=1).to(model_wrapper.device)
97
- # TODO: export video we need render_camera
98
- # render_camera = _default_render_cameras(batch_size=1).to(model_wrapper.device)
99
 
100
  with torch.no_grad():
101
  planes = model_wrapper.forward(image, source_camera)
102
-
103
  if export_mesh:
104
  grid_out = model_wrapper.model.synthesizer.forward_grid(planes=planes, grid_size=mesh_size)
105
  vtx, faces = mcubes.marching_cubes(grid_out['sigma'].float().squeeze(0).squeeze(-1).cpu().numpy(), 1.0)
@@ -108,34 +168,92 @@ def generate_mesh(image, source_size=512, render_size=384, mesh_size=512, export
108
  vtx_colors = model_wrapper.model.synthesizer.forward_points(planes, vtx_tensor)['rgb'].float().squeeze(0).cpu().numpy()
109
  vtx_colors = (vtx_colors * 255).astype(np.uint8)
110
  mesh = trimesh.Trimesh(vertices=vtx, faces=faces, vertex_colors=vtx_colors)
111
-
112
  mesh_path = "awesome_mesh.obj"
113
  mesh.export(mesh_path, 'obj')
114
- return mesh_path
115
 
116
- # we will convert image to mesh
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  def step_1_generate_obj(image):
118
- mesh_path = generate_mesh(image)
119
- return mesh_path
 
 
 
 
120
 
121
- # we will convert mesh to 3d-image
122
- def step_2_display_3d_model(mesh_file):
123
  return mesh_file
124
 
 
 
 
 
125
  with gr.Blocks() as demo:
126
  with gr.Row():
 
127
  with gr.Column():
128
  img_input = gr.Image(type="pil", label="Input Image")
129
- generate_button = gr.Button("Generate and Visualize 3D Model")
 
 
130
  obj_file_output = gr.File(label="Download .obj File")
131
-
 
132
  with gr.Column():
133
- model_output = gr.Model3D(clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model Visualization")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  def generate_and_visualize(image):
136
  mesh_path = step_1_generate_obj(image)
137
  return mesh_path, mesh_path
138
-
139
- generate_button.click(generate_and_visualize, inputs=img_input, outputs=[obj_file_output, model_output])
140
 
141
- demo.launch()
 
 
 
 
 
 
 
 
1
+ # final one
2
  import torch
3
  import gradio as gr
4
  import os
5
  import numpy as np
6
  import trimesh
7
  import mcubes
8
+ import imageio
9
  from torchvision.utils import save_image
10
  from PIL import Image
11
  from transformers import AutoModel, AutoConfig
 
13
  from functools import partial
14
  from kiui.op import recenter
15
  import kiui
16
+ from gradio_litmodel3d import LitModel3D
17
 
18
  # we load the pre-trained model from HF
19
  class LRMGeneratorWrapper:
20
  def __init__(self):
21
+ self.config = AutoConfig.from_pretrained("jadechoghari/vfusion3d", trust_remote_code=True)
22
+ self.model = AutoModel.from_pretrained("jadechoghari/vfusion3d", trust_remote_code=True)
23
  self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
24
  self.model.to(self.device)
25
  self.model.eval()
 
29
 
30
  model_wrapper = LRMGeneratorWrapper()
31
 
32
+ # we preprocess the input image
33
  def preprocess_image(image, source_size):
34
  session = new_session("isnet-general-use")
35
  rembg_remove = partial(remove, session=session)
 
44
  image = torch.clamp(image, 0, 1)
45
  return image
46
 
47
+ # Copied from https://github.com/facebookresearch/vfusion3d/blob/main/lrm/cam_utils.py and
48
+ # https://github.com/facebookresearch/vfusion3d/blob/main/lrm/inferrer.py
49
  def get_normalized_camera_intrinsics(intrinsics: torch.Tensor):
 
 
 
 
50
  fx, fy = intrinsics[:, 0, 0], intrinsics[:, 0, 1]
51
  cx, cy = intrinsics[:, 1, 0], intrinsics[:, 1, 1]
52
  width, height = intrinsics[:, 2, 0], intrinsics[:, 2, 1]
 
54
  cx, cy = cx / width, cy / height
55
  return fx, fy, cx, cy
56
 
 
57
  def build_camera_principle(RT: torch.Tensor, intrinsics: torch.Tensor):
58
+ fx, fy, cx, cy = get_normalized_camera_intrinsics(intrinsics)
59
+ return torch.cat([
60
+ RT.reshape(-1, 12),
61
+ fx.unsqueeze(-1), fy.unsqueeze(-1), cx.unsqueeze(-1), cy.unsqueeze(-1),
62
+ ], dim=-1)
63
+
64
+ def _default_intrinsics():
65
+ fx = fy = 384
66
+ cx = cy = 256
67
+ w = h = 512
68
+ intrinsics = torch.tensor([
69
+ [fx, fy],
70
+ [cx, cy],
71
+ [w, h],
72
+ ], dtype=torch.float32)
73
+ return intrinsics
74
+
75
+ def _default_source_camera(batch_size: int = 1):
76
+ canonical_camera_extrinsics = torch.tensor([[
77
+ [0, 0, 1, 1],
78
+ [1, 0, 0, 0],
79
+ [0, 1, 0, 0],
80
+ ]], dtype=torch.float32)
81
+ canonical_camera_intrinsics = _default_intrinsics().unsqueeze(0)
82
+ source_camera = build_camera_principle(canonical_camera_extrinsics, canonical_camera_intrinsics)
83
+ return source_camera.repeat(batch_size, 1)
84
+
85
+ def _center_looking_at_camera_pose(camera_position: torch.Tensor, look_at: torch.Tensor = None, up_world: torch.Tensor = None):
86
+ """
87
+ camera_position: (M, 3)
88
+ look_at: (3)
89
+ up_world: (3)
90
+ return: (M, 3, 4)
91
+ """
92
+ # by default, looking at the origin and world up is pos-z
93
+ if look_at is None:
94
+ look_at = torch.tensor([0, 0, 0], dtype=torch.float32)
95
+ if up_world is None:
96
+ up_world = torch.tensor([0, 0, 1], dtype=torch.float32)
97
+ look_at = look_at.unsqueeze(0).repeat(camera_position.shape[0], 1)
98
+ up_world = up_world.unsqueeze(0).repeat(camera_position.shape[0], 1)
99
+
100
+ z_axis = camera_position - look_at
101
+ z_axis = z_axis / z_axis.norm(dim=-1, keepdim=True)
102
+ x_axis = torch.cross(up_world, z_axis)
103
+ x_axis = x_axis / x_axis.norm(dim=-1, keepdim=True)
104
+ y_axis = torch.cross(z_axis, x_axis)
105
+ y_axis = y_axis / y_axis.norm(dim=-1, keepdim=True)
106
+ extrinsics = torch.stack([x_axis, y_axis, z_axis, camera_position], dim=-1)
107
+ return extrinsics
108
+
109
+ def compose_extrinsic_RT(RT: torch.Tensor):
110
+ """
111
+ Compose the standard form extrinsic matrix from RT.
112
+ Batched I/O.
113
+ """
114
+ return torch.cat([
115
+ RT,
116
+ torch.tensor([[[0, 0, 0, 1]]], dtype=torch.float32).repeat(RT.shape[0], 1, 1).to(RT.device)
117
+ ], dim=1)
118
+
119
+ def _build_camera_standard(RT: torch.Tensor, intrinsics: torch.Tensor):
120
  """
121
  RT: (N, 3, 4)
122
  intrinsics: (N, 3, 2), [[fx, fy], [cx, cy], [width, height]]
123
  """
124
+ E = compose_extrinsic_RT(RT)
125
  fx, fy, cx, cy = get_normalized_camera_intrinsics(intrinsics)
126
+ I = torch.stack([
127
+ torch.stack([fx, torch.zeros_like(fx), cx], dim=-1),
128
+ torch.stack([torch.zeros_like(fy), fy, cy], dim=-1),
129
+ torch.tensor([[0, 0, 1]], dtype=torch.float32, device=RT.device).repeat(RT.shape[0], 1),
130
+ ], dim=1)
131
  return torch.cat([
132
+ E.reshape(-1, 16),
133
+ I.reshape(-1, 9),
134
  ], dim=-1)
135
 
136
+ def _default_render_cameras(batch_size: int = 1):
137
+ M = 160
138
+ radius = 1.5
139
+ elevation = 0
140
+ camera_positions = []
141
+ rand_theta = np.random.uniform(0, np.pi/180)
142
+ elevation = np.radians(elevation)
143
+ for i in range(M):
144
+ theta = 2 * np.pi * i / M + rand_theta
145
+ x = radius * np.cos(theta) * np.cos(elevation)
146
+ y = radius * np.sin(theta) * np.cos(elevation)
147
+ z = radius * np.sin(elevation)
148
+ camera_positions.append([x, y, z])
149
+ camera_positions = torch.tensor(camera_positions, dtype=torch.float32)
150
+ extrinsics = _center_looking_at_camera_pose(camera_positions)
151
 
152
+ render_camera_intrinsics = _default_intrinsics().unsqueeze(0).repeat(extrinsics.shape[0], 1, 1)
153
+ render_cameras = _build_camera_standard(extrinsics, render_camera_intrinsics)
154
+ return render_cameras.unsqueeze(0).repeat(batch_size, 1, 1)
 
 
 
 
 
 
 
155
 
156
+ def generate_mesh(image, source_size=512, render_size=384, mesh_size=512, export_mesh=False, export_video=True, fps=30):
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  image = preprocess_image(image, source_size).to(model_wrapper.device)
158
  source_camera = _default_source_camera(batch_size=1).to(model_wrapper.device)
 
 
159
 
160
  with torch.no_grad():
161
  planes = model_wrapper.forward(image, source_camera)
162
+
163
  if export_mesh:
164
  grid_out = model_wrapper.model.synthesizer.forward_grid(planes=planes, grid_size=mesh_size)
165
  vtx, faces = mcubes.marching_cubes(grid_out['sigma'].float().squeeze(0).squeeze(-1).cpu().numpy(), 1.0)
 
168
  vtx_colors = model_wrapper.model.synthesizer.forward_points(planes, vtx_tensor)['rgb'].float().squeeze(0).cpu().numpy()
169
  vtx_colors = (vtx_colors * 255).astype(np.uint8)
170
  mesh = trimesh.Trimesh(vertices=vtx, faces=faces, vertex_colors=vtx_colors)
171
+
172
  mesh_path = "awesome_mesh.obj"
173
  mesh.export(mesh_path, 'obj')
 
174
 
175
+ return mesh_path, mesh_path
176
+
177
+ if export_video:
178
+ render_cameras = _default_render_cameras(batch_size=1).to(model_wrapper.device)
179
+ frames = []
180
+ chunk_size = 2
181
+ for i in range(0, render_cameras.shape[1], chunk_size):
182
+ frame_chunk = model_wrapper.model.synthesizer(
183
+ planes,
184
+ render_cameras[:, i:i + chunk_size],
185
+ render_size,
186
+ render_size,
187
+ 0,
188
+ 0
189
+ )
190
+ frames.append(frame_chunk['images_rgb'])
191
+
192
+ frames = torch.cat(frames, dim=1)
193
+ frames = (frames.permute(0, 2, 3, 1).cpu().numpy() * 255).astype(np.uint8)
194
+
195
+ video_path = "awesome_video.mp4"
196
+ imageio.mimwrite(video_path, frames, fps=fps)
197
+
198
+ return None, video_path
199
+
200
+ return None, None
201
+
202
  def step_1_generate_obj(image):
203
+ mesh_path, _ = generate_mesh(image, export_mesh=True)
204
+ return mesh_path, mesh_path
205
+
206
+ def step_2_generate_video(image):
207
+ _, video_path = generate_mesh(image, export_video=True)
208
+ return video_path
209
 
210
+ def step_3_display_3d_model(mesh_file):
 
211
  return mesh_file
212
 
213
+ # set up the example files from assets folder, we limit to 10
214
+ example_folder = "assets"
215
+ examples = [os.path.join(example_folder, f) for f in os.listdir(example_folder) if f.endswith(('.png', '.jpg', '.jpeg'))][:10]
216
+
217
  with gr.Blocks() as demo:
218
  with gr.Row():
219
+
220
  with gr.Column():
221
  img_input = gr.Image(type="pil", label="Input Image")
222
+ examples_component = gr.Examples(examples=examples, inputs=img_input, outputs=None, examples_per_page=3)
223
+ generate_mesh_button = gr.Button("Generate and Download Mesh")
224
+ generate_video_button = gr.Button("Generate and Download Video")
225
  obj_file_output = gr.File(label="Download .obj File")
226
+ video_file_output = gr.File(label="Download Video")
227
+
228
  with gr.Column():
229
+ model_output = LitModel3D(
230
+ clear_color=[0.1, 0.1, 0.1, 0], # can adjust background color for better contrast
231
+ label="3D Model Visualization",
232
+ scale=1.0,
233
+ tonemapping="aces", # can use aces tonemapping for more realistic lighting
234
+ exposure=1.0, # can adjust exposure to control brightness
235
+ contrast=1.1, # can slightly increase contrast for better depth
236
+ camera_position=(0, 0, 2), # will set initial camera position to center the model
237
+ zoom_speed=0.5, # will adjust zoom speed for better control
238
+ pan_speed=0.5, # will adjust pan speed for better control
239
+ interactive=True # this allow users to interact with the model
240
+ )
241
+
242
+
243
+ # clear outputs
244
+ def clear_model_viewer():
245
+ """Reset the Model3D component before loading a new model."""
246
+ return gr.update(value=None)
247
 
248
  def generate_and_visualize(image):
249
  mesh_path = step_1_generate_obj(image)
250
  return mesh_path, mesh_path
 
 
251
 
252
+ # first we clear the existing 3D model
253
+ img_input.change(clear_model_viewer, inputs=None, outputs=model_output)
254
+
255
+ # then, generate the mesh and video
256
+ generate_mesh_button.click(step_1_generate_obj, inputs=img_input, outputs=[obj_file_output, model_output])
257
+ generate_video_button.click(step_2_generate_video, inputs=img_input, outputs=video_file_output)
258
+
259
+ demo.launch(debug=True)