Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,7 @@ from rembg import remove
|
|
| 9 |
import open3d as o3d
|
| 10 |
import tempfile
|
| 11 |
from skimage import filters
|
|
|
|
| 12 |
|
| 13 |
# Handle GPU availability in Hugging Face Spaces with ZeroGPU
|
| 14 |
if os.environ.get("SPACES_ZERO_GPU") is not None:
|
|
@@ -62,12 +63,12 @@ def predict_depth(image: Image.Image):
|
|
| 62 |
try:
|
| 63 |
print("Processing input image...")
|
| 64 |
image = image.convert("RGB")
|
| 65 |
-
|
| 66 |
# Step 1: Remove background to isolate the main subject
|
| 67 |
print("Removing background...")
|
| 68 |
foreground = remove(image)
|
| 69 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 70 |
-
|
| 71 |
# Depth prediction
|
| 72 |
print("Predicting depth...")
|
| 73 |
depth = pipe(
|
|
@@ -76,40 +77,41 @@ def predict_depth(image: Image.Image):
|
|
| 76 |
num_inference_steps=4
|
| 77 |
)
|
| 78 |
print("Depth prediction completed.")
|
| 79 |
-
|
| 80 |
# Export high-quality depth as 16-bit PNG
|
| 81 |
print("Exporting 16-bit depth image...")
|
| 82 |
depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
|
| 83 |
depth_16bit_image = depth_16bit[0]
|
| 84 |
-
|
| 85 |
# Save depth as 16-bit PNG for further processing
|
| 86 |
depth_16bit_image_path = "depth_16bit_image.png"
|
| 87 |
depth_16bit_image.save(depth_16bit_image_path)
|
| 88 |
print(f"16-bit depth image saved to {depth_16bit_image_path}.")
|
| 89 |
-
|
| 90 |
# Convert depth to numpy array for refinement
|
| 91 |
print("Refining depth map...")
|
| 92 |
depth_array = np.array(depth_16bit_image, dtype=np.float32) / 65535
|
| 93 |
refined_depth = refine_depth(depth_array)
|
| 94 |
-
|
| 95 |
# Apply edge detection to enhance the subject's edges
|
| 96 |
print("Applying edge detection...")
|
| 97 |
sobel_x = filters.sobel_v(refined_depth)
|
| 98 |
sobel_y = filters.sobel_h(refined_depth)
|
| 99 |
gradient_magnitude = np.hypot(sobel_x, sobel_y)
|
| 100 |
-
|
| 101 |
# Generate an edge mask that captures only strong edges
|
| 102 |
edge_mask = gradient_magnitude < (gradient_magnitude.max() * 0.15)
|
| 103 |
-
|
| 104 |
# Keep depth values only within the edge mask area (isolating the main subject)
|
| 105 |
refined_depth = np.where(edge_mask, refined_depth, 0)
|
| 106 |
print("Depth refinement completed.")
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
| 113 |
return refined_depth, depth_16bit_image_path
|
| 114 |
except Exception as e:
|
| 115 |
print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
|
|
@@ -121,7 +123,7 @@ def refine_depth(depth_array):
|
|
| 121 |
print("Applying morphological transformations...")
|
| 122 |
kernel = np.ones((3, 3), np.uint8)
|
| 123 |
depth_cleaned = cv2.morphologyEx(depth_array, cv2.MORPH_CLOSE, kernel)
|
| 124 |
-
|
| 125 |
print("Applying edge-preserving filter...")
|
| 126 |
depth_filtered = cv2.edgePreservingFilter(
|
| 127 |
(depth_cleaned * 255).astype(np.uint8),
|
|
@@ -129,13 +131,13 @@ def refine_depth(depth_array):
|
|
| 129 |
sigma_s=8,
|
| 130 |
sigma_r=0.3
|
| 131 |
).astype(np.float32) / 255
|
| 132 |
-
|
| 133 |
print("Applying Gaussian blur...")
|
| 134 |
depth_smoothed = cv2.GaussianBlur(depth_filtered, (5, 5), sigmaX=3, sigmaY=3)
|
| 135 |
-
|
| 136 |
print("Applying bilateral filter...")
|
| 137 |
depth_final = cv2.bilateralFilter((depth_smoothed * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
|
| 138 |
-
|
| 139 |
print("Depth refinement process completed.")
|
| 140 |
return depth_final
|
| 141 |
except Exception as e:
|
|
@@ -162,40 +164,32 @@ def get_mesh(image: Image.Image, depth_array):
|
|
| 162 |
print("Resizing depth image...")
|
| 163 |
depth_array = (depth_array * 65535).astype(np.uint16)
|
| 164 |
depth_image_resized = Image.fromarray(depth_array)
|
| 165 |
-
|
| 166 |
if image.size != depth_image_resized.size:
|
| 167 |
image = image.resize(depth_image_resized.size, Image.Resampling.LANCZOS)
|
| 168 |
-
|
| 169 |
print("Converting depth and image to Open3D format...")
|
| 170 |
depth_o3d = o3d.geometry.Image(np.array(depth_image_resized))
|
| 171 |
image_o3d = o3d.geometry.Image(np.array(image))
|
| 172 |
-
|
| 173 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 174 |
image_o3d,
|
| 175 |
depth_o3d,
|
| 176 |
convert_rgb_to_intensity=False
|
| 177 |
)
|
| 178 |
-
|
| 179 |
# Camera intrinsics
|
| 180 |
print("Setting up camera intrinsics...")
|
| 181 |
w, h = image.size
|
| 182 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
|
| 183 |
-
|
| 184 |
# Generate point cloud
|
| 185 |
print("Generating point cloud...")
|
| 186 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 187 |
-
|
| 188 |
-
# Check if point cloud is empty
|
| 189 |
-
if pcd.is_empty():
|
| 190 |
-
print("Point cloud is empty.")
|
| 191 |
-
return None
|
| 192 |
-
|
| 193 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
|
| 194 |
-
|
| 195 |
# Generate Poisson mesh
|
| 196 |
print("Generating Poisson mesh...")
|
| 197 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=12)
|
| 198 |
-
|
| 199 |
density_threshold = np.quantile(np.asarray(densities), 0.06)
|
| 200 |
vertices_to_remove = densities < density_threshold
|
| 201 |
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
|
|
@@ -204,7 +198,8 @@ def get_mesh(image: Image.Image, depth_array):
|
|
| 204 |
print("Simplifying and smoothing mesh...")
|
| 205 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
|
| 206 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 207 |
-
voxel_size=voxel_size,
|
|
|
|
| 208 |
)
|
| 209 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 210 |
|
|
|
|
| 9 |
import open3d as o3d
|
| 10 |
import tempfile
|
| 11 |
from skimage import filters
|
| 12 |
+
import gc
|
| 13 |
|
| 14 |
# Handle GPU availability in Hugging Face Spaces with ZeroGPU
|
| 15 |
if os.environ.get("SPACES_ZERO_GPU") is not None:
|
|
|
|
| 63 |
try:
|
| 64 |
print("Processing input image...")
|
| 65 |
image = image.convert("RGB")
|
| 66 |
+
|
| 67 |
# Step 1: Remove background to isolate the main subject
|
| 68 |
print("Removing background...")
|
| 69 |
foreground = remove(image)
|
| 70 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 71 |
+
|
| 72 |
# Depth prediction
|
| 73 |
print("Predicting depth...")
|
| 74 |
depth = pipe(
|
|
|
|
| 77 |
num_inference_steps=4
|
| 78 |
)
|
| 79 |
print("Depth prediction completed.")
|
| 80 |
+
|
| 81 |
# Export high-quality depth as 16-bit PNG
|
| 82 |
print("Exporting 16-bit depth image...")
|
| 83 |
depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
|
| 84 |
depth_16bit_image = depth_16bit[0]
|
| 85 |
+
|
| 86 |
# Save depth as 16-bit PNG for further processing
|
| 87 |
depth_16bit_image_path = "depth_16bit_image.png"
|
| 88 |
depth_16bit_image.save(depth_16bit_image_path)
|
| 89 |
print(f"16-bit depth image saved to {depth_16bit_image_path}.")
|
| 90 |
+
|
| 91 |
# Convert depth to numpy array for refinement
|
| 92 |
print("Refining depth map...")
|
| 93 |
depth_array = np.array(depth_16bit_image, dtype=np.float32) / 65535
|
| 94 |
refined_depth = refine_depth(depth_array)
|
| 95 |
+
|
| 96 |
# Apply edge detection to enhance the subject's edges
|
| 97 |
print("Applying edge detection...")
|
| 98 |
sobel_x = filters.sobel_v(refined_depth)
|
| 99 |
sobel_y = filters.sobel_h(refined_depth)
|
| 100 |
gradient_magnitude = np.hypot(sobel_x, sobel_y)
|
| 101 |
+
|
| 102 |
# Generate an edge mask that captures only strong edges
|
| 103 |
edge_mask = gradient_magnitude < (gradient_magnitude.max() * 0.15)
|
| 104 |
+
|
| 105 |
# Keep depth values only within the edge mask area (isolating the main subject)
|
| 106 |
refined_depth = np.where(edge_mask, refined_depth, 0)
|
| 107 |
print("Depth refinement completed.")
|
| 108 |
+
|
| 109 |
+
del depth
|
| 110 |
+
del depth_16bit
|
| 111 |
+
del depth_16bit_image
|
| 112 |
+
gc.collect()
|
| 113 |
+
torch.cuda.empty_cache()
|
| 114 |
+
|
| 115 |
return refined_depth, depth_16bit_image_path
|
| 116 |
except Exception as e:
|
| 117 |
print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
|
|
|
|
| 123 |
print("Applying morphological transformations...")
|
| 124 |
kernel = np.ones((3, 3), np.uint8)
|
| 125 |
depth_cleaned = cv2.morphologyEx(depth_array, cv2.MORPH_CLOSE, kernel)
|
| 126 |
+
|
| 127 |
print("Applying edge-preserving filter...")
|
| 128 |
depth_filtered = cv2.edgePreservingFilter(
|
| 129 |
(depth_cleaned * 255).astype(np.uint8),
|
|
|
|
| 131 |
sigma_s=8,
|
| 132 |
sigma_r=0.3
|
| 133 |
).astype(np.float32) / 255
|
| 134 |
+
|
| 135 |
print("Applying Gaussian blur...")
|
| 136 |
depth_smoothed = cv2.GaussianBlur(depth_filtered, (5, 5), sigmaX=3, sigmaY=3)
|
| 137 |
+
|
| 138 |
print("Applying bilateral filter...")
|
| 139 |
depth_final = cv2.bilateralFilter((depth_smoothed * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
|
| 140 |
+
|
| 141 |
print("Depth refinement process completed.")
|
| 142 |
return depth_final
|
| 143 |
except Exception as e:
|
|
|
|
| 164 |
print("Resizing depth image...")
|
| 165 |
depth_array = (depth_array * 65535).astype(np.uint16)
|
| 166 |
depth_image_resized = Image.fromarray(depth_array)
|
| 167 |
+
|
| 168 |
if image.size != depth_image_resized.size:
|
| 169 |
image = image.resize(depth_image_resized.size, Image.Resampling.LANCZOS)
|
| 170 |
+
|
| 171 |
print("Converting depth and image to Open3D format...")
|
| 172 |
depth_o3d = o3d.geometry.Image(np.array(depth_image_resized))
|
| 173 |
image_o3d = o3d.geometry.Image(np.array(image))
|
|
|
|
| 174 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 175 |
image_o3d,
|
| 176 |
depth_o3d,
|
| 177 |
convert_rgb_to_intensity=False
|
| 178 |
)
|
| 179 |
+
|
| 180 |
# Camera intrinsics
|
| 181 |
print("Setting up camera intrinsics...")
|
| 182 |
w, h = image.size
|
| 183 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
|
| 184 |
+
|
| 185 |
# Generate point cloud
|
| 186 |
print("Generating point cloud...")
|
| 187 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
|
| 189 |
+
|
| 190 |
# Generate Poisson mesh
|
| 191 |
print("Generating Poisson mesh...")
|
| 192 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=12)
|
|
|
|
| 193 |
density_threshold = np.quantile(np.asarray(densities), 0.06)
|
| 194 |
vertices_to_remove = densities < density_threshold
|
| 195 |
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
|
|
|
|
| 198 |
print("Simplifying and smoothing mesh...")
|
| 199 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 7200
|
| 200 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 201 |
+
voxel_size=voxel_size,
|
| 202 |
+
contraction=o3d.geometry.SimplificationContraction.Average
|
| 203 |
)
|
| 204 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 205 |
|