DEOTH_WITH_3D / app.py
codic's picture
Update app.py
d305080 verified
Raw History Blame Contribute Delete
15.2 kB
import gradio as gr
import diffusers
import torch
from PIL import Image
import numpy as np
import cv2
import os
from rembg import remove
import open3d as o3d
import tempfile
from skimage import filters
import gc
from scipy.ndimage import sobel
import os
import torch
import diffusers
# Handle GPU availability in Hugging Face Spaces with ZeroGPU
if os.environ.get("SPACES_ZERO_GPU") is not None:
import spaces
else:
class spaces:
@staticmethod
def GPU(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
# Check if CUDA is available
if torch.cuda.is_available():
print("CUDA is available")
else:
print("CUDA is not available")
# Set device (GPU or CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Reset CUDA environment
torch.cuda.empty_cache()
try:
print("Loading depth pipeline...")
pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
"prs-eth/marigold-depth-lcm-v1-0",
variant="fp16",
torch_dtype=torch.float16
).to(device)
print("Pipeline loaded successfully.")
# Load the custom VAE
print("Loading custom VAE...")
pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
"madebyollin/taesd",
torch_dtype=torch.float16
).to(device)
print("Custom VAE loaded.")
except Exception as e:
print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
raise
# # Enable XFormers if using GPU
# if device.type == "cuda":
# try:
# from xformers.ops import memory_efficient_attention
# print("xformers is installed and operational!")
# print("Enabling XFormers...")
# pipe.enable_xformers_memory_efficient_attention()
# print("XFormers enabled.")
# except AttributeError:
# print("XFormers is not supported in the installed version of diffusers or model.")
# except ImportError:
# print("XFormers library is not installed. Run `pip install xformers`.")
# except Exception as e:
# print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
# else:
# print("XFormers not enabled as the device is CPU.")
@spaces.GPU(enable_queue=True)
def predict_depth(image: Image.Image):
"""Predict depth from an image and return refined depth map."""
try:
print("Processing input image...")
image = image.convert("RGB")
# Resize image if larger than 2K
if max(image.size) > 2000:
scale_factor = 2000 / max(image.size)
new_size = (int(image.size[0] * scale_factor), int(image.size[1] * scale_factor))
image = image.resize(new_size, Image.LANCZOS)
print(f"Image resized to {new_size}")
# Step 1: Remove background to isolate the main subject
print("Removing background...")
foreground = remove(image)
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
print("Background removal completed.")
# Save foreground for debugging
foreground_debug_path = "debug_foreground.png"
foreground.save(foreground_debug_path)
print(f"Foreground saved at {foreground_debug_path}")
# Depth prediction
print("Predicting depth...")
ensemble_size = 30
num_inference_steps = 5 # Optimized for LCM Scheduler
depth = pipe(
foreground,
ensemble_size=ensemble_size,
num_inference_steps=num_inference_steps,
output_uncertainty=True
)
print("Depth prediction completed.")
# Export depth as a 16-bit PNG
depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
depth_16bit_image = depth_16bit[0]
# Save depth map as 16-bit PNG for debugging
depth_16bit_debug_path = "debug_depth_16bit.png"
depth_16bit_image.save(depth_16bit_debug_path)
print(f"Depth map saved at {depth_16bit_debug_path}")
# Convert depth map to float for filtering
depth_array = np.array(depth_16bit_image, dtype=np.float32)
print(f"Depth map converted to array with shape {depth_array.shape}")
# Validate depth map dimensions
if depth_array.size == 0:
raise ValueError("Depth map is empty or invalid.")
# Step 2: Refine depth map using bilateral and edge-aware filters
print("Refining depth map with bilateral filter...")
depth_bilateral = cv2.bilateralFilter((depth_array / 65535 * 255).astype(np.uint8), d=12, sigmaColor=90, sigmaSpace=90)
depth_bilateral = depth_bilateral.astype(np.float32) / 255 * 65535 # Back to 16-bit scale
print("Bilateral filtering completed.")
# Visualize bilateral filtered depth map
bilateral_debug_path = "debug_bilateral_depth.png"
Image.fromarray((depth_bilateral / 65535 * 255).astype(np.uint8)).save(bilateral_debug_path)
print(f"Bilateral filtered depth map saved at {bilateral_debug_path}")
# Apply Laplacian sharpening
laplacian = cv2.Laplacian(depth_bilateral, cv2.CV_32F)
depth_sharpened = cv2.addWeighted(depth_bilateral, 1.6, laplacian, -0.5, 0)
# Normalize to 16-bit for consistent scaling
depth_normalized = cv2.normalize(depth_sharpened, None, 0, 65535, cv2.NORM_MINMAX, dtype=cv2.CV_16U)
print("Depth sharpening and normalization completed.")
# Resize depth map to match the foreground size
depth_resized = cv2.resize(
depth_normalized, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4
)
print(f"Depth map resized to match foreground: {depth_resized.shape}")
# Apply a foreground mask
print("Applying foreground mask to depth map...")
mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
depth_subject_only = np.where(mask, depth_resized, 0)
print("Foreground mask applied.")
# Visualize depth map with mask applied
masked_debug_path = "debug_masked_depth.png"
Image.fromarray((depth_subject_only / 65535 * 255).astype(np.uint8)).save(masked_debug_path)
print(f"Masked depth map saved at {masked_debug_path}")
# Convert to float depth map for further processing
depth_image_cleaned = depth_subject_only
depth_image = depth_image_cleaned.astype(np.float32) / 255
# Step 3: Smooth depth map with Gaussian filter
print("Smoothing depth map with Gaussian filter...")
depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
print("Gaussian smoothing completed.")
# Step 4: Bilateral filter for detail preservation
depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
print("Final bilateral filtering completed.")
# 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)
print("Depth map resized to final dimensions.")
# Step 6: Create an edge-aware mask (if needed for further processing)
mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
depth_image[~mask] = 0
print("Edge-aware mask applied to depth map.")
# Keep a non-inverted depth for mesh processing
depth_non_inverted = depth_image.copy()
# Invert the depth map for display
depth_image = 1.0 - depth_image
# Generate normalized depth for visualization
depth_display = np.clip(depth_image * 255, 0, 255).astype(np.uint8) # 8-bit display
# Save visualizations
depth_image_path = "depth_image.png"
Image.fromarray(depth_display).save(depth_image_path)
print(f"Depth display saved at {depth_image_path}")
# Return both non-inverted and inverted depths
return depth_non_inverted, depth_image_path
except Exception as e:
print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
return None, None
def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray):
"""Generate a 3D mesh with high-resolution texturing from the depth map."""
global model
try:
# Resize and normalize depth image to align with the foreground dimensions
depth_image_resized = np.array(
Image.fromarray((depth * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
)
print(f"Depth image resized shape: {depth_image_resized.shape}")
# Validate dimensions
if depth_image_resized.shape != foreground.shape[:2]:
raise ValueError("Depth image and foreground dimensions do not match.")
# 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)
print("Depth image normalization completed.")
# Visualize normalized depth map for debugging
Image.fromarray(depth_image_normalized.astype(np.uint8)).save("debug_depth_normalized.png")
# Ensure the foreground is RGB (remove alpha channel if present)
if foreground.shape[2] == 4:
foreground = foreground[:, :, :3]
# Create Open3D RGBD image
depth_o3d = o3d.geometry.Image(np.ascontiguousarray(depth_image_normalized))
image_o3d = o3d.geometry.Image(np.ascontiguousarray(foreground))
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
image_o3d, depth_o3d, convert_rgb_to_intensity=False
)
print("RGBD image creation completed.")
# Camera intrinsics
w, h = foreground.shape[1], foreground.shape[0]
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
print(f"Camera intrinsics: {camera_intrinsic}")
print(f"foreground: {foreground.shape}")
print(f"depth_image_sharpened: {depth_image_sharpened.shape}")
try:
# Generate point cloud
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
print(f"Point cloud generated with {len(pcd.points)} points.")
except Exception as e:
print(f"Error Point cloud generated: {type(e).__name__} - {e}")
# Visualize point cloud for debugging
if len(pcd.points) > 0:
o3d.visualization.draw_geometries([pcd])
else:
raise RuntimeError("Generated point cloud is empty.")
# 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 and orient them
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=100))
pcd.orient_normals_consistent_tangent_plane(k=10)
print("Normals estimation completed.")
try:
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
print("Normals oriented towards camera.")
except Exception as e:
print(f"Error orienting normals: {type(e).__name__} - {e}")
# Generate Poisson mesh
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
pcd, depth=12, width=0, scale=2, linear_fit=True
)
print("Poisson mesh generation completed.")
# Visualize densities for debugging
densities_array = np.asarray(densities)
print(f"Mesh densities range: {densities_array.min()} - {densities_array.max()}")
# Filter mesh by density
density_threshold = np.quantile(densities_array, 0.06)
vertices_to_remove = densities_array < density_threshold
mesh_raw.remove_vertices_by_mask(vertices_to_remove)
print("Mesh filtered by density.")
# Simplify and smooth the mesh
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,
)
mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
print("Mesh simplification and smoothing completed.")
# Crop mesh to bounding box
bbox = pcd.get_axis_aligned_bounding_box()
mesh_crop = mesh.crop(bbox)
print("Mesh cropping to bounding box completed.")
# Compute UV mapping for texture
mesh_crop.compute_vertex_normals()
uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in np.asarray(mesh_crop.vertices)])
mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
print("UV mapping computed.")
# Save high-resolution texture image
texture_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_texture_highres.png"
foreground_pil = Image.fromarray(foreground)
high_res_texture = foreground_pil.resize((2000, 2000), Image.LANCZOS)
high_res_texture.save(texture_path)
print(f"High-resolution texture saved at: {texture_path}")
# Apply texture and export mesh
mesh_crop.textures = [o3d.geometry.Image(np.array(high_res_texture))]
gltf_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_model.gltf"
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
print(f"GLTF model saved at: {gltf_path}")
return gltf_path, texture_path
except Exception as e:
print(f"Error generating 3D mesh: {type(e).__name__} - {e}")
return None, None
def process_image(image_path):
try:
image_raw = Image.open(image_path).convert("RGB")
# Predict and refine depth
depth_non_inverted, depth_16bit_path = predict_depth(image_raw)
if depth_non_inverted is None or depth_16bit_path is None:
raise ValueError("Depth prediction or refinement failed.")
# Generate 3D mesh and retrieve the GLTF path
foreground = np.array(remove(image_raw))
gltf_path, texture_path = get_mesh(image_raw, depth_non_inverted, image_path, foreground)
return depth_16bit_path, gltf_path
except Exception as e:
print(f"Error processing image: {type(e).__name__} - {e}")
return None, None
# Gradio Interface
title = "Depth Estimation & 3D Reconstruction"
description = "Upload an image to generate a depth map and 3D model."
iface = gr.Interface(
fn=process_image,
inputs=gr.Image(type="filepath", label="Input Image"),
outputs=[
gr.File(label="Refined Depth Image (16-bit)"),
gr.File(label="3D Model (GLTF)"),
],
title=title,
description=description,
flagging_mode="manual"
)
iface.launch(debug=True, share=True)