codic commited on
Commit
e49e03a
·
verified ·
1 Parent(s): e7d009a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -82
app.py CHANGED
@@ -6,87 +6,58 @@ from PIL import Image
6
  import open3d as o3d
7
  from pathlib import Path
8
  import os
9
- from gradio_client import Client
10
 
11
- # Initialize feature extractor and model for depth estimation
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
  try:
19
- image_path = Path(image_path)
20
- image_raw = Image.open(image_path)
21
- image = image_raw.resize(
22
- (800, int(800 * image_raw.size[1] / image_raw.size[0])),
23
- Image.Resampling.LANCZOS,
24
- )
25
- print("Image loaded and resized successfully.")
26
-
27
- # Step 1: Perform background removal
28
- try:
29
- result = client.predict(
30
- f=str(image_path), # Convert Path to string
31
- api_name="/png"
32
- )
33
- print("Background removal completed successfully.")
34
- except Exception as bg_removal_exception:
35
- print(f"Background removal failed: {bg_removal_exception}")
36
- raise
37
-
38
- # Load the foreground image from the returned file path
39
- foreground_image_path = result # This contains the path to the processed image
40
- foreground_image = Image.open(foreground_image_path) # Open the image
41
- print("Foreground image loaded successfully.")
42
-
43
- if depth_map_path:
44
- # Load and resize the user-provided depth map to match the RGB image size
45
- depth_image_raw = Image.open(depth_map_path)
46
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
47
- depth_image = np.array(depth_image)
48
-
49
- # Normalize depth map if needed
50
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
51
- depth_image = (depth_image * 255).astype('uint8')
52
- print("Depth map loaded and normalized successfully.")
53
-
54
- else:
55
- # Automatically generate the depth map using the DPT model
56
- encoding = feature_extractor(image, return_tensors="pt")
57
- with torch.no_grad():
58
- outputs = model(**encoding)
59
- predicted_depth = outputs.predicted_depth
60
-
61
- # Interpolate to match the image size
62
- prediction = torch.nn.functional.interpolate(
63
- predicted_depth.unsqueeze(1),
64
- size=image.size[::-1],
65
- mode="bicubic",
66
- align_corners=False,
67
- ).squeeze()
68
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
69
- print("Depth map generated successfully.")
70
-
71
- # Step 2: Create flat background depth layer and combine with foreground
72
- background_depth_value = 20 # Slight depth for background
73
- background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
74
-
75
- # Ensure foreground_mask is boolean
76
- foreground_mask_resized = np.array(foreground_image.convert("L").resize(image.size, Image.Resampling.NEAREST)) > 0
77
-
78
- # Combine the flat background with the foreground depth
79
- combined_depth_image = np.where(foreground_mask_resized[..., None], depth_image[..., None], background_depth[..., None])
80
- print("Combined depth image created successfully.")
81
-
82
- # Step 3: Generate 3D model using the combined depth map
83
- gltf_path = create_3d_obj(np.array(image), combined_depth_image, image_path)
84
- img = Image.fromarray(combined_depth_image)
85
  return [img, gltf_path, gltf_path]
86
-
87
  except Exception as e:
88
- print(f"Error in process_image: {e}")
89
- raise Exception("Error reconstructing 3D model") from e
 
 
 
 
90
 
91
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
92
  depth_o3d = o3d.geometry.Image(depth_image)
@@ -102,23 +73,27 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
102
 
103
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
104
 
105
- print("Estimating normals")
106
- pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Invalidate existing normals
 
 
107
  pcd.estimate_normals(
108
  search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
109
  )
110
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
 
 
111
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
112
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
113
 
114
- print("Running Poisson surface reconstruction")
115
  with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
116
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
117
  pcd, depth=depth, width=0, scale=1.1, linear_fit=True
118
  )
119
 
