File size: 9,835 Bytes
39c2c70 1e8d843 27495ea 39c2c70 202510d 4e9eaed 8f5830b 932c3e0 ba672d1 39c2c70 261e624 202510d 1e8d843 202510d 13e279a cc4b364 1e8d843 932c3e0 1e8d843 e42e284 0b853b9 ba672d1 e42e284 261e624 2bb519d c493dc7 e42e284 c493dc7 f4df5b1 502daac 6abcef5 f4df5b1 e42e284 502daac 39c2c70 502daac 39c2c70 1e8d843 e42e284 c0a6ef0 e42e284 c07e900 e42e284 261e624 e42e284 8254004 e42e284 8254004 261e624 e42e284 b00c2bd e42e284 cc4b364 e42e284 cc4b364 e42e284 e1f5912 e42e284 e1f5912 e42e284 171c0f8 e42e284 171c0f8 e42e284 cc4b364 6be6fc0 261e624 873ee75 39c2c70 502daac 39c2c70 873ee75 e1f5912 873ee75 261e624 95a1586 873ee75 261e624 873ee75 ef3100a 95a1586 261e624 b3933da 261e624 315ac2a c0a6ef0 261e624 c0a6ef0 261e624 c0a6ef0 261e624 8254004 261e624 b3933da 261e624 fba8e3a 873ee75 502daac b00c2bd 502daac 261e624 4eb1838 261e624 502daac e1f5912 8254004 c0a6ef0 502daac 261e624 4a47309 261e624 e1f5912 261e624 c0a6ef0 e1f5912 502daac 7bdd85d b79af75 4eb1838 7bdd85d 502daac d1c4755 c0a6ef0 e1f5912 c0a6ef0 1e8d843 932c3e0 ba672d1 932c3e0 0b853b9 c0a6ef0 0b853b9 502daac | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | from skimage import img_as_ubyte
from skimage.segmentation import clear_border
from scipy.ndimage import sobel
import gradio as gr
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
import torch
import numpy as np
from PIL import Image
import open3d as o3d
from pathlib import Path
import os
import cv2
from rembg import remove
# Initialize model and feature extractor for depth estimation
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
# Other imports and initialization remain unchanged
def process_image(image_path, depth_map_path=None):
image_path = Path(image_path)
image_raw = Image.open(image_path).convert("RGB")
image = image_raw.resize(
(3072, int(3072 * image_raw.size[1] / image_raw.size[0])),
Image.Resampling.LANCZOS,
)
# Remove background to isolate the main subject
foreground = remove(image_raw)
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
# Load or generate depth map
if depth_map_path:
if depth_map_path.endswith('.npy'):
depth_image = np.load(depth_map_path).astype(np.float32)
depth_image = 1 - depth_image # Invert depth for npy files
else:
depth_image_raw = Image.open(depth_map_path).convert("L")
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
depth_image = np.array(depth_image, dtype=np.float32)
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
depth_image = np.clip(depth_image, 0, 1)
else:
# Generate depth map using DPT model
encoding = feature_extractor(foreground, return_tensors="pt")
with torch.no_grad():
outputs = model(**encoding)
predicted_depth = outputs.predicted_depth
prediction = torch.nn.functional.interpolate(
predicted_depth.unsqueeze(1),
size=image.size[::-1],
mode="bicubic",
align_corners=False,
).squeeze()
depth_image = prediction.cpu().numpy().astype(np.float32)
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
depth_image = np.clip(depth_image, 0, 1)
# Step 1: Depth refinement (Morphological closing)
kernel = np.ones((3, 3), np.uint8)
depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
# Step 2: Edge-preserving filter (Enhance small structures)
depth_image = cv2.edgePreservingFilter(
(depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
)
depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
# Step 3: Smooth depth map with Gaussian filter
depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
# Step 4: Bilateral filter for detail preservation
depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 5, 50, 50).astype(np.float32) / 255
# Step 5: Resize the depth map to match the foreground size
depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
# Step 6: Clean up depth map using mask
mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
depth_subject_only = depth_image * mask
depth_subject_only[~mask] = 0 # Ensure background areas are zeroed out
# Generate the final depth image with reduced blur artifacts
depth_display = img_as_ubyte(depth_subject_only)
try:
# Generate the 3D model
gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
img = Image.fromarray(depth_display)
return [img, gltf_path, gltf_path]
except Exception as e:
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=9)
img = Image.fromarray(depth_display)
return [img, gltf_path, gltf_path]
def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
"""
Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
Parameters:
foreground (np.array): The main subject image (RGB).
depth_image (np.array): The depth map array for the main subject only.
image_path (str): Path to save the output model.
depth (int): Poisson reconstruction depth value for high detail.
edge_strength (float): Strength of the edge thresholding for sharper subject boundaries.
Returns:
str: Path to the saved 3D model (.gltf).
"""
# Resize and normalize depth image to align with the foreground dimensions
depth_image_resized = np.array(
Image.fromarray((depth_image * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
)
# Normalize depth map and set background to zero (remove background noise)
depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) /
(depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
# Apply edge detection to enhance the subject’s edges
sobel_x = sobel(depth_image_normalized, axis=0)
sobel_y = sobel(depth_image_normalized, axis=1)
gradient_magnitude = np.hypot(sobel_x, sobel_y)
# Generate an edge mask that captures only strong edges
edge_mask = gradient_magnitude < (gradient_magnitude.max() * edge_strength)
# Keep depth values only within the edge mask area (isolating the main subject)
depth_image_sharpened = np.where(edge_mask, depth_image_normalized, 0)
# Create Open3D RGBD image
depth_o3d = o3d.geometry.Image(depth_image_sharpened)
image_o3d = o3d.geometry.Image(foreground)
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
image_o3d, depth_o3d, convert_rgb_to_intensity=False
)
# Define camera intrinsics based on image dimensions
w, h = foreground.shape[1], foreground.shape[0]
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
# Generate point cloud and apply depth-focused filtering
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
# Check minimum point count for normals estimation
if len(pcd.points) < 100:
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
# Estimate normals with refined parameters
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=100))
pcd.orient_normals_consistent_tangent_plane(k=10)
# Orient normals towards a distant camera position
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
# Create Poisson mesh using main subject's isolated depth
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
pcd, depth=depth, width=0, scale=4, linear_fit=True
)
# Remove low-density artifacts
density_threshold = np.quantile(np.asarray(densities), 0.06) # Adjust quantile as needed
vertices_to_remove = densities < density_threshold
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
# Simplify with smaller voxel size for more detail
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 6200
mesh = mesh_raw.simplify_vertex_clustering(
voxel_size=voxel_size,
contraction=o3d.geometry.SimplificationContraction.Average,
)
# Apply Laplacian smoothing
mesh = mesh.filter_smooth_laplacian(number_of_iterations=2)
# Crop mesh to bounding box around main subject only
bbox = pcd.get_axis_aligned_bounding_box()
mesh_crop = mesh.crop(bbox)
# Compute UV mapping for texturing
mesh_crop.compute_vertex_normals()
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in mesh_crop.vertices])
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
# Save high-resolution texture image
texture_path = f"./{image_path.stem}_texture_highres.png"
foreground_pil = Image.fromarray(foreground)
high_res_texture = foreground_pil.resize((3096, 3096), Image.LANCZOS) # Increased resolution for finer details
high_res_texture.save(texture_path)
# Apply the high-resolution texture and export the mesh as a GLTF file
mesh_crop.textures = [o3d.geometry.Image(np.array(high_res_texture))]
gltf_path = f"./{image_path.stem}_model.gltf"
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
return gltf_path
# Gradio Interface
title = "Depth Estimation & 3D Reconstruction Demo"
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."
examples = [["examples/" + img] for img in os.listdir("examples/")]
iface = gr.Interface(
fn=process_image,
inputs=[
gr.Image(type="filepath", label="Input Image"),
gr.File(type="filepath", label="Input Depth Map (optional)"),
],
outputs=[
gr.Image(label="Predicted Depth", type="pil"),
gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
gr.File(label="3D gLTF File"),
],
title=title,
description=description,
examples=examples,
allow_flagging="never",
cache_examples=False,
)
iface.launch(debug=True, show_api=True, share=True) |