codic commited on
Commit
2d8a744
·
verified ·
1 Parent(s): e11f9a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -469
app.py CHANGED
@@ -12,312 +12,6 @@ from gradio_client import Client
12
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
13
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
14
 
15
- # Background removal API client
16
- client = Client("not-lain/background-removal")
17
- def process_image(image_path, depth_map_path=None):
18
- image_path = Path(image_path)
19
- image_raw = Image.open(image_path)
20
- image = image_raw.resize(
21
- (800, int(800 * image_raw.size[1] / image_raw.size[0])),
22
- Image.Resampling.LANCZOS,
23
- )
24
-
25
- # Step 1: Perform background removal
26
- result = client.predict(
27
- f=str(image_path), # Convert Path to string
28
- api_name="/png"
29
- )
30
-
31
- # Load the foreground image from the returned file path
32
- foreground_image_path = result # This contains the path to the processed image
33
- foreground_image = Image.open(foreground_image_path) # Open the image
34
-
35
- if depth_map_path:
36
- # Load and resize the user-provided depth map to match the RGB image size
37
- depth_image_raw = Image.open(depth_map_path)
38
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
39
- depth_image = np.array(depth_image)
40
-
41
- # Normalize depth map if needed
42
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
43
- depth_image = (depth_image * 255).astype('uint8')
44
-
45
- else:
46
- # Automatically generate the depth map using the DPT model
47
- encoding = feature_extractor(image, return_tensors="pt")
48
- with torch.no_grad():
49
- outputs = model(**encoding)
50
- predicted_depth = outputs.predicted_depth
51
-
52
- # Interpolate to match the image size
53
- prediction = torch.nn.functional.interpolate(
54
- predicted_depth.unsqueeze(1),
55
- size=image.size[::-1],
56
- mode="bicubic",
57
- align_corners=False,
58
- ).squeeze()
59
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
60
-
61
- # Step 2: Create flat background depth layer and combine with foreground
62
- background_depth_value = 20 # Slight depth for background
63
- background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
64
-
65
-
66
- # Ensure foreground_mask is boolean
67
- foreground_mask_resized = np.array(foreground_image.convert("L").resize(image.size, Image.Resampling.NEAREST)) > 0
68
-
69
- # Combine the flat background with the foreground depth
70
- combined_depth_image = np.where(foreground_mask_resized[..., None], depth_image[..., None], background_depth[..., None])
71
-
72
- # Step 3: Generate 3D model using the combined depth map
73
- try:
74
- gltf_path = create_3d_obj(np.array(image), combined_depth_image, image_path)
75
- img = Image.fromarray(combined_depth_image)
76
- return [img, gltf_path, gltf_path]
77
- except Exception as e:
78
- print(f"Error creating 3D object: {e}")
79
- raise Exception("Error reconstructing 3D model")
80
-
81
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
82
- depth_o3d = o3d.geometry.Image(depth_image)
83
- image_o3d = o3d.geometry.Image(rgb_image)
84
- rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
85
- image_o3d, depth_o3d, convert_rgb_to_intensity=False
86
- )
87
- w = int(depth_image.shape[1])
88
- h = int(depth_image.shape[0])
89
-
90
- camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
91
- camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
92
-
93
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
94
-
95
- print("Estimating normals")
96
- pcd.normals = o3d.utility.Vector3dVector(
97
- np.zeros((1, 3))
98
- ) # Invalidate existing normals
99
- pcd.estimate_normals(
100
- search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
101
- )
102
- pcd.orient_normals_towards_camera_location(
103
- camera_location=np.array([0.0, 0.0, 1000.0])
104
- )
105
- pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
106
- pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
107
-
108
- print("Running Poisson surface reconstruction")
109
- with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
110
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
111
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
112
- )
113
-
114
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
115
- print(f"Voxel size = {voxel_size:e}")
116
- mesh = mesh_raw.simplify_vertex_clustering(
117
- voxel_size=voxel_size,
118
- contraction=o3d.geometry.SimplificationContraction.Average,
119
- )
120
-
121
- # Apply smoothing
122
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
123
-
124
- bbox = pcd.get_axis_aligned_bounding_box()
125
- mesh_crop = mesh.crop(bbox)
126
- gltf_path = f"./{image_path.stem}.gltf"
127
- o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
128
- return gltf_path
129
-
130
- # Gradio interface setup
131
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
132
- description = "This demo allows users to provide an RGB image and optionally a depth map to create a 3D object. If no depth map is provided, the DPT model will generate it."
133
- examples = [["examples/" + img] for img in os.listdir("examples/")]
134
-
135
- iface = gr.Interface(
136
- fn=process_image,
137
- inputs=[
138
- gr.Image(type="filepath", label="Input Image"),
139
- gr.Image(type="filepath", label="Input Depth Map (optional)"),
140
- ],
141
- outputs=[
142
- gr.Image(label="Predicted Depth", type="pil"),
143
- gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
144
- gr.File(label="3D gLTF File"),
145
- ],
146
- title=title,
147
- description=description,
148
- examples=examples,
149
- allow_flagging="never",
150
- cache_examples=False,
151
- )
152
-
153
- iface.launch(debug=True, show_api=True, share=True)
154
- import gradio as gr
155
- from transformers import DPTFeatureExtractor, DPTForDepthEstimation
156
- import torch
157
- import numpy as np
158
- from PIL import Image
159
- import open3d as o3d
160
- from pathlib import Path
161
- import os
162
- from gradio_client import Client
163
-
164
- # Initialize feature extractor and model for depth estimation
165
- feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
166
- model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
167
-
168
- # Background removal API client
169
- client = Client("not-lain/background-removal")
170
-
171
- def process_image(image_path, depth_map_path=None):
172
- image_path = Path(image_path)
173
- image_raw = Image.open(image_path)
174
- image = image_raw.resize(
175
- (800, int(800 * image_raw.size[1] / image_raw.size[0])),
176
- Image.Resampling.LANCZOS,
177
- )
178
-
179
- # Step 1: Perform background removal
180
- result = client.predict(
181
- f=image_path, # Directly use the image path
182
- api_name="/png"
183
- )
184
-
185
- # Load the foreground image from the returned file path
186
- foreground_image_path = result # This contains the path to the processed image
187
- foreground_image = Image.open(foreground_image_path) # Open the image
188
-
189
- if depth_map_path:
190
- # Load and resize the user-provided depth map to match the RGB image size
191
- depth_image_raw = Image.open(depth_map_path)
192
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
193
- depth_image = np.array(depth_image)
194
-
195
- # Normalize depth map if needed
196
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
197
- depth_image = (depth_image * 255).astype('uint8')
198
-
199
- else:
200
- # Automatically generate the depth map using the DPT model
201
- encoding = feature_extractor(image, return_tensors="pt")
202
- with torch.no_grad():
203
- outputs = model(**encoding)
204
- predicted_depth = outputs.predicted_depth
205
-
206
- # Interpolate to match the image size
207
- prediction = torch.nn.functional.interpolate(
208
- predicted_depth.unsqueeze(1),
209
- size=image.size[::-1],
210
- mode="bicubic",
211
- align_corners=False,
212
- ).squeeze()
213
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
214
-
215
- # Step 2: Create flat background depth layer and combine with foreground
216
- background_depth_value = 20 # Slight depth for background
217
- background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
218
-
219
- # Foreground mask from background removal (assumed to be binary mask)
220
- foreground_mask = np.array(foreground_image.convert("L")) > 0
221
-
222
- # Combine the flat background with the foreground depth
223
- combined_depth_image = np.where(foreground_mask, depth_image, background_depth)
224
-
225
- # Step 3: Generate 3D model using the combined depth map
226
- try:
227
- gltf_path = create_3d_obj(np.array(image), combined_depth_image, image_path)
228
- img = Image.fromarray(combined_depth_image)
229
- return [img, gltf_path, gltf_path]
230
- except Exception as e:
231
- print(f"Error creating 3D object: {e}")
232
- raise Exception("Error reconstructing 3D model")
233
-
234
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
235
- depth_o3d = o3d.geometry.Image(depth_image)
236
- image_o3d = o3d.geometry.Image(rgb_image)
237
- rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
238
- image_o3d, depth_o3d, convert_rgb_to_intensity=False
239
- )
240
- w = int(depth_image.shape[1])
241
- h = int(depth_image.shape[0])
242
-
243
- camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
244
- camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
245
-
246
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
247
-
248
- print("Estimating normals")
249
- pcd.normals = o3d.utility.Vector3dVector(
250
- np.zeros((1, 3))
251
- ) # Invalidate existing normals
252
- pcd.estimate_normals(
253
- search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
254
- )
255
- pcd.orient_normals_towards_camera_location(
256
- camera_location=np.array([0.0, 0.0, 1000.0])
257
- )
258
- pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
259
- pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
260
-
261
- print("Running Poisson surface reconstruction")
262
- with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
263
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
264
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
265
- )
266
-
267
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
268
- print(f"Voxel size = {voxel_size:e}")
269
- mesh = mesh_raw.simplify_vertex_clustering(
270
- voxel_size=voxel_size,
271
- contraction=o3d.geometry.SimplificationContraction.Average,
272
- )
273
-
274
- # Apply smoothing
275
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
276
-
277
- bbox = pcd.get_axis_aligned_bounding_box()
278
- mesh_crop = mesh.crop(bbox)
279
- gltf_path = f"./{image_path.stem}.gltf"
280
- o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
281
- return gltf_path
282
-
283
- # Gradio interface setup
284
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
285
- description = "This demo allows users to provide an RGB image and optionally a depth map to create a 3D object. If no depth map is provided, the DPT model will generate it."
286
- examples = [["examples/" + img] for img in os.listdir("examples/")]
287
-
288
- iface = gr.Interface(
289
- fn=process_image,
290
- inputs=[
291
- gr.Image(type="filepath", label="Input Image"),
292
- gr.Image(type="filepath", label="Input Depth Map (optional)"),
293
- ],
294
- outputs=[
295
- gr.Image(label="Predicted Depth", type="pil"),
296
- gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
297
- gr.File(label="3D gLTF File"),
298
- ],
299
- title=title,
300
- description=description,
301
- examples=examples,
302
- allow_flagging="never",
303
- cache_examples=False,
304
- )
305
-
306
- iface.launch(debug=True, show_api=True, share=True)
307
- import gradio as gr
308
- from transformers import DPTFeatureExtractor, DPTForDepthEstimation
309
- import torch
310
- import numpy as np
311
- from PIL import Image
312
- import open3d as o3d
313
- from pathlib import Path
314
- import os
315
- from gradio_client import Client
316
-
317
- # Initialize feature extractor and model for depth estimation
318
- feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
319
- model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
320
-
321
  # Background removal API client