120
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
121
- print(f"Voxel size = {voxel_size:e}")
122
  mesh = mesh_raw.simplify_vertex_clustering(
123
  voxel_size=voxel_size,
124
  contraction=o3d.geometry.SimplificationContraction.Average,
@@ -133,7 +108,8 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
133
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
134
  return gltf_path
135
 
136
- # Gradio interface setup
 
137
  title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
138
  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."
139
  examples = [["examples/" + img] for img in os.listdir("examples/")]
@@ -155,5 +131,4 @@ iface = gr.Interface(
155
  allow_flagging="never",
156
  cache_examples=False,
157
  )
158
-
159
- iface.launch(debug=True, show_api=True, share=True)
 
6
  import open3d as o3d
7
  from pathlib import Path
8
  import os
 
9
 
 
10
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
11
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
 
 
 
12
  def process_image(image_path, depth_map_path=None):
13
+ image_path = Path(image_path)
14
+ image_raw = Image.open(image_path)
15
+ image = image_raw.resize(
16
+ (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
17
+ Image.Resampling.LANCZOS,
18
+ )
19
+
20
+ if depth_map_path:
21
+ # Load and resize the user-provided depth map to match the RGB image size
22
+ depth_image_raw = Image.open(depth_map_path)
23
+ depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
24
+ depth_image = np.array(depth_image)
25
+
26
+ # Adjust the depth map based on the Depth-Anything-V2 format
27
+ # Normalize depth if needed (assuming values are not scaled to 0-255)
28
+ depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
29
+ depth_image = (depth_image * 255).astype('uint8')
30
+
31
+ # Optionally invert the depth map if it's inverse (like MiDaS)
32
+ # depth_image = np.max(depth_image) - depth_image
33
+
34
+ else:
35
+ # Automatically generate the depth map using the model (if no depth map provided)
36
+ encoding = feature_extractor(image, return_tensors="pt")
37
+ with torch.no_grad():
38
+ outputs = model(**encoding)
39
+ predicted_depth = outputs.predicted_depth
40
+
41
+ # Interpolate to original size
42
+ prediction = torch.nn.functional.interpolate(
43
+ predicted_depth.unsqueeze(1),
44
+ size=image.size[::-1],
45
+ mode="bicubic",
46
+ align_corners=False,
47
+ ).squeeze()
48
+ depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
49
+
50
  try:
51
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
52
+ img = Image.fromarray(depth_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  return [img, gltf_path, gltf_path]
 
54
  except Exception as e:
55
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
56
+ img = Image.fromarray(depth_image)
57
+ return [img, gltf_path, gltf_path]
58
+ except:
59
+ print("Error reconstructing 3D model")
60
+ raise Exception("Error reconstructing 3D model")
61
 
62
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
63
  depth_o3d = o3d.geometry.Image(depth_image)
 
73
 
74
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
75
 
76
+ print("normals")
77
+ pcd.normals = o3d.utility.Vector3dVector(
78
+ np.zeros((1, 3))
79
+ ) # invalidate existing normals
80
  pcd.estimate_normals(
81
  search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
82
  )
83
+ pcd.orient_normals_towards_camera_location(
84
+ camera_location=np.array([0.0, 0.0, 1000.0])
85
+ )
86
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
87
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
88
 
89
+ print("run Poisson surface reconstruction")
90
  with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
91
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
92
  pcd, depth=depth, width=0, scale=1.1, linear_fit=True
93
  )
94
 
95
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
96
+ print(f"voxel_size = {voxel_size:e}")
97
  mesh = mesh_raw.simplify_vertex_clustering(
98
  voxel_size=voxel_size,
99
  contraction=o3d.geometry.SimplificationContraction.Average,
 
108
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
109
  return gltf_path
110
 
111
+
112
+
113
  title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
114
  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."
115
  examples = [["examples/" + img] for img in os.listdir("examples/")]
 
131
  allow_flagging="never",
132
  cache_examples=False,
133
  )
134
+ iface.launch(debug=True, show_api=True, share=True)