Update app.py
Browse files
app.py
CHANGED
|
@@ -6,9 +6,15 @@ 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 |
def process_image(image_path, depth_map_path=None):
|
| 13 |
image_path = Path(image_path)
|
| 14 |
image_raw = Image.open(image_path)
|
|
@@ -17,28 +23,34 @@ def process_image(image_path, depth_map_path=None):
|
|
| 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 |
-
#
|
| 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
|
| 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
|
| 42 |
prediction = torch.nn.functional.interpolate(
|
| 43 |
predicted_depth.unsqueeze(1),
|
| 44 |
size=image.size[::-1],
|
|
@@ -47,16 +59,23 @@ def process_image(image_path, depth_map_path=None):
|
|
| 47 |
).squeeze()
|
| 48 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
-
gltf_path = create_3d_obj(np.array(image),
|
| 52 |
-
img = Image.fromarray(
|
| 53 |
return [img, gltf_path, gltf_path]
|
| 54 |
except Exception as e:
|
| 55 |
-
|
| 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):
|
|
@@ -73,10 +92,10 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 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 |
-
) #
|
| 80 |
pcd.estimate_normals(
|
| 81 |
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 82 |
)
|
|
@@ -86,14 +105,14 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 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("
|
| 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"
|
| 97 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 98 |
voxel_size=voxel_size,
|
| 99 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
@@ -108,8 +127,7 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 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,4 +149,5 @@ iface = gr.Interface(
|
|
| 131 |
allow_flagging="never",
|
| 132 |
cache_examples=False,
|
| 133 |
)
|
|
|
|
| 134 |
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
+
from gradio_client import Client, handle_file
|
| 10 |
|
| 11 |
+
# Initialize feature extractor and model for depth estimation
|
| 12 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 13 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 14 |
+
|
| 15 |
+
# Background removal API client
|
| 16 |
+
client = Client("not-lain/background-removal")
|
| 17 |
+
|
| 18 |
def process_image(image_path, depth_map_path=None):
|
| 19 |
image_path = Path(image_path)
|
| 20 |
image_raw = Image.open(image_path)
|
|
|
|
| 23 |
Image.Resampling.LANCZOS,
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# Step 1: Perform background removal
|
| 27 |
+
result = client.predict(
|
| 28 |
+
image=handle_file(image_path), # Use the input image
|
| 29 |
+
api_name="/image"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Assuming the result contains the foreground mask and processed image
|
| 33 |
+
foreground_image_url = result['output'] # Replace with actual response from API
|
| 34 |
+
foreground_image = Image.open(foreground_image_url)
|
| 35 |
+
|
| 36 |
if depth_map_path:
|
| 37 |
# Load and resize the user-provided depth map to match the RGB image size
|
| 38 |
depth_image_raw = Image.open(depth_map_path)
|
| 39 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 40 |
depth_image = np.array(depth_image)
|
| 41 |
|
| 42 |
+
# Normalize depth map if needed
|
|
|
|
| 43 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 44 |
depth_image = (depth_image * 255).astype('uint8')
|
| 45 |
|
|
|
|
|
|
|
|
|
|
| 46 |
else:
|
| 47 |
+
# Automatically generate the depth map using the DPT model
|
| 48 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 49 |
with torch.no_grad():
|
| 50 |
outputs = model(**encoding)
|
| 51 |
predicted_depth = outputs.predicted_depth
|
| 52 |
|
| 53 |
+
# Interpolate to match the image size
|
| 54 |
prediction = torch.nn.functional.interpolate(
|
| 55 |
predicted_depth.unsqueeze(1),
|
| 56 |
size=image.size[::-1],
|
|
|
|
| 59 |
).squeeze()
|
| 60 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 61 |
|
| 62 |
+
# Step 2: Create flat background depth layer and combine with foreground
|
| 63 |
+
background_depth_value = 20 # Slight depth for background
|
| 64 |
+
background_depth = np.full_like(depth_image, background_depth_value) # Flat depth for background
|
| 65 |
+
|
| 66 |
+
# Foreground mask from background removal (assumed to be binary mask)
|
| 67 |
+
foreground_mask = np.array(foreground_image.convert("L")) > 0
|
| 68 |
+
|
| 69 |
+
# Combine the flat background with the foreground depth
|
| 70 |
+
combined_depth_image = np.where(foreground_mask, depth_image, background_depth)
|
| 71 |
+
|
| 72 |
+
# Step 3: Generate 3D model using the combined depth map
|
| 73 |
try:
|
| 74 |
+
gltf_path = create_3d_obj(np.array(image), combined_depth_image, image_path)
|
| 75 |
+
img = Image.fromarray(combined_depth_image)
|
| 76 |
return [img, gltf_path, gltf_path]
|
| 77 |
except Exception as e:
|
| 78 |
+
print(f"Error creating 3D object: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
raise Exception("Error reconstructing 3D model")
|
| 80 |
|
| 81 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
|
|
| 92 |
|
| 93 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 94 |
|
| 95 |
+
print("Estimating normals")
|
| 96 |
pcd.normals = o3d.utility.Vector3dVector(
|
| 97 |
np.zeros((1, 3))
|
| 98 |
+
) # Invalidate existing normals
|
| 99 |
pcd.estimate_normals(
|
| 100 |
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 101 |
)
|
|
|
|
| 105 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 106 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 107 |
|
| 108 |
+
print("Running Poisson surface reconstruction")
|
| 109 |
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
|
| 110 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 111 |
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 112 |
)
|
| 113 |
|
| 114 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 115 |
+
print(f"Voxel size = {voxel_size:e}")
|
| 116 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 117 |
voxel_size=voxel_size,
|
| 118 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
|
|
| 127 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 128 |
return gltf_path
|
| 129 |
|
| 130 |
+
# Gradio interface setup
|
|
|
|
| 131 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 132 |
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."
|
| 133 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
|
|
| 149 |
allow_flagging="never",
|
| 150 |
cache_examples=False,
|
| 151 |
)
|
| 152 |
+
|
| 153 |
iface.launch(debug=True, show_api=True, share=True)
|