codic commited on
Commit
d4d2343
·
verified ·
1 Parent(s): 6694014

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -112
app.py CHANGED
@@ -8,41 +8,11 @@ from pathlib import Path
8
  import os
9
  import cv2
10
  from rembg import remove
11
- from skimage import img_as_ubyte
12
- from skimage.filters import gaussian
13
- from skimage.segmentation import clear_border
14
 
15
  # Initialize model and feature extractor for depth estimation
16
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
17
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
18
 
19
- def normalize_depth_image(depth_image):
20
- depth_image_min = np.min(depth_image)
21
- depth_image_max = np.max(depth_image)
22
- normalized_image = (depth_image - depth_image_min) / (depth_image_max - depth_image_min)
23
- return normalized_image
24
-
25
- def process_depth_image(depth_image):
26
- # Normalize depth image
27
- normalized_depth_image = normalize_depth_image(depth_image)
28
-
29
- # Apply Gaussian smoothing to normalized depth image
30
- smoothed_depth_image = gaussian(normalized_depth_image, sigma=1.0) # Adjust sigma for smoothness
31
- return smoothed_depth_image
32
-
33
- def inpaint_background(original_image, mask):
34
- # Ensure the mask is binary and has the correct dimensions
35
- if original_image.shape[:2] != mask.shape[:2]:
36
- mask = cv2.resize(mask, (original_image.shape[1], original_image.shape[0]))
37
-
38
- # Ensure mask is of type uint8
39
- mask = mask.astype(np.uint8)
40
-
41
- # Inpaint the background using the mask
42
- inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
43
-
44
- return inpainted_image
45
-
46
  def process_image(image_path, depth_map_path=None):
47
  image_path = Path(image_path)
48
  image_raw = Image.open(image_path).convert("RGB")
@@ -55,137 +25,114 @@ def process_image(image_path, depth_map_path=None):
55
  foreground = remove(image_raw)
56
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
57
 
58
- # Create a binary mask of the foreground
59
- foreground_edges = cv2.Canny(np.array(foreground), 100, 200)
60
- foreground_edges_resized = cv2.resize(foreground_edges, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
61
-
62
- # Depth map handling
63
  if depth_map_path:
64
  if depth_map_path.endswith('.npy'):
65
  depth_image = np.load(depth_map_path)
66
- depth_image = 1 - depth_image # Invert depth for npy files
 
67
  else:
68
  depth_image_raw = Image.open(depth_map_path).convert("L")
69
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
70
  depth_image = np.array(depth_image)
71
- depth_image = process_depth_image(depth_image) # Apply processing
 
 
 
72
  else:
 
73
  encoding = feature_extractor(foreground, return_tensors="pt")
74
  with torch.no_grad():
75
  outputs = model(**encoding)
76
  predicted_depth = outputs.predicted_depth
 
77
  prediction = torch.nn.functional.interpolate(
78
  predicted_depth.unsqueeze(1),
79
  size=image.size[::-1],
80
  mode="bicubic",
81
  align_corners=False,
82
  ).squeeze()
83
- depth_image = (prediction.cpu().numpy() - np.min(prediction.cpu().numpy())) / (np.max(prediction.cpu().numpy()) - np.min(prediction.cpu().numpy())) # Normalize
84
- depth_image = process_depth_image(depth_image) # Apply processing
85
 
86
- # Smoothing and blending
87
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
88
- mask_blurred = cv2.GaussianBlur(depth_image, (5, 5), 1.0)
89
- blended_depth_image = cv2.addWeighted(depth_image, 0.7, mask_blurred, 0.3, 0)
90
- blended_depth_image[foreground_edges_resized > 0] *= 1.2
 
 
 
 
 
 
91
 
92
- # Mask creation
93
- mask = (depth_image > 0).astype(np.uint8)
94
- mask = clear_border(mask)
 
95
  background = remove(image_raw, only_mask=True)
96
  background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
97
- background_inpainted = inpaint_background(np.array(image_raw), mask)
98
- bg_scaled = cv2.resize(background_inpainted, (int(image.width * 1.2), int(image.height * 1.2)))
99
-
100
- # Flatten foreground and add zero depth channel
101
- foreground_flat = np.array(foreground)[:, :, :3]
102
- foreground_flat = np.insert(foreground_flat, 2, values=0, axis=2)
103
 
104
  try:
105
- # Convert depth image to 8-bit grayscale for PNG compatibility
106
- blended_depth_image_8bit = (blended_depth_image * 255).astype(np.uint8)
107
- img = Image.fromarray(blended_depth_image_8bit, mode="L")
108
-
109
- # Create 3D model and return paths
110
- gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path)
111
- model_3d = gr.Model3D() # Placeholder
112
- return [img, model_3d, gltf_path]
113
  except Exception as e:
