codic commited on
Commit
2ab071c
·
verified ·
1 Parent(s): dad1a22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -199
app.py CHANGED
@@ -10,142 +10,7 @@ import open3d as o3d
10
  import tempfile
11
  from skimage import filters
12
  import gc
13
-
14
- # Handle GPU availability in Hugging Face Spaces with ZeroGPU
15
- if os.environ.get("SPACES_ZERO_GPU") is not None:
16
- import spaces
17
- else:
18
- class spaces:
19
- @staticmethod
20
- def GPU(func):
21
- def wrapper(*args, **kwargs):
22
- return func(*args, **kwargs)
23
- return wrapper
24
-
25
- # Device configuration
26
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
- if device.type == "cpu":
28
- print("Using CPU, not GPU")
29
- else:
30
- print("Using ZeroGPU")
31
- torch.cuda.empty_cache()
32
-
33
- # Load the Marigold Depth Pipeline with LCM Scheduler
34
- try:
35
- print("Loading depth pipeline...")
36
- pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
37
- "prs-eth/marigold-depth-lcm-v1-0",
38
- variant="fp16",
39
- torch_dtype=torch.float16
40
- ).to(device)
41
- print("Pipeline loaded successfully.")
42
- print("Loading custom VAE...")
43
- pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
44
- "madebyollin/taesd",
45
- torch_dtype=torch.float16
46
- ).cuda()
47
- print("Custom VAE loaded.")
48
- except Exception as e:
49
- print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
50
- raise
51
-
52
- # Enable XFormers
53
- try:
54
- print("Enabling XFormers...")
55
- pipe.enable_xformers_memory_efficient_attention()
56
- print("XFormers enabled.")
57
- except Exception as e:
58
- print(f"XFormers could not be enabled: {type(e).__name__} - {e}")
59
-
60
- @spaces.GPU(enable_queue=True)
61
- def predict_depth(image: Image.Image):
62
- """Predict depth from an image and return refined depth map."""
63
- try:
64
- print("Processing input image...")
65
- image = image.convert("RGB")
66
-
67
- # Step 1: Remove background to isolate the main subject
68
- print("Removing background...")
69
- foreground = remove(image)
70
- foreground = Image.fromarray(np.array(foreground)).convert("RGB")
71
-
72
- # Depth prediction
73
- print("Predicting depth...")
74
- ensemble_size = 30
75
- num_inference_steps = 7 # Optimized for LCM Scheduler
76
- depth = pipe(
77
- foreground,
78
- ensemble_size=ensemble_size,
79
- num_inference_steps=num_inference_steps,
80
- output_uncertainty=True
81
- )
82
- print("Depth prediction completed.")
83
-
84
- # Extract uncertainty map
85
- uncertainty = depth.uncertainty
86
- uncertainty_display = pipe.image_processor.visualize_depth(uncertainty)
87
- uncertainty_image = uncertainty_display[0] # First image in the batch
88
-
89
- # Visualize depth map
90
- vis_depth = pipe.image_processor.visualize_depth(depth.prediction)
91
- depth_image = vis_depth[0] # First image in the batch
92
-
93
- # Export depth as a 16-bit PNG for higher accuracy
94
- depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
95
- depth_16bit_image = depth_16bit[0]
96
-
97
- # Normalize depth map for further processing
98
- depth_array = np.array(depth_16bit_image, dtype=np.float32) # Convert to 32-bit float if needed
99
-
100
- # Step 2: Refine depth map using bilateral and edge-aware filters
101
- depth_bilateral = cv2.bilateralFilter((depth_array / 65535 * 255).astype(np.uint8), d=12, sigmaColor=90, sigmaSpace=90)
102
- depth_bilateral = depth_bilateral.astype(np.float32) / 255 * 65535 # Convert back to 16-bit scale
103
- laplacian = cv2.Laplacian(depth_bilateral, cv2.CV_32F)
104
- depth_sharpened = cv2.addWeighted(depth_bilateral, 1.6, laplacian, -0.5, 0)
105
-
106
- # Normalize and convert to 16-bit for consistent scaling
107
- depth_normalized = cv2.normalize(depth_sharpened, None, 0, 65535, cv2.NORM_MINMAX, dtype=cv2.CV_16U)
108
-
109
- # Resize depth map to match the foreground size
110
- depth_resized = cv2.resize(
111
- depth_normalized, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4
112
- )
113
-
114
- # Apply a foreground mask
115
- mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
116
- depth_subject_only = np.where(mask, depth_resized, 0)
117
-
118
- # Generate the final depth image
119
- depth_display = np.clip(depth_subject_only / 256, 0, 255).astype(np.uint8) # Convert to 8-bit for display
120
-
121
- # Invert the depth map for visual purposes
122
- depth_inverted = 1.0 - (depth_subject_only / 65535.0) # Normalize and invert
123
- depth_inverted_display = np.clip(depth_inverted * 255, 0, 255).astype(np.uint8)
124
-
125
- # Save the images as PNG files
126
- depth_image_path = "depth_image.png"
127
- depth_16bit_image_path = "depth_16bit_image.png"
128
- Image.fromarray(depth_inverted_display).save(depth_image_path) # Save 8-bit display depth image
129
- Image.fromarray(depth_resized).save(depth_16bit_image_path) # Save 16-bit depth image
130
-
131
- return depth_subject_only / 65535.0, depth_16bit_image_path
132
- except Exception as e:
133
- print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
134
- return None, None
135
-
136
- import gradio as gr
137
- import diffusers
138
- import torch
139
- from PIL import Image
140
- import numpy as np
141
- import cv2
142
- import os
143
- from rembg import remove
144
- import open3d as o3d
145
- import tempfile
146
- from skimage import filters
147
- import gc
148
-
149
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
150
  if os.environ.get("SPACES_ZERO_GPU") is not None:
