Update app.py
Browse files
app.py
CHANGED
|
@@ -39,7 +39,6 @@ def process_image(image_path, depth_map_path=None):
|
|
| 39 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 40 |
depth_image = np.array(depth_image, dtype=np.float32)
|
| 41 |
|
| 42 |
-
# Normalize depth image to [0, 1]
|
| 43 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
|
| 44 |
depth_image = np.clip(depth_image, 0, 1)
|
| 45 |
else:
|
|
@@ -49,7 +48,6 @@ def process_image(image_path, depth_map_path=None):
|
|
| 49 |
outputs = model(**encoding)
|
| 50 |
predicted_depth = outputs.predicted_depth
|
| 51 |
|
| 52 |
-
# Resize and normalize depth map
|
| 53 |
prediction = torch.nn.functional.interpolate(
|
| 54 |
predicted_depth.unsqueeze(1),
|
| 55 |
size=image.size[::-1],
|
|
@@ -58,54 +56,61 @@ def process_image(image_path, depth_map_path=None):
|
|
| 58 |
).squeeze()
|
| 59 |
depth_image = prediction.cpu().numpy().astype(np.float32)
|
| 60 |
|
| 61 |
-
# Normalize depth to [0, 1]
|
| 62 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
|
| 63 |
depth_image = np.clip(depth_image, 0, 1)
|
| 64 |
|
| 65 |
-
# Resize
|
| 66 |
depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
# background = remove(image_raw, only_mask=True)
|
| 86 |
-
# background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 87 |
-
# background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=2, flags=cv2.INPAINT_TELEA)
|
| 88 |
|
| 89 |
try:
|
| 90 |
-
#
|
| 91 |
-
gltf_path = create_3d_obj(
|
| 92 |
img = Image.fromarray(depth_display)
|
| 93 |
return [img, gltf_path, gltf_path]
|
| 94 |
except Exception as e:
|
| 95 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 96 |
-
gltf_path = create_3d_obj(
|
| 97 |
img = Image.fromarray(depth_display)
|
| 98 |
return [img, gltf_path, gltf_path]
|
| 99 |
-
|
| 100 |
def create_3d_obj(foreground, depth_image, image_path, depth=12):
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
depth_image_resized = np.array(
|
| 103 |
Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 104 |
)
|
| 105 |
-
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) /
|
| 106 |
-
|
| 107 |
-
) * 255.0
|
| 108 |
-
depth_image_normalized = depth_image_normalized.astype(np.float32)
|
| 109 |
|
| 110 |
# Create Open3D RGBD image
|
| 111 |
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
|
@@ -114,53 +119,48 @@ def create_3d_obj(foreground, depth_image, image_path, depth=12):
|
|
| 114 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 115 |
)
|
| 116 |
|
| 117 |
-
#
|
| 118 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 119 |
-
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 120 |
-
camera_intrinsic.set_intrinsics(w, h, 2000, 2000, w / 2, h / 2)
|
| 121 |
|
| 122 |
-
#
|
| 123 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 124 |
|
| 125 |
-
#
|
| 126 |
if len(pcd.points) < 100:
|
| 127 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 128 |
|
| 129 |
-
# Estimate normals with
|
| 130 |
-
|
| 131 |
-
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.02, max_nn=80))
|
| 132 |
|
| 133 |
-
# Orient normals
|
| 134 |
-
|
| 135 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
|
| 136 |
-
else:
|
| 137 |
-
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 138 |
|
| 139 |
-
# Create
|
| 140 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 141 |
pcd, depth=depth, width=0, scale=2, linear_fit=True
|
| 142 |
)
|
| 143 |
|
| 144 |
-
#
|
| 145 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 2200
|
| 146 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 147 |
voxel_size=voxel_size,
|
| 148 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 149 |
)
|
| 150 |
|
| 151 |
-
# Apply Laplacian smoothing
|
| 152 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 153 |
|
| 154 |
-
# Crop to bounding box around main subject
|
| 155 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 156 |
mesh_crop = mesh.crop(bbox)
|
| 157 |
|
| 158 |
-
#
|
| 159 |
mesh_crop.compute_vertex_normals()
|
| 160 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
|
| 161 |
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
| 162 |
|
| 163 |
-
# Save texture image
|
| 164 |
texture_path = f"./{image_path.stem}_texture.png"
|
| 165 |
Image.fromarray(foreground).save(texture_path)
|
| 166 |
mesh_crop.textures = [o3d.geometry.Image(np.array(foreground))]
|
|
@@ -168,9 +168,8 @@ def create_3d_obj(foreground, depth_image, image_path, depth=12):
|
|
| 168 |
# Export to glTF format
|
| 169 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 170 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 171 |
-
|
| 172 |
return gltf_path
|
| 173 |
-
|
| 174 |
# Gradio Interface
|
| 175 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 176 |
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."
|
|
|
|
| 39 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 40 |
depth_image = np.array(depth_image, dtype=np.float32)
|
| 41 |
|
|
|
|
| 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:
|
|
|
|
| 48 |
outputs = model(**encoding)
|
| 49 |
predicted_depth = outputs.predicted_depth
|
| 50 |
|
|
|
|
| 51 |
prediction = torch.nn.functional.interpolate(
|
| 52 |
predicted_depth.unsqueeze(1),
|
| 53 |
size=image.size[::-1],
|
|
|
|
| 56 |
).squeeze()
|
| 57 |
depth_image = prediction.cpu().numpy().astype(np.float32)
|
| 58 |
|
|
|
|
| 59 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
|
| 60 |
depth_image = np.clip(depth_image, 0, 1)
|
| 61 |
|
| 62 |
+
# Resize depth map and create an edge-aware mask
|
| 63 |
depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
|
| 64 |
+
mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
|
| 65 |
+
|
| 66 |
+
# Create an edge mask to detect the edges of the main subject
|
| 67 |
+
edges = cv2.Canny(img_as_ubyte(mask), threshold1=100, threshold2=200)
|
| 68 |
+
edges_dilated = cv2.dilate(edges, np.ones((3, 3), np.uint8), iterations=1)
|
| 69 |
+
|
| 70 |
+
# Erode the depth map slightly around edges to remove any background extensions
|
| 71 |
+
kernel = np.ones((5, 5), np.uint8)
|
| 72 |
+
depth_eroded = cv2.erode(depth_image * mask, kernel, iterations=2)
|
| 73 |
+
|
| 74 |
+
# Apply the edge-aware mask to limit depth to the main subject only
|
| 75 |
+
depth_subject_only = np.where(edges_dilated == 0, depth_eroded, 0)
|
| 76 |
+
|
| 77 |
+
# Set depth to zero in the background and around subject edges
|
| 78 |
+
depth_subject_only[~mask] = 0
|
| 79 |
+
|
| 80 |
+
# Generate the final depth image with reduced blur artifacts
|
| 81 |
+
depth_display = img_as_ubyte(depth_subject_only)
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
try:
|
| 84 |
+
# Generate the 3D model
|
| 85 |
+
gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
|
| 86 |
img = Image.fromarray(depth_display)
|
| 87 |
return [img, gltf_path, gltf_path]
|
| 88 |
except Exception as e:
|
| 89 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 90 |
+
gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=8)
|
| 91 |
img = Image.fromarray(depth_display)
|
| 92 |
return [img, gltf_path, gltf_path]
|
| 93 |
+
|
| 94 |
def create_3d_obj(foreground, depth_image, image_path, depth=12):
|
| 95 |
+
"""
|
| 96 |
+
Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
|
| 97 |
+
|
| 98 |
+
Parameters:
|
| 99 |
+
foreground (np.array): The main subject image (RGB).
|
| 100 |
+
depth_image (np.array): The depth map array for the main subject only.
|
| 101 |
+
image_path (str): Path to save the output model.
|
| 102 |
+
depth (int): Poisson reconstruction depth value for high detail.
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
str: Path to the saved 3D model (.gltf).
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
# Resize and normalize depth image to align with the foreground
|
| 109 |
depth_image_resized = np.array(
|
| 110 |
Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 111 |
)
|
| 112 |
+
depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
|
| 113 |
+
(depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
|
|
|
|
|
|
|
| 114 |
|
| 115 |
# Create Open3D RGBD image
|
| 116 |
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
|
|
|
| 119 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 120 |
)
|
| 121 |
|
| 122 |
+
# Define camera intrinsics based on image dimensions
|
| 123 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 124 |
+
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
|
|
|
|
| 125 |
|
| 126 |
+
# Generate point cloud and apply strict filtering on depth
|
| 127 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 128 |
|
| 129 |
+
# Ensure minimum point count for robust 3D reconstruction
|
| 130 |
if len(pcd.points) < 100:
|
| 131 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 132 |
|
| 133 |
+
# Estimate normals with refined parameters for detail
|
| 134 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.02, max_nn=80))
|
|
|
|
| 135 |
|
| 136 |
+
# Orient normals towards a distant camera position
|
| 137 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
# Create Poisson mesh with main subject-only depth
|
| 140 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 141 |
pcd, depth=depth, width=0, scale=2, linear_fit=True
|
| 142 |
)
|
| 143 |
|
| 144 |
+
# Simplify with smaller voxel size for more detail
|
| 145 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 2200
|
| 146 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 147 |
voxel_size=voxel_size,
|
| 148 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 149 |
)
|
| 150 |
|
| 151 |
+
# Apply Laplacian smoothing to improve surface quality
|
| 152 |
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
|
| 153 |
|
| 154 |
+
# Crop mesh to bounding box around main subject only
|
| 155 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 156 |
mesh_crop = mesh.crop(bbox)
|
| 157 |
|
| 158 |
+
# Compute UV mapping for texturing
|
| 159 |
mesh_crop.compute_vertex_normals()
|
| 160 |
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
|
| 161 |
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
|
| 162 |
|
| 163 |
+
# Save texture image
|
| 164 |
texture_path = f"./{image_path.stem}_texture.png"
|
| 165 |
Image.fromarray(foreground).save(texture_path)
|
| 166 |
mesh_crop.textures = [o3d.geometry.Image(np.array(foreground))]
|
|
|
|
| 168 |
# Export to glTF format
|
| 169 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 170 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 171 |
+
|
| 172 |
return gltf_path
|
|
|
|
| 173 |
# Gradio Interface
|
| 174 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 175 |
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."
|