codic commited on
Commit
261e624
·
verified ·
1 Parent(s): 35f10e7

coppying the code from the other space

Browse files
Files changed (1) hide show
  1. app.py +74 -75
app.py CHANGED
@@ -1,6 +1,5 @@
1
  from skimage import img_as_ubyte
2
  from skimage.segmentation import clear_border
3
- from scipy.ndimage import gaussian_filter
4
  from scipy.ndimage import sobel
5
  import gradio as gr
6
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
@@ -8,12 +7,10 @@ import torch
8
  import numpy as np
9
  from PIL import Image
10
  import open3d as o3d
11
- import trimesh
12
  from pathlib import Path
13
  import os
14
  import cv2
15
- from rembg import remove, new_session
16
-
17
 
18
  # Initialize model and feature extractor for depth estimation
19
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
@@ -23,12 +20,12 @@ def process_image(image_path, depth_map_path=None):
23
  image_path = Path(image_path)
24
  image_raw = Image.open(image_path).convert("RGB")
25
  image = image_raw.resize(
26
- (3072, int(3072 * image_raw.size[1] / image_raw.size[0])),
27
  Image.Resampling.LANCZOS,
28
  )
29
 
30
  # Remove background to isolate the main subject
31
- foreground = remove(image_raw, session=new_session("u2netp"))
32
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
33
 
34
  # Load or generate depth map
@@ -60,15 +57,33 @@ def process_image(image_path, depth_map_path=None):
60
 
61
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
62
  depth_image = np.clip(depth_image, 0, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Resize depth map and create an edge-aware mask
65
- depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
66
- mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
67
 
 
 
 
68
  # Improved edge detection for the main subject
69
- edges = cv2.Canny(img_as_ubyte(mask), threshold1=40, threshold2=140)
70
- edges_dilated = cv2.dilate(edges, np.ones((3, 3), np.uint8), iterations=3)
71
- edges_eroded = cv2.erode(edges_dilated, np.ones((3, 3), np.uint8), iterations=4)
72
 
73
  # Use the refined edge mask to clean up the depth map
74
  depth_subject_only = np.where(edges_eroded == 0, depth_image * mask, 0)
@@ -84,11 +99,25 @@ def process_image(image_path, depth_map_path=None):
84
  return [img, gltf_path, gltf_path]
85
  except Exception as e:
86
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
87
- gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=8)
88
  img = Image.fromarray(depth_display)
89
  return [img, gltf_path, gltf_path]
90
-
91
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  # Resize and normalize depth image to align with the foreground dimensions
93
  depth_image_resized = np.array(
94
  Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
@@ -98,104 +127,75 @@ def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0
98
  depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
99
  (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
100
 
101
- # Apply Sobel edge detection to enhance the subject’s edges
102
  sobel_x = sobel(depth_image_normalized, axis=0)
103
  sobel_y = sobel(depth_image_normalized, axis=1)
104
  gradient_magnitude = np.hypot(sobel_x, sobel_y)
105
 
106
- # Multi-scale edge detection to refine boundaries further
107
- edges_high_res = sobel(gaussian_filter(depth_image_normalized, sigma=0.3), axis=0) + sobel(gaussian_filter(depth_image_normalized, sigma=0.3), axis=1)
108
- edges_low_res = sobel(gaussian_filter(depth_image_normalized, sigma=0.5), axis=0) + sobel(gaussian_filter(depth_image_normalized, sigma=0.5), axis=1)
109
- combined_edges = np.maximum(edges_high_res, edges_low_res)
110
-
111
  # Generate an edge mask that captures only strong edges
112
- edge_mask = combined_edges < (combined_edges.max() * edge_strength)
113
 
114
  # Keep depth values only within the edge mask area (isolating the main subject)
115
  depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
116
 
117
- # Convert depth image to 3D points
118
- h, w = depth_image_sharpened.shape
119
- y, x = np.mgrid[:h, :w]
120
- z = depth_image_sharpened
121
- points_3d = np.vstack((x.flatten(), y.flatten(), z.flatten())).T
122
-
123
- # Validate that there are enough points to create a mesh
124
- if points_3d.shape[0] < 100: # Adjust threshold as needed
125
- raise RuntimeError("Insufficient points to create a mesh.")
126
 
127
- try:
128
- # Attempt to create a mesh from the points
129
- mesh = trimesh.Trimesh(vertices=points_3d, process=True)
130
- if mesh.is_empty:
131
- raise ValueError("Generated mesh is empty.")
132
-
133
- # Apply filters and simplification
134
- mesh.update_faces(mesh.nondegenerate_faces())
135
- mesh.update_faces(mesh.unique_faces())
136
- mesh.fill_holes()
137
-
138
- # Simplify with smaller voxel size for more detail
139
- voxel_size = max(mesh.bounds[1] - mesh.bounds[0]) / 3200
140
- mesh = mesh.simplify_vertex_clustering(
141
- voxel_size=voxel_size,
142
- contraction='average',
143
- )
144
- except Exception as e:
145
- print(f"Error generating Trimesh mesh: {e}")
146
- return None # Return None if mesh creation fails
147
 
148
- # Continue with Open3D processing if mesh creation succeeds
149
- pcd = o3d.geometry.PointCloud()
150
- pcd.points = o3d.utility.Vector3dVector(points_3d)
151
 
152
- # Check for minimum point count in the point cloud for normals estimation
153
  if len(pcd.points) < 100:
154
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
155
 
156
- # Estimate normals
157
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.02, max_nn=80))
158
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
 