114
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
115
- gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path, depth=9)
 
 
116
 
117
- # Re-convert depth to 8-bit grayscale if retrying
118
- img = Image.fromarray(blended_depth_image_8bit, mode="L")
119
- model_3d = gr.Model3D() # Placeholder
120
- return [img, model_3d, gltf_path]
121
 
122
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
123
- # Resize background to match the original image size (no cropping)
124
- background_resized = cv2.resize(background, (foreground.shape[1], foreground.shape[0]), interpolation=cv2.INTER_LINEAR)
125
-
126
- # Resize and normalize the depth image
127
  depth_image_resized = np.array(
128
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
129
  )
130
-
131
- # Normalize depth for float32 representation
132
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
133
  depth_image_resized.max() - depth_image_resized.min()
134
- )
135
-
136
- # Ensure depth image is valid
137
- if np.all(depth_image_normalized == 0):
138
- raise RuntimeError("Depth image normalization resulted in all zeros.")
139
-
140
- depth_image_normalized = depth_image_normalized.astype(np.float32)
141
 
142
- # Create flat background depth with a small gap for empty space
143
- background_depth = np.zeros_like(depth_image_normalized) + 1.5
144
-
145
- # Combine depths to create the illusion of an empty space
146
- combined_depth = np.maximum(depth_image_normalized * 0.5, background_depth)
147
-
148
- # Create Open3D images
149
- depth_o3d = o3d.geometry.Image(combined_depth)
150
  image_o3d = o3d.geometry.Image(foreground)
151
-
152
- # Create RGBD image directly using the Open3D images
153
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
154
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
155
  )
 
156
 
157
- # Convert the Open3D color image to a NumPy array to get dimensions
158
- rgbd_color_array = np.asarray(rgbd_image.color)
159
- rgbd_height, rgbd_width = rgbd_color_array.shape[:2] # Get height and width from the NumPy array
160
-
161
- # Check if the depth and foreground sizes are compatible
162
- if rgbd_width != foreground.shape[1] or rgbd_height != foreground.shape[0]:
163
- raise RuntimeError("RGBD image dimensions do not match foreground dimensions.")
164
-
165
- # Camera intrinsic setup
166
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
167
- camera_intrinsic.set_intrinsics(rgbd_width, rgbd_height, 1500, 1500, rgbd_width / 2, rgbd_height / 2)
168
 
169
- # Create the point cloud
170
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
171
 
172
- # Check if the point cloud is valid
173
- print(f"Point Cloud Size: {len(pcd.points)}")
174
  if len(pcd.points) < 100:
175
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
176
 
177
- # Estimate normals and orient
178
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))
179
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0, 0, 0]))
 
 
 
 
180
 
181
- # Convert the point cloud to a triangle mesh
182
- mesh, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=depth)
 
183
 
184
- # Save the triangle mesh to a GLB file
185
- output_path = os.path.join("output", f"{image_path.stem}.glb")
186
- o3d.io.write_triangle_mesh(output_path, mesh)
 
 
 
 
 
187
 
188
- return output_path
 
 
189
 
190
  # Gradio Interface
191
  title = "Depth Estimation & 3D Reconstruction Demo"
@@ -210,5 +157,4 @@ iface = gr.Interface(
210
  allow_flagging="never",
211
  cache_examples=False,
212
  )
213
-
214
- iface.launch(debug=True, show_api=True, share=True)
 
8
  import os
9
  import cv2
10
  from rembg import remove
 
 
 
11
 
12
  # Initialize model and feature extractor for depth estimation
