Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
from skimage import img_as_ubyte
|
|
|
|
| 2 |
from skimage.segmentation import clear_border
|
| 3 |
import gradio as gr
|
| 4 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
|
@@ -10,8 +11,6 @@ from pathlib import Path
|
|
| 10 |
import os
|
| 11 |
import cv2
|
| 12 |
from rembg import remove
|
| 13 |
-
import logging
|
| 14 |
-
|
| 15 |
|
| 16 |
# Initialize model and feature extractor for depth estimation
|
| 17 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
|
@@ -25,7 +24,7 @@ def process_image(image_path, depth_map_path=None):
|
|
| 25 |
Image.Resampling.LANCZOS,
|
| 26 |
)
|
| 27 |
|
| 28 |
-
# Remove background
|
| 29 |
foreground = remove(image_raw)
|
| 30 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 31 |
|
|
@@ -33,16 +32,19 @@ def process_image(image_path, depth_map_path=None):
|
|
| 33 |
if depth_map_path:
|
| 34 |
if depth_map_path.endswith('.npy'):
|
| 35 |
depth_image = np.load(depth_map_path)
|
|
|
|
| 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 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 43 |
depth_image = np.clip(depth_image, 0, 1)
|
| 44 |
depth_image = img_as_ubyte(depth_image)
|
| 45 |
else:
|
|
|
|
| 46 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 47 |
with torch.no_grad():
|
| 48 |
outputs = model(**encoding)
|
|
@@ -55,100 +57,93 @@ def process_image(image_path, depth_map_path=None):
|
|
| 55 |
align_corners=False,
|
| 56 |
).squeeze()
|
| 57 |
depth_image = prediction.cpu().numpy()
|
| 58 |
-
|
|
|
|
| 59 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 60 |
depth_image = np.clip(depth_image, 0, 1)
|
| 61 |
depth_image = img_as_ubyte(depth_image)
|
| 62 |
|
| 63 |
-
#
|
| 64 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
#
|
| 72 |
# background = remove(image_raw, only_mask=True)
|
| 73 |
# background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 74 |
# background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 75 |
|
| 76 |
try:
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
img = Image.fromarray(sharp_depth_image)
|
| 80 |
return [img, gltf_path, gltf_path]
|
| 81 |
except Exception as e:
|
| 82 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 83 |
-
gltf_path = create_3d_obj(np.array(foreground),
|
| 84 |
-
img = Image.fromarray(
|
| 85 |
return [img, gltf_path, gltf_path]
|
| 86 |
|
| 87 |
-
def create_3d_obj(foreground, depth_image, background, image_path, depth=10, min_depth=5):
|
| 88 |
-
if depth < min_depth:
|
| 89 |
-
raise RuntimeError("Reached minimum depth without sufficient points for the point cloud.")
|
| 90 |
-
|
| 91 |
-
try:
|
| 92 |
-
# Resize and normalize depth image
|
| 93 |
-
depth_image_resized = np.array(
|
| 94 |
-
Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 95 |
-
)
|
| 96 |
-
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 97 |
-
depth_image_resized.max() - depth_image_resized.min()
|
| 98 |
-
) * 255
|
| 99 |
-
depth_image_normalized = depth_image_normalized.astype(np.uint8)
|
| 100 |
-
|
| 101 |
-
# Convert to Open3D format
|
| 102 |
-
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
| 103 |
-
image_o3d = o3d.geometry.Image(foreground)
|
| 104 |
-
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 105 |
-
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 106 |
-
)
|
| 107 |
-
w, h = foreground.shape[1], foreground.shape[0]
|
| 108 |
-
|
| 109 |
-
# Set up camera intrinsic
|
| 110 |
-
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 111 |
-
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 112 |
-
|
| 113 |
-
# Create point cloud
|
| 114 |
-
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
if not pcd.has_normals():
|
| 121 |
-
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 122 |
-
|
| 123 |
-
if pcd.has_normals():
|
| 124 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 125 |
-
else:
|
| 126 |
-
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 127 |
-
|
| 128 |
-
# Mesh reconstruction
|
| 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 |
-
# Simplify and crop the mesh
|
| 134 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 135 |
-
mesh = mesh_raw.simplify_vertex_clustering(
|
| 136 |
-
voxel_size=voxel_size,
|
| 137 |
-
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 138 |
-
)
|
| 139 |
-
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 140 |
-
bbox = pcd.get_axis_aligned_bounding_box()
|
| 141 |
-
mesh_crop = mesh.crop(bbox)
|
| 142 |
-
|
| 143 |
-
# Save to GLTF
|
| 144 |
-
gltf_path = f"./{image_path.stem}.gltf"
|
| 145 |
-
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 146 |
-
return gltf_path
|
| 147 |
-
|
| 148 |
-
except RuntimeError as e:
|
| 149 |
-
print(f"Error: {str(e)}.")
|
| 150 |
-
return None
|
| 151 |
-
|
| 152 |
# Gradio Interface
|
| 153 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 154 |
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."
|
|
@@ -157,12 +152,19 @@ examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
| 157 |
|
| 158 |
iface = gr.Interface(
|
| 159 |
fn=process_image,
|
| 160 |
-
inputs=[
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
title=title,
|
| 163 |
description=description,
|
| 164 |
examples=examples,
|
| 165 |
allow_flagging="never",
|
| 166 |
cache_examples=False,
|
| 167 |
)
|
| 168 |
-
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 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
|
|
|
|
| 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")
|
|
|
|
| 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 |
|
|
|
|
| 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)
|
|
|
|
| 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 |
+
# Commenting out the background inpainting section
|
| 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, None, 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, None, 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 |
+
# Flatten the back of the model from the zero point
|
| 134 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 135 |
+
mesh = mesh_raw.simplify_vertex_clustering(
|
| 136 |
+
voxel_size=voxel_size,
|
| 137 |
+
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 138 |
+
)
|
| 139 |
+
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 140 |
+
bbox = pcd.get_axis_aligned_bounding_box()
|
| 141 |
+
mesh_crop = mesh.crop(bbox)
|
| 142 |
+
|
| 143 |
+
gltf_path = f"./{image_path.stem}.gltf"
|
| 144 |
+
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 145 |
+
return gltf_path
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
# Gradio Interface
|
| 148 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 149 |
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."
|
|
|
|
| 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,
|
| 166 |
examples=examples,
|
| 167 |
allow_flagging="never",
|
| 168 |
cache_examples=False,
|
| 169 |
)
|
| 170 |
+
iface.launch(debug=True, show_api=True, share=True)
|