codic commited on
Commit
31da0af
·
verified ·
1 Parent(s): 842b34b

try handleing the errors

Browse files
Files changed (1) hide show
  1. app.py +157 -151
app.py CHANGED
@@ -39,7 +39,7 @@ pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
39
  ).cuda()
40
 
41
  # Depth and surface normals prediction function
42
- @spaces.GPU()
43
  def predict_depth(image: Image.Image):
44
  # Convert image to RGB
45
  image = image.convert("RGB")
@@ -116,79 +116,81 @@ def predict_depth(image: Image.Image):
116
  torch.cuda.empty_cache()
117
 
118
  def process_image(image_path, depth_map_path=None):
119
- image_path = image_path
120
- image_raw = Image.open(image_path).convert("RGB")
121
- image = image_raw.resize(
122
- (2072, int(2072 * image_raw.size[1] / image_raw.size[0])),
123
- Image.Resampling.LANCZOS,
124
- )
125
-
126
- # Remove background to isolate the main subject
127
- foreground = remove(image_raw)
128
- foreground = Image.fromarray(np.array(foreground)).convert("RGB")
129
-
130
- # Load or generate depth map
131
- if depth_map_path:
132
- if depth_map_path.endswith('.npy'):
133
- depth_image = np.load(depth_map_path).astype(np.float32)
134
- depth_image = 1 - depth_image # Invert depth for npy files
 
 
 
 
 
 
 
 
135
  else:
136
- depth_image_raw = Image.open(depth_map_path).convert("L")
137
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
138
- depth_image = np.array(depth_image, dtype=np.float32)
139
-
140
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
141
- depth_image = np.clip(depth_image, 0, 1)
142
- else:
143
- # Generate depth map using DPT model
144
- # encoding = feature_extractor(foreground, return_tensors="pt")
145
- # with torch.no_grad():
146
- # outputs = model(**encoding)
147
- # predicted_depth = outputs.predicted_depth
148
-
149
- # prediction = torch.nn.functional.interpolate(
150
- # predicted_depth.unsqueeze(1),
151
- # size=image.size[::-1],
152
- # mode="bicubic",
153
- # align_corners=False,
154
- # ).squeeze()
155
- # depth_image = prediction.cpu().numpy().astype(np.float32)
156
-
157
- # depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
158
- # depth_image = np.clip(depth_image, 0, 1)
159
-
160
- # Use the predict_depth function to generate the depth map
161
- depth_image_path, _, _, _ = predict_depth(image_raw)
162
- depth_image = np.array(Image.open(depth_image_path).convert("L"), dtype=np.float32) / 255.0
163
-
164
- # Step 1: Depth refinement (Morphological closing)
165
- kernel = np.ones((3, 3), np.uint8)
166
- depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
167
-
168
- # Step 2: Edge-preserving filter (Enhance small structures)
169
- depth_image = cv2.edgePreservingFilter(
170
- (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
171
- )
172
- depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
173
-
174
- # Step 3: Smooth depth map with Gaussian filter
175
- depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
176
-
177
- # Step 4: Bilateral filter for detail preservation
178
- depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
179
-
180
- # Step 5: Resize the depth map to match the foreground size
181
- depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
182
-
183
- # Step 6: Create an edge-aware mask (if needed for further processing)
184
- mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
185
-
186
- depth_subject_only = np.where(mask, depth_image * mask, 0)
187
- depth_subject_only[~mask] = 0 # Ensure background areas are zeroed out
188
-
189
- # Generate the final depth image with reduced blur artifacts
190
- depth_display = (depth_subject_only * 255).astype(np.uint8)
191
-
192
  try:
193
  # Generate the 3D model
194
  gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
@@ -200,90 +202,94 @@ def process_image(image_path, depth_map_path=None):
200
  img = Image.fromarray(depth_display)
201
  return [img, gltf_path, gltf_path]
202
  # Clear GPU cache after each iteration
 
203
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
204
- """
205
- Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
- Parameters:
208
- foreground (np.array): The main subject image (RGB).
209
- depth_image (np.array): The depth map array for the main subject only.
210
- image_path (str): Path to save the output model.
211
- depth (int): Poisson reconstruction depth value for high detail.
212
- edge_strength (float): Strength of the edge thresholding for sharper subject boundaries.
 
 
 
 
 
 
 
213
 
214
- Returns:
215
- str: Path to the saved 3D model (.gltf).
216
- """
217
-
218
- # Resize and normalize depth image to align with the foreground dimensions
219
- depth_image_resized = np.array(
220
- Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
221
- )
222
 
223
- # Normalize depth map and set background to zero (remove background noise)
224
- depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
225
- (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
226
 
227
- # Apply edge detection to enhance the subject’s edges
228
- sobel_x = filters.sobel(depth_image_normalized, axis=0)
229
- sobel_y = filters.sobel(depth_image_normalized, axis=1)
230
- gradient_magnitude = np.hypot(sobel_x, sobel_y)
231
-
232
- # Generate an edge mask that captures only strong edges
233
- edge_mask = gradient_magnitude < (gradient_magnitude.max() * edge_strength)
234
-
235
- # Keep depth values only within the edge mask area (isolating the main subject)
236
- depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
237
-
238
- # Create Open3D RGBD image
239
- depth_o3d = o3d.geometry.Image(depth_image_sharpened)
240
- image_o3d = o3d.geometry.Image(foreground)
241
- rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
242
- image_o3d, depth_o3d, convert_rgb_to_intensity=False
243
- )
244
-
245
- # Define camera intrinsics based on image dimensions
246
- w, h = foreground.shape[1], foreground.shape[0]
247
- camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
248
-
249
- # Generate point cloud and apply depth-focused filtering
250
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
251
-
252
- # Check minimum point count for normals estimation
253
- if len(pcd.points) < 100:
254
- raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
255
-
256
- # Estimate normals with refined parameters
257
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
258
- pcd.orient_normals_consistent_tangent_plane(k=10)
259
-
260
 
261
- # Orient normals towards a distant camera position
262
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
263
-
264
- # Create Poisson mesh using main subject's isolated depth
265
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
266
- pcd, depth=depth, width=0, scale=4, linear_fit=True
267
- )
268
- # Remove low-density artifacts
269
- density_threshold = np.quantile(np.asarray(densities), 0.06) # Adjust quantile as needed
270
- vertices_to_remove = densities < density_threshold
271
- mesh_raw.remove_vertices_by_mask(vertices_to_remove)
272
-
273
-
274
- # Simplify with smaller voxel size for more detail
275
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
276
- mesh = mesh_raw.simplify_vertex_clustering(
277
- voxel_size=voxel_size,
278
- contraction=o3d.geometry.SimplificationContraction.Average,
279
- )
280
-
281
- # Apply Laplacian smoothing
282
- mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
283
-
284
- # Crop mesh to bounding box around main subject only
285
- bbox = pcd.get_axis_aligned_bounding_box()
286
- mesh_crop = mesh.crop(bbox)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
  # Compute UV mapping for texturing