151
  import spaces
@@ -210,8 +75,8 @@ def predict_depth(image: Image.Image):
210
 
211
  # Depth prediction
212
  print("Predicting depth...")
213
- ensemble_size = 40
214
- num_inference_steps = 7 # Optimized for LCM Scheduler
215
  depth = pipe(
216
  foreground,
217
  ensemble_size=ensemble_size,
@@ -264,9 +129,8 @@ def predict_depth(image: Image.Image):
264
  except Exception as e:
265
  print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
266
  return None, None
267
-
268
- def get_mesh(image: Image.Image, depth):
269
- """Generate 3D mesh from refined non-inverted depth array and image."""
270
  try:
271
  print("Resizing depth image...")
272
  depth_image_resized = Image.fromarray(depth.astype(np.uint16)) # No re-normalization
@@ -290,44 +154,56 @@ def get_mesh(image: Image.Image, depth):
290
  print("Generating point cloud...")
291
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
292
 
293
- # Estimate normals
 
 
 
 
294
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
295
  pcd.orient_normals_consistent_tangent_plane(k=10)
 
 
296
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
297
 
298
- # Generate Poisson mesh
299
  print("Generating Poisson mesh...")
300
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=12)
 
 
301
 
 
302
  density_threshold = np.quantile(np.asarray(densities), 0.06)
303
  vertices_to_remove = densities < density_threshold
304
  mesh_raw.remove_vertices_by_mask(vertices_to_remove)
305
 
306
- # Simplify and smooth mesh
307
- print("Simplifying and smoothing mesh...")
308
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
309
- mesh = mesh_raw.simplify_vertex_clustering(
310
- voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average
311
- )
312
- mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
313
 
314
- # Compute UV mapping for texturing
315
- print("Computing UV mapping...")
316
- mesh.compute_vertex_normals()
317
- uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh.vertices])
318
- mesh.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
319
 
320
- # Save mesh as GLTF
321
- gltf_file = tempfile.NamedTemporaryFile(suffix='.gltf', delete=False)
322
- gltf_path = gltf_file.name
323
- o3d.io.write_triangle_mesh(gltf_path, mesh, write_triangle_uvs=True, write_ascii=True)
324
-
325
- return gltf_path
 
 
 
 
 
 
 
 
 
 
 
326
  except Exception as e:
327
  print(f"Error generating 3D mesh: {type(e).__name__} - {e}")
328
- return None
329
 
330
-
331
  def process_image(image_path):
332
  try:
333
  image_raw = Image.open(image_path).convert("RGB")
@@ -339,7 +215,8 @@ def process_image(image_path):
339
  raise ValueError("Depth prediction or refinement failed.")
340
 
341
  # Generate 3D mesh and retrieve the GLTF path
342
- gltf_path = get_mesh(image_raw, refined_depth)
 
343
  torch.cuda.empty_cache()
344
 
345
  return depth_16bit_path, gltf_path
@@ -352,40 +229,6 @@ def process_image(image_path):
352
  title = "Depth Estimation & 3D Reconstruction"
353
  description = "Upload an image to generate a depth map and 3D model."
354
 