322
  client = Client("not-lain/background-removal")
323
 
@@ -331,160 +25,7 @@ def process_image(image_path, depth_map_path=None):
331
 
332
  # Step 1: Perform background removal
333
  result = client.predict(
334
- f=image_path, # Directly use the image path
335
- api_name="/png"
336
- )
337
-
338
- # Load the foreground image from the returned file path
339
- foreground_image_path = result # This contains the path to the processed image
340
- foreground_image = Image.open(foreground_image_path) # Open the image
341
-
342
- if depth_map_path:
343
- # Load and resize the user-provided depth map to match the RGB image size
344
- depth_image_raw = Image.open(depth_map_path)
345
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
346
- depth_image = np.array(depth_image)
347
-
348
- # Normalize depth map if needed
349
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
350
- depth_image = (depth_image * 255).astype('uint8')
351
-
352
- else:
353
- # Automatically generate the depth map using the DPT model
354
- encoding = feature_extractor(image, return_tensors="pt")
355
- with torch.no_grad():
356
- outputs = model(**encoding)
357
- predicted_depth = outputs.predicted_depth
358
-
359
- # Interpolate to match the image size
360
- prediction = torch.nn.functional.interpolate(
361
- predicted_depth.unsqueeze(1),
362
- size=image.size[::-1],
363
- mode="bicubic",
364
- align_corners=False,
365
- ).squeeze()
366
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
367
-
368
- # Step 2: Create flat background depth layer and combine with foreground
369
- background_depth_value = 20 # Slight depth for background
370
- background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
371
-
372
- # Foreground mask from background removal (assumed to be binary mask)
373
- foreground_mask = np.array(foreground_image.convert("L")) > 0
374
-
375
- # Combine the flat background with the foreground depth
376
- combined_depth_image = np.where(foreground_mask, depth_image, background_depth)
377
-
378
- # Step 3: Generate 3D model using the combined depth map
379
- try:
380
- gltf_path = create_3d_obj(np.array(image), combined_depth_image, image_path)
381
- img = Image.fromarray(combined_depth_image)
382
- return [img, gltf_path, gltf_path]
383
- except Exception as e:
384
- print(f"Error creating 3D object: {e}")
385
- raise Exception("Error reconstructing 3D model")
386
-
387
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
388
- depth_o3d = o3d.geometry.Image(depth_image)
389
- image_o3d = o3d.geometry.Image(rgb_image)
390
- rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
391
- image_o3d, depth_o3d, convert_rgb_to_intensity=False
392
- )
393
- w = int(depth_image.shape[1])
394
- h = int(depth_image.shape[0])
395
-
396
- camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
397
- camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
398
-
399
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
400
-
401
- print("Estimating normals")
402
- pcd.normals = o3d.utility.Vector3dVector(
403
- np.zeros((1, 3))
404
- ) # Invalidate existing normals
405
- pcd.estimate_normals(
406
- search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
407
- )
408
- pcd.orient_normals_towards_camera_location(
409
- camera_location=np.array([0.0, 0.0, 1000.0])
410
- )
411
- pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
412
- pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
413
-
414
- print("Running Poisson surface reconstruction")
415
- with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
416
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
417
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
418
- )
419
-
420
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
421
- print(f"Voxel size = {voxel_size:e}")
422
- mesh = mesh_raw.simplify_vertex_clustering(
423
- voxel_size=voxel_size,
424
- contraction=o3d.geometry.SimplificationContraction.Average,
425
- )
426
-
427
- # Apply smoothing
428
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
429
-
430
- bbox = pcd.get_axis_aligned_bounding_box()
431
- mesh_crop = mesh.crop(bbox)
432
- gltf_path = f"./{image_path.stem}.gltf"
433
- o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
434
- return gltf_path
435
-
436
- # Gradio interface setup
437
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
438
- description = "This demo allows users to provide an RGB image and optionally a depth map to create a 3D object. If no depth map is provided, the DPT model will generate it."
439
- examples = [["examples/" + img] for img in os.listdir("examples/")]
440
-
441
- iface = gr.Interface(
442
- fn=process_image,
443
- inputs=[
444
- gr.Image(type="filepath", label="Input Image"),
445
- gr.Image(type="filepath", label="Input Depth Map (optional)"),
446
- ],
447
- outputs=[
448
- gr.Image(label="Predicted Depth", type="pil"),
449
- gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
450
- gr.File(label="3D gLTF File"),
451
- ],
452
- title=title,
453
- description=description,
454
- examples=examples,
455
- allow_flagging="never",
456
- cache_examples=False,
457
- )
458
-
459
- iface.launch(debug=True, show_api=True, share=True)
460
- import gradio as gr
461
- from transformers import DPTFeatureExtractor, DPTForDepthEstimation
462
- import torch
463
- import numpy as np
464
- from PIL import Image
465
- import open3d as o3d
466
- from pathlib import Path
467
- import os
468
- from gradio_client import Client
469
-
470
- # Initialize feature extractor and model for depth estimation
471
- feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
472
- model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
473
-
474
- # Background removal API client
475
- client = Client("not-lain/background-removal")
476
-
477
- def process_image(image_path, depth_map_path=None):
478
- image_path = Path(image_path)
479
- image_raw = Image.open(image_path)
480
- image = image_raw.resize(
481
- (800, int(800 * image_raw.size[1] / image_raw.size[0])),
482
- Image.Resampling.LANCZOS,
483
- )
484
-
485
- # Step 1: Perform background removal
486
- result = client.predict(
487
- f=image_path, # Directly use the image path
488
  api_name="/png"
489
  )
