Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,10 @@ 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 |
|
|
@@ -18,34 +21,32 @@ def process_image(image_path, depth_map_path=None):
|
|
| 18 |
Image.Resampling.LANCZOS,
|
| 19 |
)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 29 |
-
depth_image = np.array(depth_image)
|
| 30 |
-
elif depth_map_path.suffix == '.npy':
|
| 31 |
-
# Load depth map from .npy file and resize
|
| 32 |
-
depth_image = np.load(depth_map_path)
|
| 33 |
-
depth_image = np.interp(depth_image, (depth_image.min(), depth_image.max()), (0, 255))
|
| 34 |
-
depth_image = depth_image.astype('uint8')
|
| 35 |
-
depth_image = np.array(Image.fromarray(depth_image).resize(image.size, Image.Resampling.NEAREST))
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 39 |
depth_image = (depth_image * 255).astype('uint8')
|
| 40 |
-
|
| 41 |
else:
|
| 42 |
-
#
|
| 43 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 44 |
with torch.no_grad():
|
| 45 |
outputs = model(**encoding)
|
| 46 |
predicted_depth = outputs.predicted_depth
|
| 47 |
-
|
| 48 |
-
# Interpolate to the original image size
|
| 49 |
prediction = torch.nn.functional.interpolate(
|
| 50 |
predicted_depth.unsqueeze(1),
|
| 51 |
size=image.size[::-1],
|
|
@@ -54,16 +55,13 @@ def process_image(image_path, depth_map_path=None):
|
|
| 54 |
).squeeze()
|
| 55 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 56 |
|
|
|
|
| 57 |
try:
|
| 58 |
-
gltf_path = create_3d_obj(np.array(
|
| 59 |
img = Image.fromarray(depth_image)
|
| 60 |
return [img, gltf_path, gltf_path]
|
| 61 |
except Exception as e:
|
| 62 |
-
|
| 63 |
-
img = Image.fromarray(depth_image)
|
| 64 |
-
return [img, gltf_path, gltf_path]
|
| 65 |
-
except:
|
| 66 |
-
print("Error reconstructing 3D model")
|
| 67 |
raise Exception("Error reconstructing 3D model")
|
| 68 |
|
| 69 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
@@ -79,50 +77,38 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 79 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 80 |
|
| 81 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
pcd.
|
| 85 |
-
np.zeros((1, 3))
|
| 86 |
-
) # invalidate existing normals
|
| 87 |
-
pcd.estimate_normals(
|
| 88 |
-
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 89 |
-
)
|
| 90 |
-
pcd.orient_normals_towards_camera_location(
|
| 91 |
-
camera_location=np.array([0.0, 0.0, 1000.0])
|
| 92 |
-
)
|
| 93 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 94 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 103 |
-
print(f"voxel_size = {voxel_size:e}")
|
| 104 |
-
mesh = mesh_raw.simplify_vertex_clustering(
|
| 105 |
-
voxel_size=voxel_size,
|
| 106 |
-
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 107 |
)
|
| 108 |
|
| 109 |
-
|
|
|
|
| 110 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 111 |
|
|
|
|
| 112 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 113 |
mesh_crop = mesh.crop(bbox)
|
| 114 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 115 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 116 |
return gltf_path
|
| 117 |
|
|
|
|
| 118 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 119 |
-
description = "This demo allows users to provide an RGB image and optionally a depth map
|
|
|
|
| 120 |
|
| 121 |
iface = gr.Interface(
|
| 122 |
fn=process_image,
|
| 123 |
inputs=[
|
| 124 |
gr.Image(type="filepath", label="Input Image"),
|
| 125 |
-
gr.
|
| 126 |
],
|
| 127 |
outputs=[
|
| 128 |
gr.Image(label="Predicted Depth", type="pil"),
|
|
@@ -131,6 +117,7 @@ iface = gr.Interface(
|
|
| 131 |
],
|
| 132 |
title=title,
|
| 133 |
description=description,
|
|
|
|
| 134 |
allow_flagging="never",
|
| 135 |
cache_examples=False,
|
| 136 |
)
|
|
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
+
import cv2 # For inpainting
|
| 10 |
+
from rembg import remove # For background removal
|
| 11 |
|
| 12 |
+
# Initialize depth estimation model
|
| 13 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 14 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 15 |
|
|
|
|
| 21 |
Image.Resampling.LANCZOS,
|
| 22 |
)
|
| 23 |
|
| 24 |
+
# Step 1: Separate the main subject
|
| 25 |
+
image_np = np.array(image)
|
| 26 |
+
subject = remove(image_np) # Removes background
|
| 27 |
+
|
| 28 |
+
# Step 2: Inpaint the background
|
| 29 |
+
mask = cv2.inRange(subject, (0, 0, 0), (0, 0, 0)) # Binary mask
|
| 30 |
+
background_inpainted = cv2.inpaint(image_np, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# Convert back to PIL format
|
| 33 |
+
subject_image = Image.fromarray(subject)
|
| 34 |
+
inpainted_bg_image = Image.fromarray(background_inpainted)
|
| 35 |
+
|
| 36 |
+
# Step 3: Generate or use existing depth map
|
| 37 |
+
if depth_map_path:
|
| 38 |
+
# Resize user-provided depth map to match RGB size
|
| 39 |
+
depth_image_raw = Image.open(depth_map_path)
|
| 40 |
+
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 41 |
+
depth_image = np.array(depth_image)
|
| 42 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 43 |
depth_image = (depth_image * 255).astype('uint8')
|
|
|
|
| 44 |
else:
|
| 45 |
+
# Generate depth map using the model
|
| 46 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 47 |
with torch.no_grad():
|
| 48 |
outputs = model(**encoding)
|
| 49 |
predicted_depth = outputs.predicted_depth
|
|
|
|
|
|
|
| 50 |
prediction = torch.nn.functional.interpolate(
|
| 51 |
predicted_depth.unsqueeze(1),
|
| 52 |
size=image.size[::-1],
|
|
|
|
| 55 |
).squeeze()
|
| 56 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 57 |
|
| 58 |
+
# Step 4: Apply depth to main subject only
|
| 59 |
try:
|
| 60 |
+
gltf_path = create_3d_obj(np.array(subject_image), depth_image, image_path)
|
| 61 |
img = Image.fromarray(depth_image)
|
| 62 |
return [img, gltf_path, gltf_path]
|
| 63 |
except Exception as e:
|
| 64 |
+
print("Error reconstructing 3D model:", e)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
raise Exception("Error reconstructing 3D model")
|
| 66 |
|
| 67 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
|
|
| 77 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 78 |
|
| 79 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 80 |
+
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Invalidate existing normals
|
| 81 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
|
| 82 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 84 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 85 |
|
| 86 |
+
# Poisson surface reconstruction
|
| 87 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 88 |
+
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
)
|
| 90 |
|
| 91 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 92 |
+
mesh = mesh_raw.simplify_vertex_clustering(voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average)
|
| 93 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 94 |
|
| 95 |
+
# Crop mesh to a flat backside
|
| 96 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 97 |
mesh_crop = mesh.crop(bbox)
|
| 98 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 99 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 100 |
return gltf_path
|
| 101 |
|
| 102 |
+
# Gradio interface setup
|
| 103 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 104 |
+
description = "This demo allows users to provide an RGB image and optionally a depth map to create a 3D object. If no depth map is provided, the DPT model will generate it."
|
| 105 |
+
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 106 |
|
| 107 |
iface = gr.Interface(
|
| 108 |
fn=process_image,
|
| 109 |
inputs=[
|
| 110 |
gr.Image(type="filepath", label="Input Image"),
|
| 111 |
+
gr.Image(type="filepath", label="Input Depth Map (optional)"),
|
| 112 |
],
|
| 113 |
outputs=[
|
| 114 |
gr.Image(label="Predicted Depth", type="pil"),
|
|
|
|
| 117 |
],
|
| 118 |
title=title,
|
| 119 |
description=description,
|
| 120 |
+
examples=examples,
|
| 121 |
allow_flagging="never",
|
| 122 |
cache_examples=False,
|
| 123 |
)
|