Update app.py
Browse files
app.py
CHANGED
|
@@ -7,12 +7,85 @@ import open3d as o3d
|
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
import cv2
|
|
|
|
| 10 |
|
| 11 |
# Load the DPT model for depth estimation
|
| 12 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 13 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 18 |
try:
|
|
@@ -74,74 +147,7 @@ def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
|
| 74 |
|
| 75 |
except Exception as e:
|
| 76 |
print(f"Error reconstructing 3D model: {e}")
|
| 77 |
-
raise
|
| 78 |
-
|
| 79 |
-
def create_main_subject_mask(image):
|
| 80 |
-
"""Generates a binary mask for the main subject using rembg."""
|
| 81 |
-
# Remove background and create mask
|
| 82 |
-
subject_only = remove(image)
|
| 83 |
-
subject_mask = Image.fromarray((np.array(subject_only)[:, :, 3] > 0).astype(np.uint8) * 255)
|
| 84 |
-
return np.array(subject_mask)
|
| 85 |
-
|
| 86 |
-
def inpaint_background(image, original_image):
|
| 87 |
-
# Resize `image` to match `original_image` dimensions
|
| 88 |
-
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
| 89 |
-
|
| 90 |
-
# Convert to grayscale and create the mask in `uint8` format
|
| 91 |
-
mask = np.array(resized_image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
|
| 92 |
-
|
| 93 |
-
# Apply inpainting
|
| 94 |
-
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 95 |
-
return inpainted_image
|
| 96 |
-
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 97 |
-
# Create RGBD image in Open3D format
|
| 98 |
-
depth_o3d = o3d.geometry.Image(depth_image)
|
| 99 |
-
image_o3d = o3d.geometry.Image(rgb_image)
|
| 100 |
-
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 101 |
-
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
w, h = depth_image.shape[1], depth_image.shape[0]
|
| 105 |
-
|
| 106 |
-
# Set camera intrinsic parameters
|
| 107 |
-
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 108 |
-
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 109 |
-
|
| 110 |
-
# Create a 3D point cloud from the RGBD image
|
| 111 |
-
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 112 |
-
|
| 113 |
-
# Apply offset to main subject for panorama effect
|
| 114 |
-
pcd.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.05], [0, 0, 0, 1]])
|
| 115 |
-
|
| 116 |
-
# Orient normals towards the camera
|
| 117 |
-
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 118 |
-
pcd.estimate_normals(
|
| 119 |
-
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 120 |
-
)
|
| 121 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
| 122 |
-
|
| 123 |
-
# Poisson reconstruction with a flat back surface
|
| 124 |
-
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
|
| 125 |
-
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 126 |
-
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
# Flatten the back surface of the main subject
|
| 130 |
-
for vertex in np.asarray(mesh_raw.vertices):
|
| 131 |
-
if vertex[2] < -0.05: # Adjust based on the desired flatness level
|
| 132 |
-
vertex[2] = -0.05
|
| 133 |
-
|
| 134 |
-
# Simplify the mesh while keeping details
|
| 135 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 136 |
-
mesh = mesh_raw.simplify_vertex_clustering(
|
| 137 |
-
voxel_size=voxel_size,
|
| 138 |
-
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
# Remove bounding box crop to preserve background at full size
|
| 142 |
-
gltf_path = f"./{image_path.stem}.gltf"
|
| 143 |
-
o3d.io.write_triangle_mesh(gltf_path, mesh, write_triangle_uvs=True)
|
| 144 |
-
return gltf_path
|
| 145 |
|
| 146 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
| 147 |
description = (
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
import os
|
| 9 |
import cv2
|
| 10 |
+
from rembg import remove
|
| 11 |
|
| 12 |
# Load the DPT model for depth estimation
|
| 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 |
+
|
| 20 |
+
# Resize image to 1600 width while maintaining aspect ratio
|
| 21 |
+
new_width = 1600
|
| 22 |
+
new_height = int(new_width * image_raw.size[1] / image_raw.size[0])
|
| 23 |
+
image = image_raw.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 24 |
+
|
| 25 |
+
if depth_map_path:
|
| 26 |
+
# Determine if depth map is npy or image format
|
| 27 |
+
if depth_map_path.endswith(".npy"):
|
| 28 |
+
depth_image = np.load(depth_map_path)
|
| 29 |
+
else:
|
| 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 |
+
|
| 34 |
+
# Normalize depth if needed
|
| 35 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 36 |
+
depth_image = (depth_image * 255).astype('uint8')
|
| 37 |
+
else:
|
| 38 |
+
# Generate depth using DPT if not provided
|
| 39 |
+
encoding = feature_extractor(image, return_tensors="pt")
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
outputs = model(**encoding)
|
| 42 |
+
predicted_depth = outputs.predicted_depth
|
| 43 |
+
|
| 44 |
+
prediction = torch.nn.functional.interpolate(
|
| 45 |
+
predicted_depth.unsqueeze(1),
|
| 46 |
+
size=image.size[::-1],
|
| 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 |
+
# Create a mask of the main subject using rembg
|
| 53 |
+
main_subject_mask = create_main_subject_mask(image)
|
| 54 |
+
|
| 55 |
+
# Apply mask to depth map: keep depth for main subject only, set background depth to zero
|
| 56 |
+
subject_depth_map = np.where(main_subject_mask == 255, depth_image, 0)
|
| 57 |
+
|
| 58 |
+
# Create inpainted background with OpenCV
|
| 59 |
+
inpainted_bg = inpaint_background(image, np.array(image_raw.resize((new_width, new_height))))
|
| 60 |
+
|
| 61 |
+
# Scale inpainted background slightly to fill view
|
| 62 |
+
inpainted_bg = cv2.resize(inpainted_bg, None, fx=1.05, fy=1.05, interpolation=cv2.INTER_LINEAR)
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
gltf_path = create_3d_obj(np.array(image), subject_depth_map, image_path, inpainted_bg, main_subject_offset=0.2)
|
| 66 |
+
img = Image.fromarray(subject_depth_map)
|
| 67 |
+
return [img, gltf_path, gltf_path]
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error reconstructing 3D model: {e}")
|
| 70 |
+
raise Exception("Error reconstructing 3D model")
|
| 71 |
+
|
| 72 |
+
def create_main_subject_mask(image):
|
| 73 |
+
"""Generates a binary mask for the main subject using rembg."""
|
| 74 |
+
# Remove background and create mask
|
| 75 |
+
subject_only = remove(image)
|
| 76 |
+
subject_mask = Image.fromarray((np.array(subject_only)[:, :, 3] > 0).astype(np.uint8) * 255)
|
| 77 |
+
return np.array(subject_mask)
|
| 78 |
+
|
| 79 |
+
def inpaint_background(image, original_image):
|
| 80 |
+
# Resize `image` to match `original_image` dimensions
|
| 81 |
+
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
| 82 |
+
|
| 83 |
+
# Convert to grayscale and create the mask in `uint8` format
|
| 84 |
+
mask = np.array(resized_image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
|
| 85 |
+
|
| 86 |
+
# Apply inpainting
|
| 87 |
+
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 88 |
+
return inpainted_image
|
| 89 |
|
| 90 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 91 |
try:
|
|
|
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
print(f"Error reconstructing 3D model: {e}")
|
| 150 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
| 153 |
description = (
|