355
- iface = gr.Interface(
356
- fn=process_image,
357
- inputs=gr.Image(type="filepath", label="Input Image"),
358
- outputs=[
359
- gr.File(label="Refined Depth Image (16-bit)"),
360
- gr.File(label="3D Model (GLTF)"),
361
- ],
362
- title=title,
363
- description=description,
364
- allow_flagging="never"
365
- )
366
- iface.launch(debug=True, share=True)
367
- def process_image(image_path):
368
- try:
369
- image_raw = Image.open(image_path).convert("RGB")
370
-
371
- # Predict and refine depth
372
- refined_depth, depth_16bit_path = predict_depth(image_raw)
373
-
374
- if refined_depth is None or depth_16bit_path is None:
375
- raise ValueError("Depth prediction or refinement failed.")
376
-
377
- # Generate 3D mesh and retrieve the GLTF path
378
- gltf_path = get_mesh(image_raw, refined_depth)
379
-
380
- return depth_16bit_path, gltf_path
381
- except Exception as e:
382
- print(f"Error processing image: {e}")
383
- return None, None
384
-
385
- # Gradio Interface
386
- title = "Depth Estimation & 3D Reconstruction"
387
- description = "Upload an image to generate a depth map and 3D model."
388
-
389
  iface = gr.Interface(
390
  fn=process_image,
391
  inputs=gr.Image(type="filepath", label="Input Image"),
 
10
  import tempfile
11
  from skimage import filters
12
  import gc
13
+ import xformers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
15
  if os.environ.get("SPACES_ZERO_GPU") is not None:
16
  import spaces
 
75
 
76
  # Depth prediction
77
  print("Predicting depth...")
78
+ ensemble_size = 30
79
+ num_inference_steps = 5 # Optimized for LCM Scheduler
80
  depth = pipe(
81
  foreground,
82
  ensemble_size=ensemble_size,
 
129
  except Exception as e:
130
  print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
131
  return None, None
132
+ def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray):
133
+ """Generate a 3D mesh with high-resolution texturing from the depth map."""
 
134
  try:
135
  print("Resizing depth image...")
136
  depth_image_resized = Image.fromarray(depth.astype(np.uint16)) # No re-normalization
 
154
  print("Generating point cloud...")
155
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
156
 
157
+ # Check minimum point count for normals estimation
158
+ if len(pcd.points) < 100:
159
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
160
+
161
+ # Estimate normals with refined parameters
162
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
163
  pcd.orient_normals_consistent_tangent_plane(k=10)
164
+
165
+ # Orient normals towards a distant camera position
166
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
167
 
168
+ # Create Poisson mesh using main subject's isolated depth
169
  print("Generating Poisson mesh...")
170
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
171
+ pcd, depth=12, width=0, scale=4, linear_fit=True
172
+ )
173
 
174
+ # Filter mesh by density
175
  density_threshold = np.quantile(np.asarray(densities), 0.06)
176
  vertices_to_remove = densities < density_threshold
177
  mesh_raw.remove_vertices_by_mask(vertices_to_remove)
178
 
179
+ # Apply Laplacian smoothing
180
+ mesh = mesh_raw.filter_smooth_laplacian(number_of_iterations=4)
 
 
 
 
 
181
 
182
+ # Crop mesh to bounding box around main subject
183
+ bbox = pcd.get_axis_aligned_bounding_box()
184
+ mesh_crop = mesh.crop(bbox)
 
 
185
 
186
+ # Compute UV mapping for texturing
187
+ mesh_crop.compute_vertex_normals()
188
+ uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
189
+ mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
190
+
191
+ # Save high-resolution texture image
192
+ texture_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_texture_highres.png"
193
+ foreground_pil = Image.fromarray(foreground)
194
+ high_res_texture = foreground_pil.resize((3096, 3096), Image.LANCZOS) # Increased resolution for finer details
195
+ high_res_texture.save(texture_path)
196
+
197
+ # Apply the high-resolution texture and export the mesh as a GLTF file
198
+ mesh_crop.textures = [o3d.geometry.Image(np.array(high_res_texture))]
199
+ gltf_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_model.gltf"
200
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
201
+
202
+ return gltf_path, texture_path
203
  except Exception as e:
204
  print(f"Error generating 3D mesh: {type(e).__name__} - {e}")
205
+ return None, None
206
 
 
207
  def process_image(image_path):
208
  try:
209
  image_raw = Image.open(image_path).convert("RGB")
 
215
  raise ValueError("Depth prediction or refinement failed.")
216
 
217
  # Generate 3D mesh and retrieve the GLTF path
218
+ foreground = np.array(remove(image_raw))
219
+ gltf_path, texture_path = get_mesh(image_raw, refined_depth, image_path, foreground)
220
  torch.cuda.empty_cache()
221
 
222
  return depth_16bit_path, gltf_path
 
229
  title = "Depth Estimation & 3D Reconstruction"
230
  description = "Upload an image to generate a depth map and 3D model."
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  iface = gr.Interface(
233
  fn=process_image,
234
  inputs=gr.Image(type="filepath", label="Input Image"),