13
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
14
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def process_image(image_path, depth_map_path=None):
17
  image_path = Path(image_path)
18
  image_raw = Image.open(image_path).convert("RGB")
 
25
  foreground = remove(image_raw)
26
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
27
 
28
+ # Check if user-provided depth map is available
 
 
 
 
29
  if depth_map_path:
30
  if depth_map_path.endswith('.npy'):
31
  depth_image = np.load(depth_map_path)
32
+ # Invert depth only for npy files
33
+ depth_image = 1 - depth_image
34
  else:
35
  depth_image_raw = Image.open(depth_map_path).convert("L")
36
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
37
  depth_image = np.array(depth_image)
38
+
39
+ # Normalize depth image
40
+ depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
41
+ depth_image = (depth_image * 255).astype('uint8')
42
  else:
43
+ # Generate depth map using DPT model
44
  encoding = feature_extractor(foreground, return_tensors="pt")
45
  with torch.no_grad():
46
  outputs = model(**encoding)
47
  predicted_depth = outputs.predicted_depth
48
+
49
  prediction = torch.nn.functional.interpolate(
50
  predicted_depth.unsqueeze(1),
51
  size=image.size[::-1],
52
  mode="bicubic",
53
  align_corners=False,
54
  ).squeeze()
55
+ depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
 
56
 
57
+ # Resize and apply lighter Gaussian smoothing for smoother transitions
58
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
59
+ mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
60
+
61
+ # Ensure matching size and single channel for blending
62
+ if len(depth_image.shape) == 3:
63
+ depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
64
+ if len(mask_blurred.shape) == 3:
65
+ mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
66
+
67
+ mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
68
 
69
+ # Blend depth_image with mask_blurred_resized for smoother transition
70
+ blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
71
+
72
+ # Inpaint background where main subject was removed
73
  background = remove(image_raw, only_mask=True)
74
  background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
75
+ background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
 
 
 
 
 
76
 
77
  try:
78
+ gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path)
79
+ img = Image.fromarray(blended_depth_image)
80
+ return [img, gltf_path, gltf_path]
 
 
 
 
 
81
  except Exception as e:
82
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
83
+ gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path, depth=9)
84
+ img = Image.fromarray(blended_depth_image)
85
+ return [img, gltf_path, gltf_path]
86
 
 
 
 
 
87
 
88
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
 
 
 
 
89
  depth_image_resized = np.array(
90
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
91
  )
 
 
92
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
93
  depth_image_resized.max() - depth_image_resized.min()
94
+ ) * 255
95
+ depth_image_normalized = depth_image_normalized.astype(np.uint8)
 
 
 
 
 
96
 
97
+ depth_o3d = o3d.geometry.Image(depth_image_normalized)
 
 
 
 
 
 
 
98
  image_o3d = o3d.geometry.Image(foreground)
 
 
99
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
100
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
101
  )
102
+ w, h = foreground.shape[1], foreground.shape[0]
103
 
 
 
 
 
 
 
 
 
 
104
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
105
+ camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
106
 
 
107
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
108
 
 
 
109
  if len(pcd.points) < 100:
110
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
111
 
112
+ if not pcd.has_normals():
113
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
114
+
115
+ if pcd.has_normals():
116
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
117
+ else:
118
+ raise RuntimeError("Failed to estimate normals for the point cloud.")
119
 
120
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
121
+ pcd, depth=depth, width=0, scale=1.2, linear_fit=True
122
+ )
123
 
124
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
125
+ mesh = mesh_raw.simplify_vertex_clustering(
126
+ voxel_size=voxel_size,
127
+ contraction=o3d.geometry.SimplificationContraction.Average,
128
+ )
129
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3)
130
+ bbox = pcd.get_axis_aligned_bounding_box()
131
+ mesh_crop = mesh.crop(bbox)
132
 
133
+ gltf_path = f"./{image_path.stem}.gltf"
134
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
135
+ return gltf_path
136
 
137
  # Gradio Interface
138
  title = "Depth Estimation & 3D Reconstruction Demo"
 
157
  allow_flagging="never",
158
  cache_examples=False,
159
  )
160
+ iface.launch(debug=True, show_api=True, share=True)