Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
-
import
|
| 2 |
-
from gradio_client import Client
|
| 3 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 4 |
import torch
|
| 5 |
import numpy as np
|
|
@@ -7,16 +6,9 @@ from PIL import Image
|
|
| 7 |
import open3d as o3d
|
| 8 |
from pathlib import Path
|
| 9 |
import os
|
| 10 |
-
import gradio as gr
|
| 11 |
-
from io import BytesIO
|
| 12 |
|
| 13 |
-
|
| 14 |
-
client = Client("not-lain/background-removal")
|
| 15 |
-
|
| 16 |
-
# Initialize DPT depth estimation model
|
| 17 |
-
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large") # Changed from DPTImageProcessor
|
| 18 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 19 |
-
|
| 20 |
def process_image(image_path, depth_map_path=None):
|
| 21 |
image_path = Path(image_path)
|
| 22 |
image_raw = Image.open(image_path)
|
|
@@ -25,34 +17,28 @@ def process_image(image_path, depth_map_path=None):
|
|
| 25 |
Image.Resampling.LANCZOS,
|
| 26 |
)
|
| 27 |
|
| 28 |
-
# Handle background removal via Gradio Client using the file method
|
| 29 |
-
result = client.predict(gradio_client.file(str(image_path)), api_name="/png")
|
| 30 |
-
|
| 31 |
-
# Check the result to determine how to handle it
|
| 32 |
-
if isinstance(result, list) and len(result) > 0:
|
| 33 |
-
if isinstance(result[0], str):
|
| 34 |
-
subject_image = Image.open(result[0]) # Open as file path
|
| 35 |
-
else:
|
| 36 |
-
subject_image = Image.open(BytesIO(result[0])) # Use BytesIO to open image data
|
| 37 |
-
else:
|
| 38 |
-
print("Unexpected result format:", result)
|
| 39 |
-
subject_image = None # Ensure subject_image is None if result is unexpected
|
| 40 |
-
|
| 41 |
-
# Generate or load the depth map
|
| 42 |
if depth_map_path:
|
|
|
|
| 43 |
depth_image_raw = Image.open(depth_map_path)
|
| 44 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 45 |
depth_image = np.array(depth_image)
|
| 46 |
|
| 47 |
-
#
|
|
|
|
| 48 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 49 |
depth_image = (depth_image * 255).astype('uint8')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
else:
|
|
|
|
| 51 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 52 |
with torch.no_grad():
|
| 53 |
outputs = model(**encoding)
|
| 54 |
predicted_depth = outputs.predicted_depth
|
| 55 |
|
|
|
|
| 56 |
prediction = torch.nn.functional.interpolate(
|
| 57 |
predicted_depth.unsqueeze(1),
|
| 58 |
size=image.size[::-1],
|
|
@@ -64,10 +50,14 @@ def process_image(image_path, depth_map_path=None):
|
|
| 64 |
try:
|
| 65 |
gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
|
| 66 |
img = Image.fromarray(depth_image)
|
| 67 |
-
return [img, gltf_path, gltf_path]
|
| 68 |
except Exception as e:
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 73 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
@@ -83,18 +73,27 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 83 |
|
| 84 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 85 |
|
| 86 |
-
|
| 87 |
-
pcd.
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 90 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
|
| 97 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
|
|
|
| 98 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 99 |
voxel_size=voxel_size,
|
| 100 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
@@ -103,14 +102,14 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 103 |
# Apply smoothing
|
| 104 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 105 |
|
| 106 |
-
# Crop the mesh to fit the object
|
| 107 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 108 |
mesh_crop = mesh.crop(bbox)
|
| 109 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 110 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 111 |
return gltf_path
|
| 112 |
|
| 113 |
-
|
|
|
|
| 114 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 115 |
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."
|
| 116 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
@@ -132,5 +131,4 @@ iface = gr.Interface(
|
|
| 132 |
allow_flagging="never",
|
| 133 |
cache_examples=False,
|
| 134 |
)
|
| 135 |
-
|
| 136 |
-
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
| 2 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
|
|
|
| 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 |
def process_image(image_path, depth_map_path=None):
|
| 13 |
image_path = Path(image_path)
|
| 14 |
image_raw = Image.open(image_path)
|
|
|
|
| 17 |
Image.Resampling.LANCZOS,
|
| 18 |
)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
if depth_map_path:
|
| 21 |
+
# Load and resize the user-provided depth map to match the RGB image size
|
| 22 |
depth_image_raw = Image.open(depth_map_path)
|
| 23 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 24 |
depth_image = np.array(depth_image)
|
| 25 |
|
| 26 |
+
# Adjust the depth map based on the Depth-Anything-V2 format
|
| 27 |
+
# Normalize depth if needed (assuming values are not scaled to 0-255)
|
| 28 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 29 |
depth_image = (depth_image * 255).astype('uint8')
|
| 30 |
+
|
| 31 |
+
# Optionally invert the depth map if it's inverse (like MiDaS)
|
| 32 |
+
# depth_image = np.max(depth_image) - depth_image
|
| 33 |
+
|
| 34 |
else:
|
| 35 |
+
# Automatically generate the depth map using the model (if no depth map provided)
|
| 36 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 37 |
with torch.no_grad():
|
| 38 |
outputs = model(**encoding)
|
| 39 |
predicted_depth = outputs.predicted_depth
|
| 40 |
|
| 41 |
+
# Interpolate to original size
|
| 42 |
prediction = torch.nn.functional.interpolate(
|
| 43 |
predicted_depth.unsqueeze(1),
|
| 44 |
size=image.size[::-1],
|
|
|
|
| 50 |
try:
|
| 51 |
gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
|
| 52 |
img = Image.fromarray(depth_image)
|
| 53 |
+
return [img, gltf_path, gltf_path]
|
| 54 |
except Exception as e:
|
| 55 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
|
| 56 |
+
img = Image.fromarray(depth_image)
|
| 57 |
+
return [img, gltf_path, gltf_path]
|
| 58 |
+
except:
|
| 59 |
+
print("Error reconstructing 3D model")
|
| 60 |
+
raise Exception("Error reconstructing 3D model")
|
| 61 |
|
| 62 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 63 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
|
|
| 73 |
|
| 74 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 75 |
|
| 76 |
+
print("normals")
|
| 77 |
+
pcd.normals = o3d.utility.Vector3dVector(
|
| 78 |
+
np.zeros((1, 3))
|
| 79 |
+
) # invalidate existing normals
|
| 80 |
+
pcd.estimate_normals(
|
| 81 |
+
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 82 |
+
)
|
| 83 |
+
pcd.orient_normals_towards_camera_location(
|
| 84 |
+
camera_location=np.array([0.0, 0.0, 1000.0])
|
| 85 |
+
)
|
| 86 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 87 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 88 |
|
| 89 |
+
print("run Poisson surface reconstruction")
|
| 90 |
+
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
|
| 91 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 92 |
+
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 93 |
+
)
|
| 94 |
|
| 95 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 96 |
+
print(f"voxel_size = {voxel_size:e}")
|
| 97 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 98 |
voxel_size=voxel_size,
|
| 99 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
|
|
| 102 |
# Apply smoothing
|
| 103 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 104 |
|
|
|
|
| 105 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 106 |
mesh_crop = mesh.crop(bbox)
|
| 107 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 108 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 109 |
return gltf_path
|
| 110 |
|
| 111 |
+
|
| 112 |
+
|
| 113 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 114 |
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."
|
| 115 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
|
|
| 131 |
allow_flagging="never",
|
| 132 |
cache_examples=False,
|
| 133 |
)
|
| 134 |
+
iface.launch(debug=True, show_api=True, share=True)
|
|
|