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)