codic commited on
Commit
f7e7eba
·
verified ·
1 Parent(s): bfdd2d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -176
app.py CHANGED
@@ -9,7 +9,7 @@ from rembg import remove
9
  import open3d as o3d
10
  from skimage import filters
11
  import xformers
12
-
13
 
14
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
15
  if os.environ.get("SPACES_ZERO_GPU") is not None:
@@ -52,8 +52,7 @@ def predict_depth(image: Image.Image):
52
  # Convert image to RGB
53
  image = image.convert("RGB")
54
 
55
- # Step 1: Remove background to isolate the main subject
56
- # Background removal ensures depth is applied only to the subject
57
  foreground = remove(image)
58
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
59
 
@@ -67,8 +66,8 @@ def predict_depth(image: Image.Image):
67
  depth_image = vis_depth[0] # First image in the batch
68
 
69
  # Export depth as a 16-bit PNG for higher accuracy
70
- depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
71
- depth_16bit_image = depth_16bit[0]
72
 
73
  # Normalize depth map for further processing
74
  depth_array = np.array(depth_image.convert("L")) # Convert to grayscale
@@ -120,224 +119,108 @@ def predict_depth(image: Image.Image):
120
  npy_filename,
121
  npy_inverted_filename # Return the inverted depth map file path
122
  )
123
- # Clear GPU cache after each iteration
124
- torch.cuda.empty_cache()
125
 
126
- def process_image(image_path, depth_map_path=None):
127
- try:
128
- image_path = image_path
129
- image_raw = Image.open(image_path).convert("RGB")
130
- image = image_raw.resize(
131
- (2072, int(2072 * image_raw.size[1] / image_raw.size[0])),
132
- Image.Resampling.LANCZOS,
133
- )
134
-
135
- # Remove background to isolate the main subject
136
- foreground = remove(image_raw)
137
- foreground = Image.fromarray(np.array(foreground)).convert("RGB")
138
-
139
- # Load or generate depth map
140
- if depth_map_path:
141
- if depth_map_path.endswith('.npy'):
142
- depth_image = np.load(depth_map_path).astype(np.float32)
143
- depth_image = 1 - depth_image # Invert depth for npy files
144
- else:
145
- depth_image_raw = Image.open(depth_map_path).convert("L")
146
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
147
- depth_image = np.array(depth_image, dtype=np.float32)
148
-
149
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
150
- depth_image = np.clip(depth_image, 0, 1)
151
- else:
152
- # Generate depth map using DPT model
153
- # encoding = feature_extractor(foreground, return_tensors="pt")
154
- # with torch.no_grad():
155
- # outputs = model(**encoding)
156
- # predicted_depth = outputs.predicted_depth
157
-
158
- # prediction = torch.nn.functional.interpolate(
159
- # predicted_depth.unsqueeze(1),
160
- # size=image.size[::-1],
161
- # mode="bicubic",
162
- # align_corners=False,
163
- # ).squeeze()
164
- # depth_image = prediction.cpu().numpy().astype(np.float32)
165
-
166
- # depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
167
- # depth_image = np.clip(depth_image, 0, 1)
168
-
169
- # Use the predict_depth function to generate the depth map
170
- depth_image_path, _, _, _ = predict_depth(image_raw)
171
- depth_image = np.array(Image.open(depth_image_path).convert("L"), dtype=np.float32) / 255.0
172
-
173
- # Step 1: Depth refinement (Morphological closing)
174
- kernel = np.ones((3, 3), np.uint8)
175
- depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
176
-
177
- # Step 2: Edge-preserving filter (Enhance small structures)
178
- depth_image = cv2.edgePreservingFilter(
179
- (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
180
- )
181
- depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
182
-
183
- # Step 3: Smooth depth map with Gaussian filter
184
- depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
185
-
186
- # Step 4: Bilateral filter for detail preservation
187
- depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
188
-
189
- # Step 5: Resize the depth map to match the foreground size
190
- depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
191
-
192
- # Step 6: Create an edge-aware mask (if needed for further processing)
193
- mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
194
-
195
- depth_subject_only = np.where(mask, depth_image * mask, 0)
196
- depth_subject_only[~mask] = 0 # Ensure background areas are zeroed out
197
-
198
- # Generate the final depth image with reduced blur artifacts
199
- depth_display = (depth_subject_only * 255).astype(np.uint8)
200
- except Exception as e:
201
- print(f"Error with image process {str(e)}")
202
- try:
203
- # Generate the 3D model
204
- gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
205
- img = Image.fromarray(depth_display)
206
- return [img, gltf_path, gltf_path]
207
- except Exception as e:
208
- print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
209
- gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=9)
210
- img = Image.fromarray(depth_display)
211
- return [img, gltf_path, gltf_path]
212
- # Clear GPU cache after each iteration
213
 
 
 
 
 
 
 
214
  @spaces.GPU(enable_queue=True)
215
- def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
216
  try:
