Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 3 |
import torch
|
|
@@ -6,109 +9,157 @@ from PIL import Image
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
|
|
|
|
|
|
| 9 |
|
|
|
|
| 10 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 11 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 12 |
|
| 13 |
-
|
| 14 |
-
def process_image(image_path):
|
| 15 |
image_path = Path(image_path)
|
| 16 |
-
image_raw = Image.open(image_path)
|
| 17 |
image = image_raw.resize(
|
| 18 |
-
(
|
| 19 |
Image.Resampling.LANCZOS,
|
| 20 |
)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
try:
|
| 40 |
-
gltf_path = create_3d_obj(np.array(
|
| 41 |
-
img = Image.fromarray(
|
| 42 |
return [img, gltf_path, gltf_path]
|
| 43 |
except Exception as e:
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
return [img, gltf_path, gltf_path]
|
| 47 |
-
except:
|
| 48 |
-
print("Error reconstructing 3D model")
|
| 49 |
-
raise Exception("Error reconstructing 3D model")
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
image_o3d = o3d.geometry.Image(rgb_image)
|
| 55 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 56 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 57 |
)
|
| 58 |
-
w =
|
| 59 |
-
h = int(depth_image.shape[0])
|
| 60 |
|
| 61 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 62 |
-
camera_intrinsic.set_intrinsics(w, h,
|
| 63 |
|
| 64 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
np.zeros((1, 3))
|
| 69 |
-
) # invalidate existing normals
|
| 70 |
-
pcd.estimate_normals(
|
| 71 |
-
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=30)
|
| 72 |
-
)
|
| 73 |
-
pcd.orient_normals_towards_camera_location(
|
| 74 |
-
camera_location=np.array([0.0, 0.0, 1000.0])
|
| 75 |
-
)
|
| 76 |
-
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 77 |
-
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
)
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 88 |
voxel_size=voxel_size,
|
| 89 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 90 |
)
|
| 91 |
-
|
| 92 |
-
# vertices_to_remove = densities < np.quantile(densities, 0.001)
|
| 93 |
-
# mesh.remove_vertices_by_mask(vertices_to_remove)
|
| 94 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 95 |
mesh_crop = mesh.crop(bbox)
|
|
|
|
| 96 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 97 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 98 |
return gltf_path
|
| 99 |
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
title = "Demo: zero-shot depth estimation with DPT + 3D Point Cloud"
|
| 102 |
-
description = "This demo is a variation from the original <a href='https://huggingface.co/spaces/nielsr/dpt-depth-estimation' target='_blank'>DPT Demo</a>. It uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object."
|
| 103 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 104 |
|
|
|
|
| 105 |
iface = gr.Interface(
|
| 106 |
fn=process_image,
|
| 107 |
-
inputs=[
|
|
|
|
|
|
|
|
|
|
| 108 |
outputs=[
|
| 109 |
-
gr.Image(label="
|
| 110 |
-
gr.Model3D(label="
|
| 111 |
-
gr.File(label="
|
| 112 |
],
|
| 113 |
title=title,
|
| 114 |
description=description,
|
|
@@ -116,4 +167,4 @@ iface = gr.Interface(
|
|
| 116 |
allow_flagging="never",
|
| 117 |
cache_examples=False,
|
| 118 |
)
|
| 119 |
-
iface.launch(debug=True, show_api=
|
|
|
|
| 1 |
+
from skimage import img_as_ubyte
|
| 2 |
+
from skimage.filters import gaussian
|
| 3 |
+
from skimage.segmentation import clear_border
|
| 4 |
import gradio as gr
|
| 5 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 6 |
import torch
|
|
|
|
| 9 |
import open3d as o3d
|
| 10 |
from pathlib import Path
|
| 11 |
import os
|
| 12 |
+
import cv2
|
| 13 |
+
from rembg import remove
|
| 14 |
|
| 15 |
+
# Initialize model and feature extractor for depth estimation
|
| 16 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 17 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 18 |
|
| 19 |
+
def process_image(image_path, depth_map_path=None):
|
|
|
|
| 20 |
image_path = Path(image_path)
|
| 21 |
+
image_raw = Image.open(image_path).convert("RGB")
|
| 22 |
image = image_raw.resize(
|
| 23 |
+
(2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
|
| 24 |
Image.Resampling.LANCZOS,
|
| 25 |
)
|
| 26 |
|
| 27 |
+
# Remove background using rembg
|
| 28 |
+
foreground = remove(image_raw)
|
| 29 |
+
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 30 |
+
|
| 31 |
+
# Check if user-provided depth map is available
|
| 32 |
+
if depth_map_path:
|
| 33 |
+
if depth_map_path.endswith('.npy'):
|
| 34 |
+
depth_image = np.load(depth_map_path)
|
| 35 |
+
# Invert depth only for npy files
|
| 36 |
+
depth_image = 1 - depth_image
|
| 37 |
+
else:
|
| 38 |
+
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 39 |
+
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 40 |
+
depth_image = np.array(depth_image)
|
| 41 |
+
|
| 42 |
+
# Normalize depth image to [0, 1] range
|
| 43 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 44 |
+
depth_image = np.clip(depth_image, 0, 1)
|
| 45 |
+
depth_image = img_as_ubyte(depth_image)
|
| 46 |
+
else:
|
| 47 |
+
# Generate depth map using DPT model
|
| 48 |
+
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 49 |
+
with torch.no_grad():
|
| 50 |
+
outputs = model(**encoding)
|
| 51 |
+
predicted_depth = outputs.predicted_depth
|
| 52 |
+
|
| 53 |
+
prediction = torch.nn.functional.interpolate(
|
| 54 |
+
predicted_depth.unsqueeze(1),
|
| 55 |
+
size=image.size[::-1],
|
| 56 |
+
mode="bicubic",
|
| 57 |
+
align_corners=False,
|
| 58 |
+
).squeeze()
|
| 59 |
+
depth_image = prediction.cpu().numpy()
|
| 60 |
+
|
| 61 |
+
# Normalize depth image to [0, 1] range before converting
|
| 62 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 63 |
+
depth_image = np.clip(depth_image, 0, 1)
|
| 64 |
+
depth_image = img_as_ubyte(depth_image)
|
| 65 |
+
|
| 66 |
+
# Resize and apply lighter Gaussian smoothing for smoother transitions
|
| 67 |
+
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 68 |
+
mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
|
| 69 |
+
|
| 70 |
+
# Ensure matching size and single channel for blending
|
| 71 |
+
if len(depth_image.shape) == 3:
|
| 72 |
+
depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
|
| 73 |
+
if len(mask_blurred.shape) == 3:
|
| 74 |
+
mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
|
| 75 |
+
|
| 76 |
+
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
| 77 |
+
|
| 78 |
+
# Blend depth_image with mask_blurred_resized for smoother transition
|
| 79 |
+
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
|
| 80 |
+
|
| 81 |
+
# Inpaint background where main subject was removed
|
| 82 |
+
background = remove(image_raw, only_mask=True)
|
| 83 |
+
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 84 |
+
background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 85 |
+
|
| 86 |
try:
|
| 87 |
+
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path)
|
| 88 |
+
img = Image.fromarray(blended_depth_image)
|
| 89 |
return [img, gltf_path, gltf_path]
|
| 90 |
except Exception as e:
|
| 91 |
+
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 92 |
+
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path, depth=9)
|
| 93 |
+
img = Image.fromarray(blended_depth_image)
|
| 94 |
return [img, gltf_path, gltf_path]
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
|
| 97 |
+
def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
| 98 |
+
depth_image_resized = np.array(
|
| 99 |
+
Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 100 |
+
)
|
| 101 |
+
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 102 |
+
depth_image_resized.max() - depth_image_resized.min()
|
| 103 |
+
) * 255
|
| 104 |
+
depth_image_normalized = depth_image_normalized.astype(np.uint8)
|
| 105 |
|
| 106 |
+
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
| 107 |
+
image_o3d = o3d.geometry.Image(foreground)
|
|
|
|
| 108 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 109 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 110 |
)
|
| 111 |
+
w, h = foreground.shape[1], foreground.shape[0]
|
|
|
|
| 112 |
|
| 113 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 114 |
+
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 115 |
|
| 116 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 117 |
|
| 118 |
+
if len(pcd.points) < 100:
|
| 119 |
+
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
if not pcd.has_normals():
|
| 122 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 123 |
+
|
| 124 |
+
if pcd.has_normals():
|
| 125 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 126 |
+
else:
|
| 127 |
+
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 128 |
|
| 129 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 130 |
+
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 134 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 135 |
voxel_size=voxel_size,
|
| 136 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 137 |
)
|
| 138 |
+
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
|
|
|
|
|
|
| 139 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 140 |
mesh_crop = mesh.crop(bbox)
|
| 141 |
+
|
| 142 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 143 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 144 |
return gltf_path
|
| 145 |
|
| 146 |
+
# Gradio Interface
|
| 147 |
+
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 148 |
+
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."
|
| 149 |
|
|
|
|
|
|
|
| 150 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 151 |
|
| 152 |
+
|
| 153 |
iface = gr.Interface(
|
| 154 |
fn=process_image,
|
| 155 |
+
inputs=[
|
| 156 |
+
gr.Image(type="filepath", label="Input Image"),
|
| 157 |
+
gr.File(type="filepath", label="Input Depth Map (optional)"),
|
| 158 |
+
],
|
| 159 |
outputs=[
|
| 160 |
+
gr.Image(label="Predicted Depth", type="pil"),
|
| 161 |
+
gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
|
| 162 |
+
gr.File(label="3D gLTF File"),
|
| 163 |
],
|
| 164 |
title=title,
|
| 165 |
description=description,
|
|
|
|
| 167 |
allow_flagging="never",
|
| 168 |
cache_examples=False,
|
| 169 |
)
|
| 170 |
+
iface.launch(debug=True, show_api=True, share=True)
|