159
 
160
- # Crop point cloud to main subject bounds
161
- bbox = pcd.get_axis_aligned_bounding_box()
162
- bbox.scale(0.5, bbox.get_center()) # Adjust scale to fit the main subject tightly
163
- pcd_cropped = pcd.crop(bbox)
164
 
165
  # Create Poisson mesh using main subject's isolated depth
166
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
167
- pcd_cropped, depth=depth, width=0, scale=2, linear_fit=True
168
  )
 
 
 
 
 
169
 
170
  # Simplify with smaller voxel size for more detail
171
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 3200
172
  mesh = mesh_raw.simplify_vertex_clustering(
173
  voxel_size=voxel_size,
174
  contraction=o3d.geometry.SimplificationContraction.Average,
175
  )
176
 
177
- # Apply edge-aware smoothing (bilateral filter in 3D)
178
  mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
179
-
180
- # Apply an edge-aware bilateral filter to retain small features
181
- pcd_filtered = pcd.crop(bbox) # Crop to the subject's bounds
182
- pcd_filtered = o3d.geometry.PointCloud()
183
- pcd_filtered.points = o3d.utility.Vector3dVector(np.array(mesh.vertices)) # Update with filtered points
184
-
185
- mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd_filtered, depth=12)
186
-
187
  # Crop mesh to bounding box around main subject only
 
188
  mesh_crop = mesh.crop(bbox)
189
 
190
  # Compute UV mapping for texturing
191
  mesh_crop.compute_vertex_normals()
192
  uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
193
  mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
194
-
195
  # Save high-resolution texture image
196
  texture_path = f"./{image_path.stem}_texture_highres.png"
197
  foreground_pil = Image.fromarray(foreground)
198
- high_res_texture = foreground_pil.resize((4096, 4096), Image.LANCZOS) # Increased resolution for finer details
199
  high_res_texture.save(texture_path)
200
 
201
  # Apply the high-resolution texture and export the mesh as a GLTF file
@@ -204,7 +204,6 @@ def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0
204
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
205
 
206
  return gltf_path
207
-
208
  # Gradio Interface
209
  title = "Depth Estimation & 3D Reconstruction Demo"
210
  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."
 
1
  from skimage import img_as_ubyte
2
  from skimage.segmentation import clear_border
 
3
  from scipy.ndimage import sobel
4
  import gradio as gr
5
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
 
7
  import numpy as np
8
  from PIL import Image
9
  import open3d as o3d
 
10
  from pathlib import Path
11
  import os
12
  import cv2
13
+ from rembg import remove
 
14
 
15
  # Initialize model and feature extractor for depth estimation
16
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
 
20
  image_path = Path(image_path)
21
  image_raw = Image.open(image_path).convert("RGB")
22
  image = image_raw.resize(
23
+ (4072, int(4072 * image_raw.size[1] / image_raw.size[0])),
24
  Image.Resampling.LANCZOS,
25
  )
26
 
27
  # Remove background to isolate the main subject
28
+ foreground = remove(image_raw)
29
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
30
 
31
  # Load or generate depth map
 
57
 
58
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
59
  depth_image = np.clip(depth_image, 0, 1)
