Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,20 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
import open3d as o3d
|
| 7 |
-
from gradio_client import Client
|
| 8 |
from pathlib import Path
|
| 9 |
import os
|
| 10 |
|
| 11 |
-
|
| 12 |
client = Client("not-lain/background-removal")
|
|
|
|
|
|
|
|
|
|
| 13 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
|
|
|
| 14 |
def process_image(image_path, depth_map_path=None):
|
| 15 |
image_path = Path(image_path)
|
| 16 |
image_raw = Image.open(image_path)
|
|
@@ -19,52 +23,47 @@ def process_image(image_path, depth_map_path=None):
|
|
| 19 |
Image.Resampling.LANCZOS,
|
| 20 |
)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
with open(image_path, 'rb') as image_file:
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
subject_image = Image.open(result[0]) # Result is a PNG with transparent background
|
| 27 |
-
|
| 28 |
if depth_map_path:
|
| 29 |
-
#
|
| 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 |
else:
|
| 34 |
-
#
|
| 35 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 36 |
with torch.no_grad():
|
| 37 |
outputs = model(**encoding)
|
| 38 |
predicted_depth = outputs.predicted_depth
|
| 39 |
|
| 40 |
-
# Interpolate
|
| 41 |
-
|
| 42 |
predicted_depth.unsqueeze(1),
|
| 43 |
size=image.size[::-1],
|
| 44 |
mode="bicubic",
|
| 45 |
align_corners=False,
|
| 46 |
-
).squeeze()
|
| 47 |
-
|
| 48 |
-
# Normalize depth image
|
| 49 |
-
depth_image = (depth_image * 255 / np.max(depth_image)).astype('uint8')
|
| 50 |
|
| 51 |
-
# Adjust subject depth separately
|
| 52 |
-
subject_depth_map = process_subject_depth(subject_image, depth_image)
|
| 53 |
-
|
| 54 |
-
# Create slightly 3D background effect (you could slightly shift the depth map here)
|
| 55 |
-
bg_depth_map = process_background_depth(image, depth_image)
|
| 56 |
-
|
| 57 |
-
# Merge depth maps back together
|
| 58 |
-
combined_depth_map = merge_depth_maps(subject_depth_map, bg_depth_map)
|
| 59 |
-
|
| 60 |
-
# 3D reconstruction process
|
| 61 |
try:
|
| 62 |
-
gltf_path = create_3d_obj(np.array(image),
|
| 63 |
-
img = Image.fromarray(
|
| 64 |
return [img, gltf_path, gltf_path]
|
| 65 |
except Exception as e:
|
| 66 |
-
print(f"Error
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 70 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
@@ -80,27 +79,18 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 80 |
|
| 81 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
pcd.
|
| 85 |
-
|
| 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 |
-
|
| 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,
|
|
@@ -109,14 +99,14 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
|
| 109 |
# Apply smoothing
|
| 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 |
-
|
| 119 |
-
|
| 120 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 121 |
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."
|
| 122 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
@@ -138,4 +128,5 @@ iface = gr.Interface(
|
|
| 138 |
allow_flagging="never",
|
| 139 |
cache_examples=False,
|
| 140 |
)
|
| 141 |
-
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
from gradio_client import Client
|
| 3 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 4 |
import torch
|
| 5 |
import numpy as np
|
| 6 |
from PIL import Image
|
| 7 |
import open3d as o3d
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
import os
|
| 10 |
|
| 11 |
+
# Initialize Gradio client for background removal
|
| 12 |
client = Client("not-lain/background-removal")
|
| 13 |
+
|
| 14 |
+
# Initialize DPT depth estimation model
|
| 15 |
+
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 16 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 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 |
+
# Handle background removal via Gradio Client
|
| 27 |
with open(image_path, 'rb') as image_file:
|
| 28 |
+
image_data = base64.b64encode(image_file.read()).decode('utf-8')
|
| 29 |
+
|
| 30 |
+
result = client.predict(f"data:image/png;base64,{image_data}", api_name="/png")
|
| 31 |
+
subject_image = Image.open(result[0]) # Processed PNG with transparent background
|
| 32 |
|
|
|
|
|
|
|
| 33 |
if depth_map_path:
|
| 34 |
+
# Load and resize the user-provided depth map to match the RGB image size
|
| 35 |
depth_image_raw = Image.open(depth_map_path)
|
| 36 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 37 |
depth_image = np.array(depth_image)
|
| 38 |
+
|
| 39 |
+
# Normalize depth map
|
| 40 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 41 |
+
depth_image = (depth_image * 255).astype('uint8')
|
| 42 |
else:
|
| 43 |
+
# Generate depth map using the DPT model
|
| 44 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 45 |
with torch.no_grad():
|
| 46 |
outputs = model(**encoding)
|
| 47 |
predicted_depth = outputs.predicted_depth
|
| 48 |
|
| 49 |
+
# Interpolate to original size
|
| 50 |
+
prediction = torch.nn.functional.interpolate(
|
| 51 |
predicted_depth.unsqueeze(1),
|
| 52 |
size=image.size[::-1],
|
| 53 |
mode="bicubic",
|
| 54 |
align_corners=False,
|
| 55 |
+
).squeeze()
|
| 56 |
+
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
|
|
|
|
|
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
try:
|
| 59 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
|
| 60 |
+
img = Image.fromarray(depth_image)
|
| 61 |
return [img, gltf_path, gltf_path]
|
| 62 |
except Exception as e:
|
| 63 |
+
print(f"Error: {e}")
|
| 64 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
|
| 65 |
+
img = Image.fromarray(depth_image)
|
| 66 |
+
return [img, gltf_path, gltf_path]
|
| 67 |
|
| 68 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 69 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
|
|
| 79 |
|
| 80 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 81 |
|
| 82 |
+
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Invalidate existing normals
|
| 83 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
|
| 84 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 86 |
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 87 |
|
| 88 |
+
# Poisson surface reconstruction
|
| 89 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 90 |
+
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 91 |
+
)
|
|
|
|
| 92 |
|
| 93 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
|
|
|
| 94 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 95 |
voxel_size=voxel_size,
|
| 96 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
|
|
| 99 |
# Apply smoothing
|
| 100 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 101 |
|
| 102 |
+
# Crop the mesh to fit the object
|
| 103 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 104 |
mesh_crop = mesh.crop(bbox)
|
| 105 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 106 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 107 |
return gltf_path
|
| 108 |
|
| 109 |
+
# Gradio interface setup
|
|
|
|
| 110 |
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 111 |
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."
|
| 112 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
|
|
|
| 128 |
allow_flagging="never",
|
| 129 |
cache_examples=False,
|
| 130 |
)
|
| 131 |
+
|
| 132 |
+
iface.launch(debug=True, show_api=True, share=True)
|