Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from skimage import
|
| 2 |
from skimage.filters import gaussian
|
| 3 |
from skimage.segmentation import clear_border
|
| 4 |
import gradio as gr
|
|
@@ -16,44 +16,6 @@ from rembg import remove
|
|
| 16 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 17 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 18 |
|
| 19 |
-
|
| 20 |
-
def normalize_depth_image(depth_image):
|
| 21 |
-
# Ensure depth_image is of type float32
|
| 22 |
-
depth_image = depth_image.astype(np.float32)
|
| 23 |
-
|
| 24 |
-
# Normalize depth values to the range [0, 1]
|
| 25 |
-
min_val = np.min(depth_image)
|
| 26 |
-
max_val = np.max(depth_image)
|
| 27 |
-
|
| 28 |
-
# Avoid division by zero
|
| 29 |
-
if max_val - min_val > 0:
|
| 30 |
-
depth_image_normalized = (depth_image - min_val) / (max_val - min_val)
|
| 31 |
-
else:
|
| 32 |
-
depth_image_normalized = depth_image - min_val # Handle the case where all values are the same
|
| 33 |
-
|
| 34 |
-
return depth_image_normalized
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# Function to inpaint the background
|
| 38 |
-
def inpaint_background(image, mask):
|
| 39 |
-
# Ensure the mask is binary (0 and 255)
|
| 40 |
-
mask_binary = (mask * 255).astype(np.uint8)
|
| 41 |
-
|
| 42 |
-
# Resize the mask to match the dimensions of the image if necessary
|
| 43 |
-
if image.shape[:2] != mask_binary.shape[:2]:
|
| 44 |
-
mask_binary_resized = cv2.resize(mask_binary, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
|
| 45 |
-
else:
|
| 46 |
-
mask_binary_resized = mask_binary
|
| 47 |
-
|
| 48 |
-
# Check dimensions before inpainting
|
| 49 |
-
print(f"Image shape: {image.shape}, Resized Mask shape: {mask_binary_resized.shape}")
|
| 50 |
-
|
| 51 |
-
# Inpaint the image using the resized mask
|
| 52 |
-
inpainted_image = cv2.inpaint(image.astype(np.uint8), mask_binary_resized, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 53 |
-
|
| 54 |
-
return inpainted_image
|
| 55 |
-
|
| 56 |
-
|
| 57 |
def process_image(image_path, depth_map_path=None):
|
| 58 |
image_path = Path(image_path)
|
| 59 |
image_raw = Image.open(image_path).convert("RGB")
|
|
@@ -69,15 +31,18 @@ def process_image(image_path, depth_map_path=None):
|
|
| 69 |
# Check if user-provided depth map is available
|
| 70 |
if depth_map_path:
|
| 71 |
if depth_map_path.endswith('.npy'):
|
| 72 |
-
depth_image = np.load(depth_map_path)
|
| 73 |
-
|
|
|
|
| 74 |
else:
|
| 75 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 76 |
-
depth_image =
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
depth_image =
|
|
|
|
|
|
|
| 81 |
else:
|
| 82 |
# Generate depth map using DPT model
|
| 83 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
@@ -91,117 +56,93 @@ def process_image(image_path, depth_map_path=None):
|
|
| 91 |
mode="bicubic",
|
| 92 |
align_corners=False,
|
| 93 |
).squeeze()
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
depth_image =
|
| 98 |
-
depth_image =
|
|
|
|
| 99 |
|
| 100 |
-
# Resize and apply Gaussian smoothing for smoother transitions
|
| 101 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 102 |
-
mask_blurred = cv2.GaussianBlur(depth_image, (
|
| 103 |
-
|
| 104 |
-
#
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
-
|
| 108 |
-
foreground_edges = cv2.Canny(np.array(foreground), 100, 200)
|
| 109 |
-
foreground_edges_resized = cv2.resize(foreground_edges, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
|
| 110 |
-
blended_depth_image[foreground_edges_resized > 0] *= 1.2
|
| 111 |
|
| 112 |
-
#
|
| 113 |
-
|
| 114 |
-
mask = clear_border(mask) # Clear objects touching the border
|
| 115 |
|
| 116 |
-
# Inpaint background where
|
| 117 |
background = remove(image_raw, only_mask=True)
|
| 118 |
-
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 119 |
-
background_inpainted =
|
| 120 |
|
| 121 |
try:
|
| 122 |
-
gltf_path = create_3d_obj(np.array(foreground)
|
| 123 |
-
|
| 124 |
-
img
|
| 125 |
-
return [img, gr.Model3D(), gltf_path]
|
| 126 |
except Exception as e:
|
| 127 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 128 |
-
gltf_path = create_3d_obj(np.array(foreground)
|
| 129 |
-
|
| 130 |
-
img
|
| 131 |
-
return [img, gr.Model3D(), gltf_path]
|
| 132 |
|
| 133 |
|
| 134 |
def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
| 135 |
-
# Resize and normalize the depth image
|
| 136 |
depth_image_resized = np.array(
|
| 137 |
Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
# Normalize depth values and convert to uint16
|
| 141 |
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 142 |
depth_image_resized.max() - depth_image_resized.min()
|
| 143 |
-
)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
# Log depth image details to verify compatibility
|
| 147 |
-
print("Depth image dtype:", depth_image_uint16.dtype)
|
| 148 |
-
print("Depth image min, max values:", depth_image_uint16.min(), depth_image_uint16.max())
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
image_o3d = o3d.geometry.Image(foreground.astype(np.uint8)) # Ensure foreground is uint8
|
| 153 |
-
|
| 154 |
-
# Create RGBD image using the uint16 depth image
|
| 155 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 156 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 157 |
)
|
| 158 |
-
|
| 159 |
-
# Get width and height for camera intrinsic setup
|
| 160 |
w, h = foreground.shape[1], foreground.shape[0]
|
|
|
|
| 161 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 162 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 163 |
|
| 164 |
-
# Create the point cloud from the RGBD image
|
| 165 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 166 |
|
| 167 |
-
# Check if there are enough points in the point cloud
|
| 168 |
if len(pcd.points) < 100:
|
| 169 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 170 |
|
| 171 |
-
# Estimate normals if they are not present
|
| 172 |
if not pcd.has_normals():
|
| 173 |
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
# Orient normals towards the camera location
|
| 176 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 177 |
-
|
| 178 |
-
# Create mesh using Poisson reconstruction
|
| 179 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 180 |
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 181 |
)
|
| 182 |
|
| 183 |
-
# Simplify and smooth the mesh
|
| 184 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 185 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 186 |
voxel_size=voxel_size,
|
| 187 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 188 |
)
|
| 189 |
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
min_bound = bbox.min_bound.copy() - [1, 1, 1]
|
| 194 |
-
max_bound = bbox.max_bound.copy() + [1, 1, 1]
|
| 195 |
-
bbox.min_bound = min_bound
|
| 196 |
-
bbox.max_bound = max_bound
|
| 197 |
-
mesh = mesh.crop(bbox)
|
| 198 |
-
|
| 199 |
-
# Save the mesh to a GLTF file
|
| 200 |
-
gltf_path = str(image_path.with_suffix(".gltf"))
|
| 201 |
-
o3d.io.write_triangle_mesh(gltf_path, mesh)
|
| 202 |
-
|
| 203 |
return gltf_path
|
| 204 |
-
|
| 205 |
# Gradio Interface
|
| 206 |
title = "Depth Estimation & 3D Reconstruction Demo"
|
| 207 |
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."
|
|
|
|
| 1 |
+
from skimage import img_as_uint
|
| 2 |
from skimage.filters import gaussian
|
| 3 |
from skimage.segmentation import clear_border
|
| 4 |
import gradio as gr
|
|
|
|
| 16 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 17 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
def process_image(image_path, depth_map_path=None):
|
| 20 |
image_path = Path(image_path)
|
| 21 |
image_raw = Image.open(image_path).convert("RGB")
|
|
|
|
| 31 |
# Check if user-provided depth map is available
|
| 32 |
if depth_map_path:
|
| 33 |
if depth_map_path.endswith('.npy'):
|
| 34 |
+
depth_image = np.load(depth_map_path)
|
| 35 |
+
# Invert depth only for npy files
|
| 36 |
+
depth_image = 1 - depth_image
|
| 37 |
else:
|
| 38 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 39 |
+
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 40 |
+
depth_image = np.array(depth_image)
|
| 41 |
+
|
| 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_uint(depth_image) # Changed to uint16
|
| 46 |
else:
|
| 47 |
# Generate depth map using DPT model
|
| 48 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
|
|
| 56 |
mode="bicubic",
|
| 57 |
align_corners=False,
|
| 58 |
).squeeze()
|
| 59 |
+
depth_image = prediction.cpu().numpy()
|
| 60 |
+
|
| 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_uint(depth_image) # Changed to uint16
|
| 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)
|
| 68 |
+
mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
|
| 69 |
+
|
| 70 |
+
# Ensure matching size and single channel for blending
|
| 71 |
+
if len(depth_image.shape) == 3:
|
| 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
|
| 79 |
+
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
|
|
|
|
| 80 |
|
| 81 |
+
# Inpaint background where main subject was removed
|
| 82 |
background = remove(image_raw, only_mask=True)
|
| 83 |
+
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 84 |
+
background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 85 |
|
| 86 |
try:
|
| 87 |
+
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path)
|
| 88 |
+
img = Image.fromarray(blended_depth_image)
|
| 89 |
+
return [img, gltf_path, gltf_path]
|
|
|
|
| 90 |
except Exception as e:
|
| 91 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 92 |
+
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path, depth=9)
|
| 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 |
+
) * 65535 # Updated for uint16 scale
|
| 104 |
+
depth_image_normalized = depth_image_normalized.astype(np.uint16) # Changed to uint16
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 124 |
+
if pcd.has_normals():
|
| 125 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 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."
|