Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -31,55 +31,69 @@ torch.cuda.empty_cache()
|
|
| 31 |
|
| 32 |
# Load the Marigold Depth Pipeline with LCM Scheduler
|
| 33 |
try:
|
|
|
|
| 34 |
pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
|
| 35 |
"prs-eth/marigold-depth-lcm-v1-0", variant="fp16", torch_dtype=torch.float16
|
| 36 |
).to(device)
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
|
| 39 |
"madebyollin/taesd", torch_dtype=torch.float16
|
| 40 |
).cuda()
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
-
print(f"Error loading depth pipeline: {e}")
|
| 43 |
raise
|
| 44 |
|
| 45 |
# Enable XFormers
|
| 46 |
try:
|
|
|
|
| 47 |
pipe.enable_xformers_memory_efficient_attention()
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
-
print(f"XFormers could not be enabled: {e}")
|
| 50 |
|
| 51 |
@spaces.GPU(enable_queue=True)
|
| 52 |
def predict_depth(image: Image.Image):
|
| 53 |
"""Predict depth from an image and return refined depth map."""
|
| 54 |
try:
|
|
|
|
| 55 |
image = image.convert("RGB")
|
| 56 |
|
| 57 |
# Step 1: Remove background to isolate the main subject
|
|
|
|
| 58 |
foreground = remove(image)
|
| 59 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 60 |
|
| 61 |
# Depth prediction
|
|
|
|
| 62 |
depth = pipe(
|
| 63 |
foreground,
|
| 64 |
ensemble_size=10,
|
| 65 |
num_inference_steps=4
|
| 66 |
)
|
|
|
|
| 67 |
|
| 68 |
# Export high-quality depth as 16-bit PNG
|
|
|
|
| 69 |
depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
|
| 70 |
depth_16bit_image = depth_16bit[0]
|
| 71 |
|
| 72 |
# Save depth as 16-bit PNG for further processing
|
| 73 |
depth_16bit_image_path = "depth_16bit_image.png"
|
| 74 |
depth_16bit_image.save(depth_16bit_image_path)
|
|
|
|
| 75 |
|
| 76 |
# Convert depth to numpy array for refinement
|
|
|
|
| 77 |
depth_array = np.array(depth_16bit_image, dtype=np.float32) / 65535
|
| 78 |
refined_depth = refine_depth(depth_array)
|
| 79 |
|
| 80 |
# Apply edge detection to enhance the subject's edges
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
gradient_magnitude = np.hypot(sobel_x, sobel_y)
|
| 84 |
|
| 85 |
# Generate an edge mask that captures only strong edges
|
|
@@ -87,30 +101,40 @@ def predict_depth(image: Image.Image):
|
|
| 87 |
|
| 88 |
# Keep depth values only within the edge mask area (isolating the main subject)
|
| 89 |
refined_depth = np.where(edge_mask, refined_depth, 0)
|
|
|
|
| 90 |
|
| 91 |
return refined_depth, depth_16bit_image_path
|
| 92 |
except Exception as e:
|
| 93 |
-
print(f"Error in depth prediction or processing: {e}")
|
| 94 |
return None, None
|
| 95 |
|
| 96 |
def refine_depth(depth_array):
|
| 97 |
"""Refine depth map with smoothing and edge-aware processing."""
|
| 98 |
try:
|
|
|
|
| 99 |
kernel = np.ones((3, 3), np.uint8)
|
| 100 |
depth_cleaned = cv2.morphologyEx(depth_array, cv2.MORPH_CLOSE, kernel)
|
|
|
|
|
|
|
| 101 |
depth_filtered = cv2.edgePreservingFilter(
|
| 102 |
(depth_cleaned * 255).astype(np.uint8), flags=1, sigma_s=8, sigma_r=0.3
|
| 103 |
).astype(np.float32) / 255
|
|
|
|
|
|
|
| 104 |
depth_smoothed = cv2.GaussianBlur(depth_filtered, (5, 5), sigmaX=3, sigmaY=3)
|
|
|
|
|
|
|
| 105 |
depth_final = cv2.bilateralFilter((depth_smoothed * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
|
|
|
|
| 106 |
return depth_final
|
| 107 |
except Exception as e:
|
| 108 |
-
print(f"Error refining depth: {e}")
|
| 109 |
return None
|
| 110 |
|
| 111 |
def save_raw_16bit(depth, fpath="raw.png"):
|
| 112 |
"""Save depth as raw 16-bit PNG."""
|
| 113 |
try:
|
|
|
|
| 114 |
if isinstance(depth, torch.Tensor):
|
| 115 |
depth = depth.squeeze().cpu().numpy()
|
| 116 |
|
|
@@ -119,18 +143,21 @@ def save_raw_16bit(depth, fpath="raw.png"):
|
|
| 119 |
|
| 120 |
depth = (depth * 65535).astype(np.uint16)
|
| 121 |
cv2.imwrite(fpath, depth)
|
|
|
|
| 122 |
except Exception as e:
|
| 123 |
-
print(f"Error saving raw depth: {e}")
|
| 124 |
|
| 125 |
def get_mesh(image: Image.Image, depth_array):
|
| 126 |
"""Generate 3D mesh from depth array and image."""
|
| 127 |
try:
|
|
|
|
| 128 |
depth_array = (depth_array * 65535).astype(np.uint16)
|
| 129 |
depth_image_resized = Image.fromarray(depth_array)
|
| 130 |
|
| 131 |
if image.size != depth_image_resized.size:
|
| 132 |
image = image.resize(depth_image_resized.size, Image.Resampling.LANCZOS)
|
| 133 |
|
|
|
|
| 134 |
depth_o3d = o3d.geometry.Image(np.array(depth_image_resized))
|
| 135 |
image_o3d = o3d.geometry.Image(np.array(image))
|
| 136 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
|
@@ -138,21 +165,25 @@ def get_mesh(image: Image.Image, depth_array):
|
|
| 138 |
)
|
| 139 |
|
| 140 |
# Camera intrinsics
|
|
|
|
| 141 |
w, h = image.size
|
| 142 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
|
| 143 |
|
| 144 |
# Generate point cloud
|
|
|
|
| 145 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 146 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
|
| 147 |
pcd.orient_normals_consistent_tangent_plane(k=10)
|
| 148 |
|
| 149 |
# Generate Poisson mesh
|
|
|
|
| 150 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=12)
|
| 151 |
density_threshold = np.quantile(np.asarray(densities), 0.06)
|
| 152 |
vertices_to_remove = densities < density_threshold
|
| 153 |
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
|
| 154 |
|
| 155 |
# Simplify and smooth mesh
|
|
|
|
| 156 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
|
| 157 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 158 |
voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average
|
|
@@ -160,6 +191,7 @@ def get_mesh(image: Image.Image, depth_array):
|
|
| 160 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 161 |
|
| 162 |
# Compute UV mapping for texturing
|
|
|
|
| 163 |
mesh.compute_vertex_normals()
|
| 164 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh.vertices])
|
| 165 |
mesh.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
|
@@ -171,7 +203,7 @@ def get_mesh(image: Image.Image, depth_array):
|
|
| 171 |
|
| 172 |
return gltf_path
|
| 173 |
except Exception as e:
|
| 174 |
-
print(f"Error generating 3D mesh: {e}")
|
| 175 |
return None
|
| 176 |
|
| 177 |
def process_image(image_path):
|
|
@@ -184,12 +216,6 @@ def process_image(image_path):
|
|
| 184 |
if refined_depth is None or depth_16bit_path is None:
|
| 185 |
return None, None
|
| 186 |
|
| 187 |
-
# Generate 3D mesh
|
| 188 |
-
gltf_path = get_mesh(image_raw, refined_depth)
|
| 189 |
-
|
| 190 |
-
if gltf_path is None:
|
| 191 |
-
return None, None
|
| 192 |
-
|
| 193 |
return depth_16bit_path, gltf_path
|
| 194 |
except Exception as e:
|
| 195 |
print(f"Error processing image: {e}")
|
|
|
|
| 31 |
|
| 32 |
# Load the Marigold Depth Pipeline with LCM Scheduler
|
| 33 |
try:
|
| 34 |
+
print("Loading depth pipeline...")
|
| 35 |
pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
|
| 36 |
"prs-eth/marigold-depth-lcm-v1-0", variant="fp16", torch_dtype=torch.float16
|
| 37 |
).to(device)
|
| 38 |
+
print("Pipeline loaded successfully.")
|
| 39 |
+
|
| 40 |
+
print("Loading custom VAE...")
|
| 41 |
pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
|
| 42 |
"madebyollin/taesd", torch_dtype=torch.float16
|
| 43 |
).cuda()
|
| 44 |
+
print("Custom VAE loaded.")
|
| 45 |
except Exception as e:
|
| 46 |
+
print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
|
| 47 |
raise
|
| 48 |
|
| 49 |
# Enable XFormers
|
| 50 |
try:
|
| 51 |
+
print("Enabling XFormers...")
|
| 52 |
pipe.enable_xformers_memory_efficient_attention()
|
| 53 |
+
print("XFormers enabled.")
|
| 54 |
except Exception as e:
|
| 55 |
+
print(f"XFormers could not be enabled: {type(e).__name__} - {e}")
|
| 56 |
|
| 57 |
@spaces.GPU(enable_queue=True)
|
| 58 |
def predict_depth(image: Image.Image):
|
| 59 |
"""Predict depth from an image and return refined depth map."""
|
| 60 |
try:
|
| 61 |
+
print("Processing input image...")
|
| 62 |
image = image.convert("RGB")
|
| 63 |
|
| 64 |
# Step 1: Remove background to isolate the main subject
|
| 65 |
+
print("Removing background...")
|
| 66 |
foreground = remove(image)
|
| 67 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 68 |
|
| 69 |
# Depth prediction
|
| 70 |
+
print("Predicting depth...")
|
| 71 |
depth = pipe(
|
| 72 |
foreground,
|
| 73 |
ensemble_size=10,
|
| 74 |
num_inference_steps=4
|
| 75 |
)
|
| 76 |
+
print("Depth prediction completed.")
|
| 77 |
|
| 78 |
# Export high-quality depth as 16-bit PNG
|
| 79 |
+
print("Exporting 16-bit depth image...")
|
| 80 |
depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
|
| 81 |
depth_16bit_image = depth_16bit[0]
|
| 82 |
|
| 83 |
# Save depth as 16-bit PNG for further processing
|
| 84 |
depth_16bit_image_path = "depth_16bit_image.png"
|
| 85 |
depth_16bit_image.save(depth_16bit_image_path)
|
| 86 |
+
print(f"16-bit depth image saved to {depth_16bit_image_path}.")
|
| 87 |
|
| 88 |
# Convert depth to numpy array for refinement
|
| 89 |
+
print("Refining depth map...")
|
| 90 |
depth_array = np.array(depth_16bit_image, dtype=np.float32) / 65535
|
| 91 |
refined_depth = refine_depth(depth_array)
|
| 92 |
|
| 93 |
# Apply edge detection to enhance the subject's edges
|
| 94 |
+
print("Applying edge detection...")
|
| 95 |
+
sobel_x = filters.sobel_v(refined_depth)
|
| 96 |
+
sobel_y = filters.sobel_h(refined_depth)
|
| 97 |
gradient_magnitude = np.hypot(sobel_x, sobel_y)
|
| 98 |
|
| 99 |
# Generate an edge mask that captures only strong edges
|
|
|
|
| 101 |
|
| 102 |
# Keep depth values only within the edge mask area (isolating the main subject)
|
| 103 |
refined_depth = np.where(edge_mask, refined_depth, 0)
|
| 104 |
+
print("Depth refinement completed.")
|
| 105 |
|
| 106 |
return refined_depth, depth_16bit_image_path
|
| 107 |
except Exception as e:
|
| 108 |
+
print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
|
| 109 |
return None, None
|
| 110 |
|
| 111 |
def refine_depth(depth_array):
|
| 112 |
"""Refine depth map with smoothing and edge-aware processing."""
|
| 113 |
try:
|
| 114 |
+
print("Applying morphological transformations...")
|
| 115 |
kernel = np.ones((3, 3), np.uint8)
|
| 116 |
depth_cleaned = cv2.morphologyEx(depth_array, cv2.MORPH_CLOSE, kernel)
|
| 117 |
+
|
| 118 |
+
print("Applying edge-preserving filter...")
|
| 119 |
depth_filtered = cv2.edgePreservingFilter(
|
| 120 |
(depth_cleaned * 255).astype(np.uint8), flags=1, sigma_s=8, sigma_r=0.3
|
| 121 |
).astype(np.float32) / 255
|
| 122 |
+
|
| 123 |
+
print("Applying Gaussian blur...")
|
| 124 |
depth_smoothed = cv2.GaussianBlur(depth_filtered, (5, 5), sigmaX=3, sigmaY=3)
|
| 125 |
+
|
| 126 |
+
print("Applying bilateral filter...")
|
| 127 |
depth_final = cv2.bilateralFilter((depth_smoothed * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
|
| 128 |
+
print("Depth refinement process completed.")
|
| 129 |
return depth_final
|
| 130 |
except Exception as e:
|
| 131 |
+
print(f"Error refining depth: {type(e).__name__} - {e}")
|
| 132 |
return None
|
| 133 |
|
| 134 |
def save_raw_16bit(depth, fpath="raw.png"):
|
| 135 |
"""Save depth as raw 16-bit PNG."""
|
| 136 |
try:
|
| 137 |
+
print("Saving raw 16-bit depth image...")
|
| 138 |
if isinstance(depth, torch.Tensor):
|
| 139 |
depth = depth.squeeze().cpu().numpy()
|
| 140 |
|
|
|
|
| 143 |
|
| 144 |
depth = (depth * 65535).astype(np.uint16)
|
| 145 |
cv2.imwrite(fpath, depth)
|
| 146 |
+
print(f"Raw depth image saved to {fpath}.")
|
| 147 |
except Exception as e:
|
| 148 |
+
print(f"Error saving raw depth: {type(e).__name__} - {e}")
|
| 149 |
|
| 150 |
def get_mesh(image: Image.Image, depth_array):
|
| 151 |
"""Generate 3D mesh from depth array and image."""
|
| 152 |
try:
|
| 153 |
+
print("Resizing depth image...")
|
| 154 |
depth_array = (depth_array * 65535).astype(np.uint16)
|
| 155 |
depth_image_resized = Image.fromarray(depth_array)
|
| 156 |
|
| 157 |
if image.size != depth_image_resized.size:
|
| 158 |
image = image.resize(depth_image_resized.size, Image.Resampling.LANCZOS)
|
| 159 |
|
| 160 |
+
print("Converting depth and image to Open3D format...")
|
| 161 |
depth_o3d = o3d.geometry.Image(np.array(depth_image_resized))
|
| 162 |
image_o3d = o3d.geometry.Image(np.array(image))
|
| 163 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
|
|
|
| 165 |
)
|
| 166 |
|
| 167 |
# Camera intrinsics
|
| 168 |
+
print("Setting up camera intrinsics...")
|
| 169 |
w, h = image.size
|
| 170 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
|
| 171 |
|
| 172 |
# Generate point cloud
|
| 173 |
+
print("Generating point cloud...")
|
| 174 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 175 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
|
| 176 |
pcd.orient_normals_consistent_tangent_plane(k=10)
|
| 177 |
|
| 178 |
# Generate Poisson mesh
|
| 179 |
+
print("Generating Poisson mesh...")
|
| 180 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=12)
|
| 181 |
density_threshold = np.quantile(np.asarray(densities), 0.06)
|
| 182 |
vertices_to_remove = densities < density_threshold
|
| 183 |
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
|
| 184 |
|
| 185 |
# Simplify and smooth mesh
|
| 186 |
+
print("Simplifying and smoothing mesh...")
|
| 187 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
|
| 188 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 189 |
voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average
|
|
|
|
| 191 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 192 |
|
| 193 |
# Compute UV mapping for texturing
|
| 194 |
+
print("Computing UV mapping...")
|
| 195 |
mesh.compute_vertex_normals()
|
| 196 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh.vertices])
|
| 197 |
mesh.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
|
|
|
| 203 |
|
| 204 |
return gltf_path
|
| 205 |
except Exception as e:
|
| 206 |
+
print(f"Error generating 3D mesh: {type(e).__name__} - {e}")
|
| 207 |
return None
|
| 208 |
|
| 209 |
def process_image(image_path):
|
|
|
|
| 216 |
if refined_depth is None or depth_16bit_path is None:
|
| 217 |
return None, None
|
| 218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
return depth_16bit_path, gltf_path
|
| 220 |
except Exception as e:
|
| 221 |
print(f"Error processing image: {e}")
|