217
- """
218
- Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
219
-
220
- Parameters:
221
- foreground (np.array): The main subject image (RGB).
222
- depth_image (np.array): The depth map array for the main subject only.
223
- image_path (str): Path to save the output model.
224
- depth (int): Poisson reconstruction depth value for high detail.
225
- edge_strength (float): Strength of the edge thresholding for sharper subject boundaries.
226
-
227
- Returns:
228
- str: Path to the saved 3D model (.gltf).
229
- """
230
-
231
- # Resize and normalize depth image to align with the foreground dimensions
232
- depth_image_resized = np.array(
233
- Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
234
- )
235
-
236
- # Normalize depth map and set background to zero (remove background noise)
237
- depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
238
- (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
239
-
240
- # Apply edge detection to enhance the subject’s edges
241
- sobel_x = filters.sobel(depth_image_normalized, axis=0)
242
- sobel_y = filters.sobel(depth_image_normalized, axis=1)
243
- gradient_magnitude = np.hypot(sobel_x, sobel_y)
244
-
245
- # Generate an edge mask that captures only strong edges
246
- edge_mask = gradient_magnitude < (gradient_magnitude.max() * edge_strength)
247
-
248
- # Keep depth values only within the edge mask area (isolating the main subject)
249
- depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
250
-
251
  # Create Open3D RGBD image
252
- depth_o3d = o3d.geometry.Image(depth_image_sharpened)
253
- image_o3d = o3d.geometry.Image(foreground)
254
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
255
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
256
  )
257
-
258
  # Define camera intrinsics based on image dimensions
259
- w, h = foreground.shape[1], foreground.shape[0]
260
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
261
-
262
  # Generate point cloud and apply depth-focused filtering
263
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
264
-
265
  # Check minimum point count for normals estimation
266
  if len(pcd.points) < 100:
267
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
268
-
269
  # Estimate normals with refined parameters
270
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
271
  pcd.orient_normals_consistent_tangent_plane(k=10)
272
-
273
-
274
  # Orient normals towards a distant camera position
275
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
276
-
277
  # Create Poisson mesh using main subject's isolated depth
278
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
279
- pcd, depth=depth, width=0, scale=4, linear_fit=True
280
  )
 
281
  # Remove low-density artifacts
282
  density_threshold = np.quantile(np.asarray(densities), 0.06) # Adjust quantile as needed
283
  vertices_to_remove = densities < density_threshold
284
  mesh_raw.remove_vertices_by_mask(vertices_to_remove)
285
-
286
-
287
  # Simplify with smaller voxel size for more detail
288
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
289
  mesh = mesh_raw.simplify_vertex_clustering(
290
  voxel_size=voxel_size,
291
  contraction=o3d.geometry.SimplificationContraction.Average,
292
  )
293
-
294
  # Apply Laplacian smoothing
295
  mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
296
-
297
  # Crop mesh to bounding box around main subject only
298
  bbox = pcd.get_axis_aligned_bounding_box()
299
  mesh_crop = mesh.crop(bbox)
300
- except Exception as e:
301
- print(f"Error with 3d model {str(e)}")
302
 
303
- # Compute UV mapping for texturing
304
- mesh_crop.compute_vertex_normals()
305
- uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
306
- mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
307
- # Save high-resolution texture image
308
- texture_path = f"./{image_path.stem}_texture_highres.png"
309
- foreground_pil = Image.fromarray(foreground)
310
- high_res_texture = foreground_pil.resize((3096, 3096), Image.LANCZOS) # Increased resolution for finer details
311
- high_res_texture.save(texture_path)
312
-
313
- # Apply the high-resolution texture and export the mesh as a GLTF file
314
- mesh_crop.textures = [o3d.geometry.Image(np.array(high_res_texture))]
315
- gltf_path = f"./{image_path.stem}_model.gltf"
316
- o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
317
 
318
- return gltf_path
 
 
 
 
 
 
 
 
 
 
319
 
320
  # Gradio Interface
321
- title = "Depth Estimation & 3D Reconstruction Demo"
322
- description = "Upload an image and optionally a depth map (in .npy or image format) to generate a 3D model. If no depth map is provided, the DPT model will generate it."
323
-
324
- examples = [["examples/" + img] for img in os.listdir("examples/")]
325
 
326
  iface = gr.Interface(
327
  fn=process_image,
328
- inputs=[
329
- gr.Image(type="filepath", label="Input Image"),
330
- gr.File(type="filepath", label="Input Depth Map (optional)"),
331
- ],
332
  outputs=[
333
- gr.Image(label="Predicted Depth", type="pil"),
334
- gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
335
- gr.File(label="3D gLTF File"),
336
  ],
337
  title=title,
338
  description=description,
339
- examples=examples,
340
- allow_flagging="never",
341
- cache_examples=False,
342
  )
343
- iface.launch(debug=True, show_api=True, share=True)
 
9
  import open3d as o3d
10
  from skimage import filters
11
  import xformers
12
+ import tempfile
13
 
14
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
15
  if os.environ.get("SPACES_ZERO_GPU") is not None:
 
52
  # Convert image to RGB
