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 from skimage import img_as_ubyte from skimage.filters import gaussian from skimage.segmentation import clear_border # Initialize model and feature extractor for depth estimation feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large") model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large") 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( (2048, int(2048 * image_raw.size[1] / image_raw.size[0])), Image.Resampling.LANCZOS, ) # Remove background using rembg foreground = remove(image_raw) foreground = Image.fromarray(np.array(foreground)).convert("RGB") # Create a binary mask of the foreground foreground_edges = cv2.Canny(np.array(foreground), 100, 200) # Resize foreground edges to match depth image dimensions foreground_edges_resized = cv2.resize(foreground_edges, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST) # Check if user-provided depth map is available if depth_map_path: if depth_map_path.endswith('.npy'): depth_image = np.load(depth_map_path) depth_image = 1 - depth_image # Invert depth only 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) # Normalize depth image depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image)) depth_image = depth_image.astype('float32') # Directly convert to float32 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() - np.min(prediction.cpu().numpy())) / (np.max(prediction.cpu().numpy()) - np.min(prediction.cpu().numpy())) # Normalize depth values depth_image = depth_image.astype("float32") # Changed to float32 # Resize and apply Gaussian smoothing for smoother transitions depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC) mask_blurred = cv2.GaussianBlur(depth_image, (5, 5), 1.0) # Blend depth_image with mask_blurred for smoother transition blended_depth_image = cv2.addWeighted(depth_image, 0.7, mask_blurred, 0.3, 0) # Sharpen subject edges slightly depth_image[foreground_edges_resized > 0] = depth_image[foreground_edges_resized > 0] * 1.2 # Inpaint background where the main subject was removed background = remove(image_raw, only_mask=True) background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR) background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=5, flags=cv2.INPAINT_TELEA) # Scale up background to prevent cropping and maintain colors bg_scaled = cv2.resize(background_inpainted, (int(image.width * 1.2), int(image.height * 1.2))) # Optionally, adjust the foreground position and flatten the back foreground_flat = np.array(foreground) foreground_flat = foreground_flat[:, :, :3] # Keep only RGB channels foreground_flat = np.insert(foreground_flat, 2, values=0, axis=2) # Add a zero channel for depth try: gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path) img = Image.fromarray(blended_depth_image) return [img, gltf_path] except Exception as e: print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.") gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path, depth=9) img = Image.fromarray(blended_depth_image) return [img, gltf_path] def create_3d_obj(foreground, depth_image, background, image_path, depth=10): # Resize background to match the original image size (no cropping) background_resized = cv2.resize(background, (foreground.shape[1], foreground.shape[0]), interpolation=cv2.INTER_LINEAR) # Resize and normalize the depth image depth_image_resized = np.array( Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS) ) # Normalize depth for float32 representation depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / ( depth_image_resized.max() - depth_image_resized.min() ) # Ensure depth image is valid if np.all(depth_image_normalized == 0): raise RuntimeError("Depth image normalization resulted in all zeros.") depth_image_normalized = depth_image_normalized.astype(np.float32) # Create flat background depth with a small gap for empty space background_depth = np.zeros_like(depth_image_normalized) + 1.5 # Combine depths to create the illusion of an empty space combined_depth = np.maximum(depth_image_normalized * 0.5, background_depth) depth_o3d = o3d.geometry.Image(combined_depth) image_o3d = o3d.geometry.Image(foreground) # Create RGBD image directly without using width and height rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth( image_o3d, depth_o3d, convert_rgb_to_intensity=False ) # Get dimensions of the rgbd_image rgbd_width, rgbd_height = rgbd_image.color.shape[1], rgbd_image.color.shape[0] # Check if the depth and foreground sizes are compatible if rgbd_width != foreground.shape[1] or rgbd_height != foreground.shape[0]: raise RuntimeError("RGBD image dimensions do not match foreground dimensions.") # Camera intrinsic setup camera_intrinsic = o3d.camera.PinholeCameraIntrinsic() camera_intrinsic.set_intrinsics(rgbd_width, rgbd_height, 1500, 1500, rgbd_width / 2, rgbd_height / 2) # Create the point cloud pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic) # Check if the point cloud is valid print(f"Point Cloud Size: {len(pcd.points)}") if len(pcd.points) < 100: raise RuntimeError("Insufficient points in the point cloud for normals estimation.") # Estimate normals and orient pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50)) pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0])) # Generate 3D mesh using Poisson reconstruction mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson( pcd, depth=depth, width=0, scale=1.2, linear_fit=True ) # Validate mesh creation if not mesh_raw.has_triangles(): raise RuntimeError("No triangles found in the generated mesh. Check the point cloud data.") # Simplify and smooth the mesh voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400 mesh = mesh_raw.simplify_vertex_clustering( voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average, ) mesh = mesh.filter_smooth_simple(number_of_iterations=3) # Validate the mesh before cropping if mesh.is_empty(): raise RuntimeError("The mesh is empty after processing.") # Save mesh to GLTF format output_dir = Path("output") output_dir.mkdir(parents=True, exist_ok=True) gltf_path = output_dir / f"{image_path.stem}.gltf" o3d.io.write_triangle_mesh(str(gltf_path), mesh) return str(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)