Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@ import gradio as gr
|
|
| 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 pathlib import Path
|
| 8 |
import os
|
|
@@ -16,60 +16,71 @@ model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
|
| 16 |
def process_image(image_path, depth_map_path=None):
|
| 17 |
image_path = Path(image_path)
|
| 18 |
image_raw = Image.open(image_path).convert("RGB")
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
# Remove background using rembg
|
| 22 |
foreground = remove(image_raw)
|
| 23 |
foreground = Image.fromarray(np.array(foreground)).convert("RGB")
|
| 24 |
|
| 25 |
-
# Duplicate the background to keep original size
|
| 26 |
-
background_with_depth = image_raw.copy()
|
| 27 |
-
background_regular = image_raw.copy()
|
| 28 |
-
|
| 29 |
# Check if user-provided depth map is available
|
| 30 |
if depth_map_path:
|
| 31 |
if depth_map_path.endswith('.npy'):
|
| 32 |
depth_image = np.load(depth_map_path)
|
| 33 |
else:
|
| 34 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 35 |
-
depth_image = depth_image_raw.resize(
|
| 36 |
depth_image = np.array(depth_image)
|
|
|
|
|
|
|
| 37 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 38 |
depth_image = (depth_image * 255).astype('uint8')
|
| 39 |
else:
|
|
|
|
| 40 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 41 |
with torch.no_grad():
|
| 42 |
outputs = model(**encoding)
|
| 43 |
predicted_depth = outputs.predicted_depth
|
|
|
|
| 44 |
prediction = torch.nn.functional.interpolate(
|
| 45 |
predicted_depth.unsqueeze(1),
|
| 46 |
-
size=
|
| 47 |
mode="bicubic",
|
| 48 |
align_corners=False,
|
| 49 |
).squeeze()
|
| 50 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
mask_blurred =
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
| 57 |
-
|
| 58 |
-
# Blend
|
| 59 |
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
|
| 60 |
-
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred, 0.2, 0)
|
| 61 |
|
| 62 |
try:
|
| 63 |
-
gltf_path = create_3d_obj(np.array(
|
| 64 |
-
|
| 65 |
-
return [
|
| 66 |
-
except Exception
|
| 67 |
-
print("Error with default depth. Retrying with shallower depth.")
|
| 68 |
-
gltf_path = create_3d_obj(np.array(
|
| 69 |
-
|
| 70 |
-
return [
|
| 71 |
|
| 72 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
|
|
|
|
| 73 |
depth_image_resized = np.array(
|
| 74 |
Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
|
| 75 |
)
|
|
@@ -86,30 +97,43 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
|
|
| 86 |
)
|
| 87 |
w, h = rgb_image.shape[1], rgb_image.shape[0]
|
| 88 |
|
|
|
|
| 89 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 90 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 91 |
|
|
|
|
| 92 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
if not pcd.has_normals():
|
|
|
|
| 95 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 96 |
|
| 97 |
if pcd.has_normals():
|
| 98 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
|
|
|
|
|
|
| 99 |
|
|
|
|
| 100 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 101 |
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 102 |
)
|
| 103 |
|
| 104 |
-
|
|
|
|
| 105 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 106 |
voxel_size=voxel_size,
|
| 107 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 108 |
)
|
| 109 |
-
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 110 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 111 |
mesh_crop = mesh.crop(bbox)
|
| 112 |
|
|
|
|
| 113 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 114 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 115 |
return gltf_path
|
|
|
|
| 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 pathlib import Path
|
| 8 |
import os
|
|
|
|
| 16 |
def process_image(image_path, depth_map_path=None):
|
| 17 |
image_path = Path(image_path)
|
| 18 |
image_raw = Image.open(image_path).convert("RGB")
|
| 19 |
+
image = image_raw.resize(
|
| 20 |
+
(2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
|
| 21 |
+
Image.Resampling.LANCZOS,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
# Remove background using rembg
|
| 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).convert("L")
|
| 34 |
+
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 35 |
depth_image = np.array(depth_image)
|
| 36 |
+
|
| 37 |
+
# Normalize depth image
|
| 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 |
+
# Generate depth map using DPT model
|
| 42 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 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],
|
| 50 |
mode="bicubic",
|
| 51 |
align_corners=False,
|
| 52 |
).squeeze()
|
| 53 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 54 |
|
| 55 |
+
# Resize and apply lighter Gaussian smoothing
|
| 56 |
+
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 57 |
+
mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for more detail
|
| 58 |
+
|
| 59 |
+
# Ensure matching size and single channel for blending
|
| 60 |
+
if len(depth_image.shape) == 3:
|
| 61 |
+
depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
|
| 62 |
+
|
| 63 |
+
if len(mask_blurred.shape) == 3:
|
| 64 |
+
mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
|
| 65 |
+
|
| 66 |
+
# Resize mask_blurred to match depth_image dimensions
|
| 67 |
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
| 68 |
+
|
| 69 |
+
# Blend depth_image with mask_blurred_resized
|
| 70 |
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
|
|
|
|
| 71 |
|
| 72 |
try:
|
| 73 |
+
gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path)
|
| 74 |
+
img = Image.fromarray(blended_depth_image)
|
| 75 |
+
return [img, gltf_path, gltf_path]
|
| 76 |
+
except Exception:
|
| 77 |
+
print("Error with default depth. Retrying with a shallower depth.")
|
| 78 |
+
gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path, depth=9)
|
| 79 |
+
img = Image.fromarray(blended_depth_image)
|
| 80 |
+
return [img, gltf_path, gltf_path]
|
| 81 |
|
| 82 |
def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
|
| 83 |
+
# Resize and normalize the depth image
|
| 84 |
depth_image_resized = np.array(
|
| 85 |
Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
|
| 86 |
)
|
|
|
|
| 97 |
)
|
| 98 |
w, h = rgb_image.shape[1], rgb_image.shape[0]
|
| 99 |
|
| 100 |
+
# Camera intrinsic setup
|
| 101 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 102 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 103 |
|
| 104 |
+
# Create Point Cloud from RGBD Image
|
| 105 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 106 |
|
| 107 |
+
# Check if the point cloud has enough points
|
| 108 |
+
if len(pcd.points) < 100:
|
| 109 |
+
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 110 |
+
|
| 111 |
+
# Estimate and orient normals
|
| 112 |
if not pcd.has_normals():
|
| 113 |
+
print("Estimating normals with increased search radius for sparse data...")
|
| 114 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 115 |
|
| 116 |
if pcd.has_normals():
|
| 117 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 118 |
+
else:
|
| 119 |
+
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 120 |
|
| 121 |
+
# Poisson Surface Reconstruction
|
| 122 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 123 |
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 124 |
)
|
| 125 |
|
| 126 |
+
# Mesh simplification and reduced smoothing for better detail
|
| 127 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400 # Decreased voxel size for finer detail
|
| 128 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 129 |
voxel_size=voxel_size,
|
| 130 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 131 |
)
|
| 132 |
+
mesh = mesh.filter_smooth_simple(number_of_iterations=3) # Reduced smoothing iterations for sharpness
|
| 133 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 134 |
mesh_crop = mesh.crop(bbox)
|
| 135 |
|
| 136 |
+
# Save GLTF
|
| 137 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 138 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 139 |
return gltf_path
|