289
  mesh_crop.compute_vertex_normals()
 
39
  ).cuda()
40
 
41
  # Depth and surface normals prediction function
42
+ @spaces.GPU(enable_queue=True)
43
  def predict_depth(image: Image.Image):
44
  # Convert image to RGB
45
  image = image.convert("RGB")
 
116
  torch.cuda.empty_cache()
117
 
118
  def process_image(image_path, depth_map_path=None):
119
+ try:
120
+ image_path = image_path
121
+ image_raw = Image.open(image_path).convert("RGB")
122
+ image = image_raw.resize(
123
+ (2072, int(2072 * image_raw.size[1] / image_raw.size[0])),
124
+ Image.Resampling.LANCZOS,
125
+ )
126
+
127
+ # Remove background to isolate the main subject
128
+ foreground = remove(image_raw)
129
+ foreground = Image.fromarray(np.array(foreground)).convert("RGB")
130
+
131
+ # Load or generate depth map
132
+ if depth_map_path:
133
+ if depth_map_path.endswith('.npy'):
134
+ depth_image = np.load(depth_map_path).astype(np.float32)
135
+ depth_image = 1 - depth_image # Invert depth for npy files
136
+ else:
137
+ depth_image_raw = Image.open(depth_map_path).convert("L")
138
+ depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
139
+ depth_image = np.array(depth_image, dtype=np.float32)
140
+
141
+ depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
142
+ depth_image = np.clip(depth_image, 0, 1)
143
  else:
