Spaces:
Runtime error
Runtime error
try handleing the errors
Browse files
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 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
if depth_map_path
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
else:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
#
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
depth_image =
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 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 |
-
|
| 224 |
-
|
| 225 |
-
(depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 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 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
pcd
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|