Update app.py
Browse files
app.py
CHANGED
|
@@ -6,44 +6,39 @@ from PIL import Image
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
-
import cv2
|
| 10 |
-
from rembg import remove
|
| 11 |
|
| 12 |
-
#
|
| 13 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 14 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 15 |
|
| 16 |
def process_image(image_path, depth_map_path=None):
|
| 17 |
image_path = Path(image_path)
|
| 18 |
-
image_raw = Image.open(image_path)
|
| 19 |
image = image_raw.resize(
|
| 20 |
-
(
|
| 21 |
Image.Resampling.LANCZOS,
|
| 22 |
)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
foreground = remove(image_raw)
|
| 26 |
-
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 27 |
-
|
| 28 |
-
# Check if user-provided depth map is available
|
| 29 |
if depth_map_path:
|
| 30 |
if depth_map_path.endswith('.npy'):
|
| 31 |
depth_image = np.load(depth_map_path)
|
| 32 |
else:
|
| 33 |
-
depth_image_raw = Image.open(depth_map_path)
|
| 34 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 35 |
depth_image = np.array(depth_image)
|
| 36 |
|
| 37 |
-
# Normalize depth
|
| 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 |
else:
|
| 41 |
-
#
|
| 42 |
-
encoding = feature_extractor(
|
| 43 |
with torch.no_grad():
|
| 44 |
outputs = model(**encoding)
|
| 45 |
predicted_depth = outputs.predicted_depth
|
| 46 |
|
|
|
|
| 47 |
prediction = torch.nn.functional.interpolate(
|
| 48 |
predicted_depth.unsqueeze(1),
|
| 49 |
size=image.size[::-1],
|
|
@@ -52,90 +47,71 @@ def process_image(image_path, depth_map_path=None):
|
|
| 52 |
).squeeze()
|
| 53 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 54 |
|
| 55 |
-
# Resize and apply Gaussian smoothing
|
| 56 |
-
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 57 |
-
smoothed_depth_map = cv2.GaussianBlur(depth_image, (7, 7), 1.5) # Slightly stronger blur for smoother transition
|
| 58 |
-
|
| 59 |
try:
|
| 60 |
-
|
| 61 |
-
|
|
|
|
| 62 |
return [img, gltf_path, gltf_path]
|
| 63 |
-
except Exception:
|
| 64 |
-
|
| 65 |
-
gltf_path = create_3d_obj(np.array(image),
|
| 66 |
-
img = Image.fromarray(
|
| 67 |
return [img, gltf_path, gltf_path]
|
| 68 |
|
| 69 |
-
def create_3d_obj(rgb_image, depth_image, image_path, depth=
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
|
| 73 |
-
)
|
| 74 |
-
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 75 |
-
depth_image_resized.max() - depth_image_resized.min()
|
| 76 |
-
)
|
| 77 |
-
depth_image_inverted = (1 - depth_image_normalized) * 255
|
| 78 |
-
depth_image_inverted = depth_image_inverted.astype(np.uint8)
|
| 79 |
-
|
| 80 |
-
depth_o3d = o3d.geometry.Image(depth_image_inverted)
|
| 81 |
image_o3d = o3d.geometry.Image(rgb_image)
|
| 82 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 83 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 84 |
)
|
| 85 |
-
w, h =
|
| 86 |
|
| 87 |
-
#
|
| 88 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 89 |
-
camera_intrinsic.set_intrinsics(w, h,
|
| 90 |
|
| 91 |
-
#
|
| 92 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 93 |
|
| 94 |
-
#
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 110 |
-
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
# Mesh simplification and smoothing
|
| 114 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 320 # Decreased voxel size for detail
|
| 115 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 116 |
voxel_size=voxel_size,
|
| 117 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 118 |
)
|
| 119 |
-
mesh = mesh.filter_smooth_simple(number_of_iterations=
|
|
|
|
|
|
|
| 120 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 121 |
mesh_crop = mesh.crop(bbox)
|
| 122 |
-
|
| 123 |
-
# Save GLTF
|
| 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 |
-
# Gradio
|
| 129 |
-
title = "Depth Estimation & 3D Reconstruction
|
| 130 |
-
description = "
|
| 131 |
-
|
| 132 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 133 |
|
| 134 |
iface = gr.Interface(
|
| 135 |
fn=process_image,
|
| 136 |
inputs=[
|
| 137 |
gr.Image(type="filepath", label="Input Image"),
|
| 138 |
-
gr.
|
| 139 |
],
|
| 140 |
outputs=[
|
| 141 |
gr.Image(label="Predicted Depth", type="pil"),
|
|
@@ -148,4 +124,5 @@ iface = gr.Interface(
|
|
| 148 |
allow_flagging="never",
|
| 149 |
cache_examples=False,
|
| 150 |
)
|
|
|
|
| 151 |
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 6 |
import open3d as o3d
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# Load the DPT 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)
|
| 17 |
image = image_raw.resize(
|
| 18 |
+
(1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
|
| 19 |
Image.Resampling.LANCZOS,
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# Check if a depth map is provided; support both .npy and image formats
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
if depth_map_path:
|
| 24 |
if depth_map_path.endswith('.npy'):
|
| 25 |
depth_image = np.load(depth_map_path)
|
| 26 |
else:
|
| 27 |
+
depth_image_raw = Image.open(depth_map_path)
|
| 28 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 29 |
depth_image = np.array(depth_image)
|
| 30 |
|
| 31 |
+
# Normalize and adjust the depth map to improve visualization
|
| 32 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 33 |
depth_image = (depth_image * 255).astype('uint8')
|
| 34 |
else:
|
| 35 |
+
# Automatically generate a depth map if none is 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 |
+
# Resize depth map to the original image size
|
| 42 |
prediction = torch.nn.functional.interpolate(
|
| 43 |
predicted_depth.unsqueeze(1),
|
| 44 |
size=image.size[::-1],
|
|
|
|
| 47 |
).squeeze()
|
| 48 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
+
# Create the 3D object from the image and depth map
|
| 52 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
|
| 53 |
+
img = Image.fromarray(depth_image)
|
| 54 |
return [img, gltf_path, gltf_path]
|
| 55 |
+
except Exception as e:
|
| 56 |
+
# Retry with a different Poisson depth if initial attempt fails
|
| 57 |
+
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
|
| 58 |
+
img = Image.fromarray(depth_image)
|
| 59 |
return [img, gltf_path, gltf_path]
|
| 60 |
|
| 61 |
+
def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
|
| 62 |
+
# Convert depth and RGB images to Open3D format
|
| 63 |
+
depth_o3d = o3d.geometry.Image(depth_image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
image_o3d = o3d.geometry.Image(rgb_image)
|
| 65 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 66 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 67 |
)
|
| 68 |
+
w, h = depth_image.shape[1], depth_image.shape[0]
|
| 69 |
|
| 70 |
+
# Set camera intrinsics for depth estimation
|
| 71 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 72 |
+
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 73 |
|
| 74 |
+
# Generate a point cloud from the RGBD image
|
| 75 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 76 |
|
| 77 |
+
# Normalize and orient point cloud
|
| 78 |
+
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 79 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
|
| 80 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
| 81 |
+
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 82 |
+
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 83 |
+
|
| 84 |
+
# Poisson surface reconstruction for creating a 3D mesh from the point cloud
|
| 85 |
+
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
|
| 86 |
+
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 87 |
+
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Simplify and smooth the mesh to improve visual quality
|
| 91 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 93 |
voxel_size=voxel_size,
|
| 94 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 95 |
)
|
| 96 |
+
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 97 |
+
|
| 98 |
+
# Crop the mesh to the bounding box for alignment
|
| 99 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 100 |
mesh_crop = mesh.crop(bbox)
|
|
|
|
|
|
|
| 101 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 102 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 103 |
return gltf_path
|
| 104 |
|
| 105 |
+
# Gradio interface configuration
|
| 106 |
+
title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
|
| 107 |
+
description = "This demo allows users to provide an RGB image and optionally a depth map (in image or .npy format) to create a 3D object. If no depth map is provided, the DPT model will generate it."
|
|
|
|
| 108 |
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 109 |
|
| 110 |
iface = gr.Interface(
|
| 111 |
fn=process_image,
|
| 112 |
inputs=[
|
| 113 |
gr.Image(type="filepath", label="Input Image"),
|
| 114 |
+
gr.Image(type="filepath", label="Input Depth Map (optional)"),
|
| 115 |
],
|
| 116 |
outputs=[
|
| 117 |
gr.Image(label="Predicted Depth", type="pil"),
|
|
|
|
| 124 |
allow_flagging="never",
|
| 125 |
cache_examples=False,
|
| 126 |
)
|
| 127 |
+
|
| 128 |
iface.launch(debug=True, show_api=True, share=True)
|