Update app.py
Browse files
app.py
CHANGED
|
@@ -24,21 +24,21 @@ def process_image(image_path, depth_map_path=None):
|
|
| 24 |
Image.Resampling.LANCZOS,
|
| 25 |
)
|
| 26 |
|
| 27 |
-
# Remove background
|
| 28 |
foreground = remove(image_raw)
|
| 29 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 30 |
|
| 31 |
-
# Check if
|
| 32 |
if depth_map_path:
|
| 33 |
if depth_map_path.endswith('.npy'):
|
| 34 |
depth_image = np.load(depth_map_path).astype(np.float32)
|
| 35 |
-
depth_image = 1 - depth_image # Invert depth
|
| 36 |
else:
|
| 37 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 38 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 39 |
depth_image = np.array(depth_image, dtype=np.float32)
|
| 40 |
|
| 41 |
-
# Normalize depth image to [0, 1]
|
| 42 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
|
| 43 |
depth_image = np.clip(depth_image, 0, 1)
|
| 44 |
else:
|
|
@@ -57,43 +57,43 @@ def process_image(image_path, depth_map_path=None):
|
|
| 57 |
).squeeze()
|
| 58 |
depth_image = prediction.cpu().numpy().astype(np.float32)
|
| 59 |
|
| 60 |
-
# Normalize depth
|
| 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 and apply edge-preserving blur
|
| 65 |
depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
|
| 66 |
mask_blurred = cv2.bilateralFilter(depth_image, 5, 50, 50)
|
| 67 |
|
| 68 |
# Apply depth only to main subject
|
| 69 |
foreground_array = np.array(foreground)
|
| 70 |
-
mask = np.all(foreground_array != [0, 0, 0], axis=-1) # Mask
|
| 71 |
|
| 72 |
-
depth_image_subject = depth_image * mask #
|
| 73 |
-
depth_image_subject =
|
| 74 |
|
| 75 |
# Smooth transitions along edges
|
| 76 |
-
blended_depth_image = cv2.addWeighted(depth_image_subject, 0.9, mask_blurred * mask, 0.
|
| 77 |
depth_display = img_as_ubyte(blended_depth_image)
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
background = remove(image_raw, only_mask=True)
|
| 81 |
-
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 82 |
-
background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=2, flags=cv2.INPAINT_TELEA)
|
| 83 |
|
| 84 |
try:
|
| 85 |
-
# Pass updated depth and
|
| 86 |
-
gltf_path = create_3d_obj(foreground_array, blended_depth_image,
|
| 87 |
img = Image.fromarray(depth_display)
|
| 88 |
return [img, gltf_path, gltf_path]
|
| 89 |
except Exception as e:
|
| 90 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 91 |
-
gltf_path = create_3d_obj(foreground_array, blended_depth_image,
|
| 92 |
img = Image.fromarray(depth_display)
|
| 93 |
return [img, gltf_path, gltf_path]
|
| 94 |
|
| 95 |
-
def create_3d_obj(foreground, depth_image,
|
| 96 |
-
# Resize and normalize depth image for more detail
|
| 97 |
depth_image_resized = np.array(
|
| 98 |
Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 99 |
)
|
|
@@ -102,14 +102,14 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=12):
|
|
| 102 |
) * 255.0
|
| 103 |
depth_image_normalized = depth_image_normalized.astype(np.float32)
|
| 104 |
|
| 105 |
-
# Create Open3D RGBD image
|
| 106 |
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
| 107 |
image_o3d = o3d.geometry.Image(foreground)
|
| 108 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 109 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 110 |
)
|
| 111 |
|
| 112 |
-
# Set camera intrinsics
|
| 113 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 114 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 115 |
camera_intrinsic.set_intrinsics(w, h, 2000, 2000, w / 2, h / 2)
|
|
@@ -125,47 +125,47 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=12):
|
|
| 125 |
if not pcd.has_normals():
|
| 126 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.02, max_nn=80))
|
| 127 |
|
| 128 |
-
# Orient normals
|
| 129 |
if pcd.has_normals():
|
| 130 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
|
| 131 |
else:
|
| 132 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 133 |
|
| 134 |
-
# Create
|
| 135 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 136 |
pcd, depth=depth, width=0, scale=2, linear_fit=True
|
| 137 |
)
|
| 138 |
|
| 139 |
-
#
|
| 140 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) /
|
| 141 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 142 |
voxel_size=voxel_size,
|
| 143 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 144 |
)
|
| 145 |
|
| 146 |
-
# Apply Laplacian smoothing
|
| 147 |
-
mesh = mesh.filter_smooth_laplacian(number_of_iterations=
|
| 148 |
-
|
| 149 |
-
#
|
| 150 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 151 |
mesh_crop = mesh.crop(bbox)
|
| 152 |
|
| 153 |
-
# Add
|
| 154 |
mesh_crop.compute_vertex_normals()
|
| 155 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
|
| 156 |
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
| 157 |
|
| 158 |
-
# Save
|
| 159 |
texture_path = f"./{image_path.stem}_texture.png"
|
| 160 |
Image.fromarray(foreground).save(texture_path)
|
| 161 |
mesh_crop.textures = [o3d.geometry.Image(np.array(foreground))]
|
| 162 |
|
| 163 |
-
# Export
|
| 164 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 165 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 166 |
|
| 167 |
return gltf_path
|
| 168 |
-
|
| 169 |
# Gradio Interface
|
| 170 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 171 |
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."
|
|
|
|
| 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 |
+
# Check if a depth map is provided by the user
|
| 32 |
if depth_map_path:
|
| 33 |
if depth_map_path.endswith('.npy'):
|
| 34 |
depth_image = np.load(depth_map_path).astype(np.float32)
|
| 35 |
+
depth_image = 1 - depth_image # Invert depth for npy files
|
| 36 |
else:
|
| 37 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 38 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 39 |
depth_image = np.array(depth_image, dtype=np.float32)
|
| 40 |
|
| 41 |
+
# Normalize depth image to [0, 1]
|
| 42 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
|
| 43 |
depth_image = np.clip(depth_image, 0, 1)
|
| 44 |
else:
|
|
|
|
| 57 |
).squeeze()
|
| 58 |
depth_image = prediction.cpu().numpy().astype(np.float32)
|
| 59 |
|
| 60 |
+
# Normalize depth to [0, 1]
|
| 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 and apply edge-preserving blur to depth map for main subject only
|
| 65 |
depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
|
| 66 |
mask_blurred = cv2.bilateralFilter(depth_image, 5, 50, 50)
|
| 67 |
|
| 68 |
# Apply depth only to main subject
|
| 69 |
foreground_array = np.array(foreground)
|
| 70 |
+
mask = np.all(foreground_array != [0, 0, 0], axis=-1) # Mask for isolating main subject
|
| 71 |
|
| 72 |
+
depth_image_subject = depth_image * mask # Depth for main subject, zero for background
|
| 73 |
+
depth_image_subject[~mask] = 0 # Zero depth beyond main subject to push back
|
| 74 |
|
| 75 |
# Smooth transitions along edges
|
| 76 |
+
blended_depth_image = cv2.addWeighted(depth_image_subject, 0.9, mask_blurred * mask, 0.1, 0)
|
| 77 |
depth_display = img_as_ubyte(blended_depth_image)
|
| 78 |
|
| 79 |
+
# Background removal - commented for potential future use
|
| 80 |
+
# background = remove(image_raw, only_mask=True)
|
| 81 |
+
# background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 82 |
+
# background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=2, flags=cv2.INPAINT_TELEA)
|
| 83 |
|
| 84 |
try:
|
| 85 |
+
# Pass updated depth and isolated main subject to 3D model creation
|
| 86 |
+
gltf_path = create_3d_obj(foreground_array, blended_depth_image, image_path)
|
| 87 |
img = Image.fromarray(depth_display)
|
| 88 |
return [img, gltf_path, gltf_path]
|
| 89 |
except Exception as e:
|
| 90 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 91 |
+
gltf_path = create_3d_obj(foreground_array, blended_depth_image, image_path, depth=8)
|
| 92 |
img = Image.fromarray(depth_display)
|
| 93 |
return [img, gltf_path, gltf_path]
|
| 94 |
|
| 95 |
+
def create_3d_obj(foreground, depth_image, image_path, depth=12):
|
| 96 |
+
# Resize and normalize depth image for more detail
|
| 97 |
depth_image_resized = np.array(
|
| 98 |
Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 99 |
)
|
|
|
|
| 102 |
) * 255.0
|
| 103 |
depth_image_normalized = depth_image_normalized.astype(np.float32)
|
| 104 |
|
| 105 |
+
# Create Open3D RGBD image
|
| 106 |
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
| 107 |
image_o3d = o3d.geometry.Image(foreground)
|
| 108 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 109 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 110 |
)
|
| 111 |
|
| 112 |
+
# Set camera intrinsics
|
| 113 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 114 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 115 |
camera_intrinsic.set_intrinsics(w, h, 2000, 2000, w / 2, h / 2)
|
|
|
|
| 125 |
if not pcd.has_normals():
|
| 126 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.02, max_nn=80))
|
| 127 |
|
| 128 |
+
# Orient normals for accurate 3D surface
|
| 129 |
if pcd.has_normals():
|
| 130 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
|
| 131 |
else:
|
| 132 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 133 |
|
| 134 |
+
# Create high-detail Poisson mesh
|
| 135 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 136 |
pcd, depth=depth, width=0, scale=2, linear_fit=True
|
| 137 |
)
|
| 138 |
|
| 139 |
+
# Smaller voxel size for finer mesh detail
|
| 140 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 2200
|
| 141 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 142 |
voxel_size=voxel_size,
|
| 143 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# Apply Laplacian smoothing for better surface
|
| 147 |
+
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 148 |
+
|
| 149 |
+
# Crop to bounding box around main subject
|
| 150 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 151 |
mesh_crop = mesh.crop(bbox)
|
| 152 |
|
| 153 |
+
# Add UV mapping for texture
|
| 154 |
mesh_crop.compute_vertex_normals()
|
| 155 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
|
| 156 |
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
| 157 |
|
| 158 |
+
# Save texture image for main subject
|
| 159 |
texture_path = f"./{image_path.stem}_texture.png"
|
| 160 |
Image.fromarray(foreground).save(texture_path)
|
| 161 |
mesh_crop.textures = [o3d.geometry.Image(np.array(foreground))]
|
| 162 |
|
| 163 |
+
# Export to glTF format
|
| 164 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 165 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 166 |
|
| 167 |
return gltf_path
|
| 168 |
+
|
| 169 |
# Gradio Interface
|
| 170 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 171 |
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."
|