144
+ # Generate depth map using DPT model
145
+ # encoding = feature_extractor(foreground, return_tensors="pt")
146
+ # with torch.no_grad():
147
+ # outputs = model(**encoding)
148
+ # predicted_depth = outputs.predicted_depth
149
+
150
+ # prediction = torch.nn.functional.interpolate(
151
+ # predicted_depth.unsqueeze(1),
152
+ # size=image.size[::-1],
153
+ # mode="bicubic",
154
+ # align_corners=False,
155
+ # ).squeeze()
156
+ # depth_image = prediction.cpu().numpy().astype(np.float32)
157
+
158
+ # depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
159
+ # depth_image = np.clip(depth_image, 0, 1)
160
+
161
+ # Use the predict_depth function to generate the depth map
162
+ depth_image_path, _, _, _ = predict_depth(image_raw)
163
+ depth_image = np.array(Image.open(depth_image_path).convert("L"), dtype=np.float32) / 255.0
164
+
165
+ # Step 1: Depth refinement (Morphological closing)
166
+ kernel = np.ones((3, 3), np.uint8)
167
+ depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
168
+
169
+ # Step 2: Edge-preserving filter (Enhance small structures)
170
+ depth_image = cv2.edgePreservingFilter(
171
+ (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
172
+ )
173
+ depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
174
+
175
+ # Step 3: Smooth depth map with Gaussian filter
176
+ depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
177
+
178
+ # Step 4: Bilateral filter for detail preservation
179
+ depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
180
+
181
+ # Step 5: Resize the depth map to match the foreground size
182
+ depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
183
+
184
+ # Step 6: Create an edge-aware mask (if needed for further processing)
185
+ mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
186
+
187
+ depth_subject_only = np.where(mask, depth_image * mask, 0)
188
+ depth_subject_only[~mask] = 0 # Ensure background areas are zeroed out
189
+
190
+ # Generate the final depth image with reduced blur artifacts
191
+ depth_display = (depth_subject_only * 255).astype(np.uint8)
192
+ except Exception as e:
193
+ print(f"Error with image process {str(e)}")
 
 
 
 
 
 
194
  try:
195
  # Generate the 3D model
196
  gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
 
202
  img = Image.fromarray(depth_display)
203
  return [img, gltf_path, gltf_path]
204
  # Clear GPU cache after each iteration
205
+ @spaces.GPU(enable_queue=True,duration=140 )
206
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
207
+ try:
208
+ """
209
+ Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
210
+
211
+ Parameters:
212
+ foreground (np.array): The main subject image (RGB).
213
+ depth_image (np.array): The depth map array for the main subject only.
214
+ image_path (str): Path to save the output model.
215
+ depth (int): Poisson reconstruction depth value for high detail.
216
+ edge_strength (float): Strength of the edge thresholding for sharper subject boundaries.
217
+
218
+ Returns:
219
+ str: Path to the saved 3D model (.gltf).
220
+ """
221
 
222
+ # Resize and normalize depth image to align with the foreground dimensions
223
+ depth_image_resized = np.array(
224
+ Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
225
+ )
226
+
227
+ # Normalize depth map and set background to zero (remove background noise)
228
+ depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
229
+ (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
230
+
231
+ # Apply edge detection to enhance the subject’s edges
232
+ sobel_x = filters.sobel(depth_image_normalized, axis=0)
233
+ sobel_y = filters.sobel(depth_image_normalized, axis=1)
234
+ gradient_magnitude = np.hypot(sobel_x, sobel_y)
235
 
236
+ # Generate an edge mask that captures only strong edges
237
+ edge_mask = gradient_magnitude < (gradient_magnitude.max() * edge_strength)
 
 
 
 
 
 
238
 
239
+ # Keep depth values only within the edge mask area (isolating the main subject)
240
+ depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
 
241
 
242
+ # Create Open3D RGBD image
243
+ depth_o3d = o3d.geometry.Image(depth_image_sharpened)
244
+ image_o3d = o3d.geometry.Image(foreground)
245
+ rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
246
+ image_o3d, depth_o3d, convert_rgb_to_intensity=False
247
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
+ # Define camera intrinsics based on image dimensions
250
+ w, h = foreground.shape[1], foreground.shape[0]
251
+ camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
252
+
253
+ # Generate point cloud and apply depth-focused filtering
254
+ pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
255
+
256
+ # Check minimum point count for normals estimation
257
+ if len(pcd.points) < 100:
258
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
259
+
260
+ # Estimate normals with refined parameters
261
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
262
+ pcd.orient_normals_consistent_tangent_plane(k=10)
263
+
264
+
265
+ # Orient normals towards a distant camera position
266
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
267
+
268
+ # Create Poisson mesh using main subject's isolated depth
269
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
270
+ pcd, depth=depth, width=0, scale=4, linear_fit=True
271
+ )
272
+ # Remove low-density artifacts
273
+ density_threshold = np.quantile(np.asarray(densities), 0.06) # Adjust quantile as needed
274
+ vertices_to_remove = densities < density_threshold
275
+ mesh_raw.remove_vertices_by_mask(vertices_to_remove)
276
+
277
+
278
+ # Simplify with smaller voxel size for more detail
279
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
280
+ mesh = mesh_raw.simplify_vertex_clustering(
281
+ voxel_size=voxel_size,
282
+ contraction=o3d.geometry.SimplificationContraction.Average,
283
+ )
284
+
285
+ # Apply Laplacian smoothing
286
+ mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
287
+
288
+ # Crop mesh to bounding box around main subject only
289
+ bbox = pcd.get_axis_aligned_bounding_box()
290
+ mesh_crop = mesh.crop(bbox)
291
+ except Exception as e:
292
+ print(f"Error with 3d model {str(e)}")
293
 
294
  # Compute UV mapping for texturing
295
  mesh_crop.compute_vertex_normals()