Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
from skimage import
|
| 2 |
from skimage.filters import gaussian
|
| 3 |
from skimage.segmentation import clear_border
|
| 4 |
-
from scipy.ndimage import gaussian_filter
|
| 5 |
import gradio as gr
|
| 6 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 7 |
import torch
|
|
@@ -43,7 +42,7 @@ def process_image(image_path, depth_map_path=None):
|
|
| 43 |
# Normalize depth image to [0, 1] range
|
| 44 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 45 |
depth_image = np.clip(depth_image, 0, 1)
|
| 46 |
-
depth_image =
|
| 47 |
else:
|
| 48 |
# Generate depth map using DPT model
|
| 49 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
@@ -62,7 +61,7 @@ def process_image(image_path, depth_map_path=None):
|
|
| 62 |
# Normalize depth image to [0, 1] range before converting
|
| 63 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 64 |
depth_image = np.clip(depth_image, 0, 1)
|
| 65 |
-
depth_image =
|
| 66 |
|
| 67 |
# Resize and apply lighter Gaussian smoothing for smoother transitions
|
| 68 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
|
@@ -73,7 +72,7 @@ def process_image(image_path, depth_map_path=None):
|
|
| 73 |
depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
|
| 74 |
if len(mask_blurred.shape) == 3:
|
| 75 |
mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
|
| 76 |
-
|
| 77 |
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
| 78 |
|
| 79 |
# Blend depth_image with mask_blurred_resized for smoother transition
|
|
@@ -94,59 +93,31 @@ def process_image(image_path, depth_map_path=None):
|
|
| 94 |
img = Image.fromarray(blended_depth_image)
|
| 95 |
return [img, gltf_path, gltf_path]
|
| 96 |
|
| 97 |
-
|
| 98 |
-
import cv2 # Make sure OpenCV is installed
|
| 99 |
-
|
| 100 |
def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
raise ValueError("Depth image should be a 2D array, but got: {}".format(depth_image.shape))
|
| 104 |
-
|
| 105 |
-
depth_image = depth_image.astype(np.uint16)
|
| 106 |
-
|
| 107 |
-
# Create a PIL image from the depth image
|
| 108 |
-
try:
|
| 109 |
-
depth_image_pil = Image.fromarray(depth_image, mode='I;16')
|
| 110 |
-
print(f"Depth image mode: {depth_image_pil.mode}") # Debug: Check mode after creation
|
| 111 |
-
except Exception as e:
|
| 112 |
-
raise ValueError(f"Error creating PIL image from depth array: {e}")
|
| 113 |
-
|
| 114 |
-
# Convert to 'L' mode if resizing fails with 'I;16' mode
|
| 115 |
-
if depth_image_pil.mode != 'L':
|
| 116 |
-
depth_image_pil = depth_image_pil.convert('L')
|
| 117 |
-
print(f"Converted depth image mode to: {depth_image_pil.mode}") # Debug
|
| 118 |
-
|
| 119 |
-
# Resize depth image
|
| 120 |
-
depth_image_resized = depth_image_pil.resize(
|
| 121 |
-
foreground.shape[1::-1], Image.Resampling.BILINEAR
|
| 122 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
-
|
| 125 |
-
depth_image_resized_np = np.array(depth_image_resized)
|
| 126 |
-
|
| 127 |
-
# Check for valid shape and dtype
|
| 128 |
-
if depth_image_resized_np.ndim != 2 or depth_image_resized_np.shape[0] == 0 or depth_image_resized_np.shape[1] == 0:
|
| 129 |
-
raise ValueError(f"Resized depth image is not valid. Shape: {depth_image_resized_np.shape}")
|
| 130 |
-
|
| 131 |
-
# Create Open3D image from depth
|
| 132 |
-
depth_o3d = o3d.geometry.Image(depth_image_resized_np)
|
| 133 |
image_o3d = o3d.geometry.Image(foreground)
|
| 134 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 135 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 136 |
)
|
| 137 |
-
|
| 138 |
-
# Set camera intrinsic parameters
|
| 139 |
w, h = foreground.shape[1], foreground.shape[0]
|
|
|
|
| 140 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 141 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 142 |
|
| 143 |
-
# Create point cloud from RGBD image
|
| 144 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 145 |
|
| 146 |
if len(pcd.points) < 100:
|
| 147 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 148 |
|
| 149 |
-
# Estimate normals
|
| 150 |
if not pcd.has_normals():
|
| 151 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 152 |
|
|
@@ -155,31 +126,23 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
|
| 155 |
else:
|
| 156 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 157 |
|
| 158 |
-
# Increase the depth parameter dynamically based on image size for finer details in complex images
|
| 159 |
-
adjusted_depth = depth + int(min(w, h) / 500)
|
| 160 |
-
|
| 161 |
-
# Create mesh using Poisson reconstruction
|
| 162 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 163 |
-
pcd, depth=
|
| 164 |
)
|
| 165 |
|
| 166 |
-
# Simplify mesh
|
| 167 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 168 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 169 |
voxel_size=voxel_size,
|
| 170 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 171 |
)
|
| 172 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 173 |
-
|
| 174 |
-
# Crop mesh to point cloud bounding box
|
| 175 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 176 |
mesh_crop = mesh.crop(bbox)
|
| 177 |
|
| 178 |
-
# Save as GLTF
|
| 179 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 180 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 181 |
return gltf_path
|
| 182 |
-
|
| 183 |
# Gradio Interface
|
| 184 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 185 |
description = "Upload an image and optionally a depth map (in .npy or image format) to generate a 3D model. If no depth map is provided, the DPT model will generate it."
|
|
@@ -203,4 +166,4 @@ iface = gr.Interface(
|
|
| 203 |
allow_flagging="never",
|
| 204 |
cache_examples=False,
|
| 205 |
)
|
| 206 |
-
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 1 |
+
from skimage import img_as_ubyte
|
| 2 |
from skimage.filters import gaussian
|
| 3 |
from skimage.segmentation import clear_border
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 6 |
import torch
|
|
|
|
| 42 |
# Normalize depth image to [0, 1] range
|
| 43 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 44 |
depth_image = np.clip(depth_image, 0, 1)
|
| 45 |
+
depth_image = img_as_ubyte(depth_image)
|
| 46 |
else:
|
| 47 |
# Generate depth map using DPT model
|
| 48 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
|
|
| 61 |
# Normalize depth image to [0, 1] range before converting
|
| 62 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 63 |
depth_image = np.clip(depth_image, 0, 1)
|
| 64 |
+
depth_image = img_as_ubyte(depth_image)
|
| 65 |
|
| 66 |
# Resize and apply lighter Gaussian smoothing for smoother transitions
|
| 67 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
|
|
|
| 72 |
depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
|
| 73 |
if len(mask_blurred.shape) == 3:
|
| 74 |
mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
|
| 75 |
+
|
| 76 |
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
| 77 |
|
| 78 |
# Blend depth_image with mask_blurred_resized for smoother transition
|
|
|
|
| 93 |
img = Image.fromarray(blended_depth_image)
|
| 94 |
return [img, gltf_path, gltf_path]
|
| 95 |
|
| 96 |
+
|
|
|
|
|
|
|
| 97 |
def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
| 98 |
+
depth_image_resized = np.array(
|
| 99 |
+
Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
)
|
| 101 |
+
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 102 |
+
depth_image_resized.max() - depth_image_resized.min()
|
| 103 |
+
) * 255
|
| 104 |
+
depth_image_normalized = depth_image_normalized.astype(np.uint8)
|
| 105 |
|
| 106 |
+
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
image_o3d = o3d.geometry.Image(foreground)
|
| 108 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 109 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 110 |
)
|
|
|
|
|
|
|
| 111 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 112 |
+
|
| 113 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 114 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 115 |
|
|
|
|
| 116 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 117 |
|
| 118 |
if len(pcd.points) < 100:
|
| 119 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 120 |
|
|
|
|
| 121 |
if not pcd.has_normals():
|
| 122 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 123 |
|
|
|
|
| 126 |
else:
|
| 127 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 130 |
+
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 131 |
)
|
| 132 |
|
|
|
|
| 133 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 134 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 135 |
voxel_size=voxel_size,
|
| 136 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 137 |
)
|
| 138 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
|
|
|
|
|
|
| 139 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 140 |
mesh_crop = mesh.crop(bbox)
|
| 141 |
|
|
|
|
| 142 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 143 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 144 |
return gltf_path
|
| 145 |
+
|
| 146 |
# Gradio Interface
|
| 147 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 148 |
description = "Upload an image and optionally a depth map (in .npy or image format) to generate a 3D model. If no depth map is provided, the DPT model will generate it."
|
|
|
|
| 166 |
allow_flagging="never",
|
| 167 |
cache_examples=False,
|
| 168 |
)
|
| 169 |
+
iface.launch(debug=True, show_api=True, share=True)
|