60
+
61
+ # Step 1: Depth refinement (Morphological closing)
62
+ kernel = np.ones((3, 3), np.uint8)
63
+ depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
64
+
65
+ # Step 2: Edge-preserving filter (Enhance small structures)
66
+ depth_image = cv2.edgePreservingFilter(
67
+ (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=20, sigma_r=0.3
68
+ )
69
+ depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
70
+
71
+ # Step 3: Smooth depth map with Gaussian filter
72
+ depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
73
+
74
+ # Step 4: Bilateral filter for detail preservation
75
+ depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
76
 
77
+ # Step 5: Resize the depth map to match the foreground size
78
+ depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
 
79
 
80
+ # Step 6: Create an edge-aware mask (if needed for further processing)
81
+ mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
82
+
83
  # Improved edge detection for the main subject
84
+ edges = cv2.Canny(img_as_ubyte(mask), threshold1=30, threshold2=80) # Adjust thresholds for edges
85
+ edges_dilated = cv2.dilate(edges, np.ones((9, 9), np.uint8), iterations=4) # Larger kernel, fewer gaps
86
+ edges_eroded = cv2.erode(edges_dilated, np.ones((9, 9), np.uint8), iterations=2)
87
 
88
  # Use the refined edge mask to clean up the depth map
89
  depth_subject_only = np.where(edges_eroded == 0, depth_image * mask, 0)
 
99
  return [img, gltf_path, gltf_path]
100
  except Exception as e:
101
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
102
+ gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=9)
103
  img = Image.fromarray(depth_display)
104
  return [img, gltf_path, gltf_path]
105
+
106
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
107
+ """
108
+ Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
109
+
110
+ Parameters:
111
+ foreground (np.array): The main subject image (RGB).
112
+ depth_image (np.array): The depth map array for the main subject only.
113
+ image_path (str): Path to save the output model.
114
+ depth (int): Poisson reconstruction depth value for high detail.
115
+ edge_strength (float): Strength of the edge thresholding for sharper subject boundaries.
116
+
117
+ Returns:
118
+ str: Path to the saved 3D model (.gltf).
119
+ """
120
+
121
  # Resize and normalize depth image to align with the foreground dimensions
122
  depth_image_resized = np.array(
123
  Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
 
127
  depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
128
  (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
129
 
130
+ # Apply edge detection to enhance the subject’s edges
131
  sobel_x = sobel(depth_image_normalized, axis=0)
132
  sobel_y = sobel(depth_image_normalized, axis=1)
133
  gradient_magnitude = np.hypot(sobel_x, sobel_y)
134
 
 
 
 
 
 
135
  # Generate an edge mask that captures only strong edges
136
+ edge_mask = gradient_magnitude < (gradient_magnitude.max() * edge_strength)
137
 
138
  # Keep depth values only within the edge mask area (isolating the main subject)
139
  depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
140
 
141
+ # Create Open3D RGBD image
142
+ depth_o3d = o3d.geometry.Image(depth_image_sharpened)
143
+ image_o3d = o3d.geometry.Image(foreground)
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 = foreground.shape[1], foreground.shape[0]
150
+ camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 3000, 3000, 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.05, max_nn=100))
161
+ pcd.orient_normals_consistent_tangent_plane(k=10)
162
+
163
 
164
+ # Orient normals towards a distant camera position
165
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
 
 
166
 
167
  # Create Poisson mesh using main subject's isolated depth
168
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
169
+ pcd, depth=depth, width=0, scale=4, linear_fit=True
170
  )
171
+ # Remove low-density artifacts
172
+ density_threshold = np.quantile(np.asarray(densities), 0.05) # Adjust quantile as needed
173
+ vertices_to_remove = densities < density_threshold
174
+ mesh_raw.remove_vertices_by_mask(vertices_to_remove)
175
+
176
 
177
  # Simplify with smaller voxel size for more detail
178
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 6200
179
  mesh = mesh_raw.simplify_vertex_clustering(
180
  voxel_size=voxel_size,
181
  contraction=o3d.geometry.SimplificationContraction.Average,
182
  )
183
 
184
+ # Apply Laplacian smoothing
185
  mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
186
+
 
 
 
 
 
 
 
187
  # Crop mesh to bounding box around main subject only
188
+ bbox = pcd.get_axis_aligned_bounding_box()
189
  mesh_crop = mesh.crop(bbox)
190
 
191
  # Compute UV mapping for texturing
192
  mesh_crop.compute_vertex_normals()
193
  uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
194
  mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
 
195
  # Save high-resolution texture image
196
  texture_path = f"./{image_path.stem}_texture_highres.png"
197
  foreground_pil = Image.fromarray(foreground)
198
+ high_res_texture = foreground_pil.resize((5096, 5096), Image.LANCZOS) # Increased resolution for finer details
199
  high_res_texture.save(texture_path)
200
 
201
  # Apply the high-resolution texture and export the mesh as a GLTF file
 
204
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
205
 
206
  return gltf_path
 
207
  # Gradio Interface
208
  title = "Depth Estimation & 3D Reconstruction Demo"
209
  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."