53
  image = image.convert("RGB")
54
 
55
+ # Remove background to isolate the main subject
 
56
  foreground = remove(image)
57
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
58
 
 
66
  depth_image = vis_depth[0] # First image in the batch
67
 
68
  # Export depth as a 16-bit PNG for higher accuracy
69
+ depth_16bit = save_raw_16bit(depth_image)
70
+ depth_16bit_image = Image.fromarray(depth_16bit)
71
 
72
  # Normalize depth map for further processing
73
  depth_array = np.array(depth_image.convert("L")) # Convert to grayscale
 
119
  npy_filename,
120
  npy_inverted_filename # Return the inverted depth map file path
121
  )
 
 
122
 
123
+ @spaces.GPU(enable_queue=True)
124
+ def save_raw_16bit(depth, fpath="raw.png"):
125
+ if isinstance(depth, torch.Tensor):
126
+ depth = depth.squeeze().cpu().numpy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ assert isinstance(depth, np.ndarray), "Depth must be a torch tensor or numpy array"
129
+ assert depth.ndim == 2, "Depth must be 2D"
130
+ depth = depth * 256 # scale for 16-bit png
131
+ depth = depth.astype(np.uint16)
132
+ return depth
133
+
134
  @spaces.GPU(enable_queue=True)
135
+ def get_mesh(image: Image.Image, depth_image, keep_edges=True):
136
  try:
137
+ # Check if image is too large
138
+ if image.size[0] > 1024 or image.size[1] > 1024:
139
+ image = image.resize((1024, int(1024 * image.size[1] / image.size[0])), Image.Resampling.LANCZOS)
140
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  # Create Open3D RGBD image
142
+ depth_o3d = o3d.geometry.Image(depth_image)
143
+ image_o3d = o3d.geometry.Image(np.array(image))
144
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
145
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
146
  )
147
+
148
  # Define camera intrinsics based on image dimensions
149
+ w, h = np.array(image).shape[1], np.array(image).shape[0]
150
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
151
+
152
  # Generate point cloud and apply depth-focused filtering
153
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
154
+
155
  # Check minimum point count for normals estimation
156
  if len(pcd.points) < 100:
157
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
158
+
159
  # Estimate normals with refined parameters
160
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
161
  pcd.orient_normals_consistent_tangent_plane(k=10)
162
+
 
163
  # Orient normals towards a distant camera position
164
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
165
+
166
  # Create Poisson mesh using main subject's isolated depth
167
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
168
+ pcd, depth=12, width=0, scale=4, linear_fit=True
169
  )
170
+
171
  # Remove low-density artifacts
172
  density_threshold = np.quantile(np.asarray(densities), 0.06) # Adjust quantile as needed
173
  vertices_to_remove = densities < density_threshold
174
  mesh_raw.remove_vertices_by_mask(vertices_to_remove)
175
+
 
176
  # Simplify with smaller voxel size for more detail
177
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
178
  mesh = mesh_raw.simplify_vertex_clustering(
179
  voxel_size=voxel_size,
180
  contraction=o3d.geometry.SimplificationContraction.Average,
181
  )
182
+
183
  # Apply Laplacian smoothing
184
  mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
185
+
186
  # Crop mesh to bounding box around main subject only
187
  bbox = pcd.get_axis_aligned_bounding_box()
188
  mesh_crop = mesh.crop(bbox)
 
 
189
 
190
+ # Save as gltf
191
+ gltf_file = tempfile.NamedTemporaryFile(suffix='.gltf', delete=False)
192
+ gltf_path = gltf_file.name
193
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True, write_ascii=True)
194
+ return gltf_path
195
+ except Exception as e:
196
+ print(f"Error with 3D model generation: {str(e)}")
 
 
 
 
 
 
 
197
 
198
+ def process_image(image_path):
199
+ try:
200
+ image_raw = Image.open(image_path).convert("RGB")
201
+ depth_image_path, depth_16bit_image_path, _, _ = predict_depth(image_raw)
202
+ depth_image = np.array(Image.open(depth_image_path).convert("L"), dtype=np.float32) / 255.0
203
+
204
+ gltf_path = get_mesh(image_raw, depth_image, keep_edges=True)
205
+ return depth_image_path, depth_16bit_image_path, gltf_path
206
+ except Exception as e:
207
+ print(f"Error processing image: {e}")
208
+ return None, None, None
209
 
210
  # Gradio Interface
211
+ title = "Depth Estimation & 3D Reconstruction"
212
+ description = "Upload an image to generate a depth map and 3D model."
 
 
213
 
214
  iface = gr.Interface(
215
  fn=process_image,
216
+ inputs=gr.Image(type="filepath", label="Input Image"),
 
 
 
217
  outputs=[
218
+ gr.Image(label="Depth Image"),
219
+ gr.File(label="Depth 16-bit Image"),
220
+ gr.File(label="3D GLTF File"),
221
  ],
222
  title=title,
223
  description=description,
224
+ allow_flagging="never"
 
 
225
  )
226
+ iface.launch(debug=True, share=True)