490
 
@@ -522,11 +63,11 @@ def process_image(image_path, depth_map_path=None):
522
  background_depth_value = 20 # Slight depth for background
523
  background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
524
 
525
- # Foreground mask from background removal (assumed to be binary mask)
526
- foreground_mask = np.array(foreground_image.convert("L")) > 0
527
 
528
  # Combine the flat background with the foreground depth
529
- combined_depth_image = np.where(foreground_mask, depth_image, background_depth)
530
 
531
  # Step 3: Generate 3D model using the combined depth map
532
  try:
@@ -552,15 +93,11 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
552
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
553
 
554
  print("Estimating normals")
555
- pcd.normals = o3d.utility.Vector3dVector(
556
- np.zeros((1, 3))
557
- ) # Invalidate existing normals
558
  pcd.estimate_normals(
559
  search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
560
  )
561
- pcd.orient_normals_towards_camera_location(
562
- camera_location=np.array([0.0, 0.0, 1000.0])
563
- )
564
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
565
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
566
 
 
12
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
13
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Background removal API client
16
  client = Client("not-lain/background-removal")
17
 
 
25
 
26
  # Step 1: Perform background removal
27
  result = client.predict(
28
+ f=str(image_path), # Convert Path to string
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  api_name="/png"
30
  )
31
 
 
63
  background_depth_value = 20 # Slight depth for background
64
  background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
65
 
66
+ # Ensure foreground_mask is boolean
67
+ foreground_mask_resized = np.array(foreground_image.convert("L").resize(image.size, Image.Resampling.NEAREST)) > 0
68
 
69
  # Combine the flat background with the foreground depth
70
+ combined_depth_image = np.where(foreground_mask_resized[..., None], depth_image[..., None], background_depth[..., None])
71
 
72
  # Step 3: Generate 3D model using the combined depth map
73
  try:
 
93
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
94
 
95
  print("Estimating normals")
96
+ pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Invalidate existing normals
 
 
97
  pcd.estimate_normals(
98
  search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
99
  )
100
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
 
 
101
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
102
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
103