Update app.py
Browse files
app.py
CHANGED
|
@@ -3,20 +3,14 @@ from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
-
from rembg import remove # Add this to use rembg for background separation
|
| 7 |
import open3d as o3d
|
| 8 |
from pathlib import Path
|
| 9 |
import os
|
| 10 |
|
|
|
|
| 11 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 12 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 13 |
-
from rembg import remove # Add this to use rembg for background separation
|
| 14 |
-
from PIL import Image
|
| 15 |
-
from pathlib import Path
|
| 16 |
-
import numpy as np
|
| 17 |
-
import torch
|
| 18 |
|
| 19 |
-
# Update process_image function
|
| 20 |
def process_image(image_path, depth_map_path=None):
|
| 21 |
image_path = Path(image_path)
|
| 22 |
image_raw = Image.open(image_path)
|
|
@@ -25,24 +19,23 @@ def process_image(image_path, depth_map_path=None):
|
|
| 25 |
Image.Resampling.LANCZOS,
|
| 26 |
)
|
| 27 |
|
|
|
|
| 28 |
if depth_map_path:
|
| 29 |
-
# Load and resize the user-provided depth map to match the RGB image size
|
| 30 |
depth_image_raw = Image.open(depth_map_path)
|
| 31 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 32 |
depth_image = np.array(depth_image)
|
| 33 |
|
| 34 |
-
#
|
| 35 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 36 |
depth_image = (depth_image * 255).astype('uint8')
|
| 37 |
|
| 38 |
else:
|
| 39 |
-
#
|
| 40 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 41 |
with torch.no_grad():
|
| 42 |
outputs = model(**encoding)
|
| 43 |
predicted_depth = outputs.predicted_depth
|
| 44 |
|
| 45 |
-
# Interpolate to original size
|
| 46 |
prediction = torch.nn.functional.interpolate(
|
| 47 |
predicted_depth.unsqueeze(1),
|
| 48 |
size=image.size[::-1],
|
|
@@ -51,30 +44,18 @@ def process_image(image_path, depth_map_path=None):
|
|
| 51 |
).squeeze()
|
| 52 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 53 |
|
| 54 |
-
# Assuming subject_depth is generated from the input depth image
|
| 55 |
-
subject_depth = depth_image # Example, replace with actual subject depth calculation
|
| 56 |
-
|
| 57 |
-
# Here, you should retrieve or create your background depth image
|
| 58 |
-
depth_image_background = np.zeros_like(subject_depth) # Replace this with actual background depth processing
|
| 59 |
-
|
| 60 |
-
# Resize background depth to match subject depth
|
| 61 |
-
depth_image_background = np.array(Image.fromarray(depth_image_background).resize(subject_depth.shape[::-1], Image.Resampling.NEAREST))
|
| 62 |
-
|
| 63 |
-
# Combine depth images
|
| 64 |
-
depth_image_combined = np.where(subject_depth > 0, subject_depth, depth_image_background)
|
| 65 |
-
|
| 66 |
-
# Continue with the rest of your process
|
| 67 |
try:
|
| 68 |
-
gltf_path = create_3d_obj(np.array(image),
|
| 69 |
-
img = Image.fromarray(
|
| 70 |
return [img, gltf_path, gltf_path]
|
| 71 |
except Exception as e:
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
return [img, gltf_path, gltf_path]
|
| 75 |
-
except
|
| 76 |
-
print(
|
| 77 |
-
raise
|
| 78 |
|
| 79 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 80 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
@@ -82,53 +63,44 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 82 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 83 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 84 |
)
|
| 85 |
-
w =
|
| 86 |
-
h = int(depth_image.shape[0])
|
| 87 |
|
|
|
|
| 88 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 89 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 90 |
|
|
|
|
| 91 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
pcd.
|
| 95 |
-
np.zeros((1, 3))
|
| 96 |
-
) # invalidate existing normals
|
| 97 |
-
pcd.estimate_normals(
|
| 98 |
-
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 99 |
-
)
|
| 100 |
-
pcd.orient_normals_towards_camera_location(
|
| 101 |
-
camera_location=np.array([0.0, 0.0, 1000.0])
|
| 102 |
-
)
|
| 103 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 104 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
)
|
| 111 |
|
|
|
|
| 112 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 113 |
-
print(f"voxel_size = {voxel_size:e}")
|
| 114 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 115 |
voxel_size=voxel_size,
|
| 116 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
# Apply smoothing
|
| 120 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 121 |
-
|
| 122 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 123 |
mesh_crop = mesh.crop(bbox)
|
|
|
|
|
|
|
| 124 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 125 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 126 |
return gltf_path
|
| 127 |
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
-
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 131 |
-
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."
|
| 132 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 133 |
|
| 134 |
iface = gr.Interface(
|
|
@@ -148,4 +120,4 @@ iface = gr.Interface(
|
|
| 148 |
allow_flagging="never",
|
| 149 |
cache_examples=False,
|
| 150 |
)
|
| 151 |
-
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
|
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
|
| 10 |
+
# Initialize model and feature extractor for depth estimation
|
| 11 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 12 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
| 14 |
def process_image(image_path, depth_map_path=None):
|
| 15 |
image_path = Path(image_path)
|
| 16 |
image_raw = Image.open(image_path)
|
|
|
|
| 19 |
Image.Resampling.LANCZOS,
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# Check if user-provided depth map is available
|
| 23 |
if depth_map_path:
|
|
|
|
| 24 |
depth_image_raw = Image.open(depth_map_path)
|
| 25 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 26 |
depth_image = np.array(depth_image)
|
| 27 |
|
| 28 |
+
# Normalize depth image to match expected format
|
| 29 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 30 |
depth_image = (depth_image * 255).astype('uint8')
|
| 31 |
|
| 32 |
else:
|
| 33 |
+
# Generate depth map using DPT model
|
| 34 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 35 |
with torch.no_grad():
|
| 36 |
outputs = model(**encoding)
|
| 37 |
predicted_depth = outputs.predicted_depth
|
| 38 |
|
|
|
|
| 39 |
prediction = torch.nn.functional.interpolate(
|
| 40 |
predicted_depth.unsqueeze(1),
|
| 41 |
size=image.size[::-1],
|
|
|
|
| 44 |
).squeeze()
|
| 45 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
|
| 49 |
+
img = Image.fromarray(depth_image)
|
| 50 |
return [img, gltf_path, gltf_path]
|
| 51 |
except Exception as e:
|
| 52 |
+
print("Error with default depth. Retrying with a shallower depth.")
|
| 53 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
|
| 54 |
+
img = Image.fromarray(depth_image)
|
| 55 |
return [img, gltf_path, gltf_path]
|
| 56 |
+
except:
|
| 57 |
+
print("Error reconstructing 3D model")
|
| 58 |
+
raise Exception("Error reconstructing 3D model")
|
| 59 |
|
| 60 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 61 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
|
|
| 63 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 64 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 65 |
)
|
| 66 |
+
w, h = depth_image.shape[1], depth_image.shape[0]
|
|
|
|
| 67 |
|
| 68 |
+
# Camera intrinsic setup for 3D point cloud
|
| 69 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 70 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 71 |
|
| 72 |
+
# Point Cloud and Normals
|
| 73 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 74 |
+
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 75 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
|
| 76 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 78 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 79 |
|
| 80 |
+
# Poisson Surface Reconstruction
|
| 81 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 82 |
+
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 83 |
+
)
|
|
|
|
| 84 |
|
| 85 |
+
# Mesh simplification and smoothing
|
| 86 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
|
|
|
| 87 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 88 |
voxel_size=voxel_size,
|
| 89 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 90 |
)
|
|
|
|
|
|
|
| 91 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
|
|
|
| 92 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 93 |
mesh_crop = mesh.crop(bbox)
|
| 94 |
+
|
| 95 |
+
# Save GLTF
|
| 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 |
+
# Gradio Interface
|
| 101 |
+
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 102 |
+
description = "Upload an image and optionally a depth map to generate a 3D model. If no depth map is provided, the DPT model will generate it."
|
| 103 |
|
|
|
|
|
|
|
|
|
|
| 104 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 105 |
|
| 106 |
iface = gr.Interface(
|
|
|
|
| 120 |
allow_flagging="never",
|
| 121 |
cache_examples=False,
|
| 122 |
)
|
| 123 |
+
iface.launch(debug=True, show_api=True, share=True)
|