Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,8 @@ import cv2
|
|
| 12 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 13 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 14 |
|
|
|
|
|
|
|
| 15 |
def process_image(image_path, depth_map_path=None):
|
| 16 |
image_path = Path(image_path)
|
| 17 |
image_raw = Image.open(image_path)
|
|
@@ -25,21 +27,14 @@ def process_image(image_path, depth_map_path=None):
|
|
| 25 |
# Determine if depth map is npy or image format
|
| 26 |
if depth_map_path.endswith(".npy"):
|
| 27 |
depth_image = np.load(depth_map_path)
|
| 28 |
-
|
| 29 |
-
# Invert depth map for .npy format
|
| 30 |
-
depth_image = np.max(depth_image) - depth_image
|
| 31 |
-
|
| 32 |
-
# Normalize depth values
|
| 33 |
-
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 34 |
-
depth_image = (depth_image * 255).astype('uint8')
|
| 35 |
else:
|
| 36 |
depth_image_raw = Image.open(depth_map_path)
|
| 37 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 38 |
depth_image = np.array(depth_image)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
else:
|
| 44 |
# Generate depth using DPT if not provided
|
| 45 |
encoding = feature_extractor(image, return_tensors="pt")
|
|
@@ -55,21 +50,33 @@ def process_image(image_path, depth_map_path=None):
|
|
| 55 |
).squeeze()
|
| 56 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Create inpainted background with OpenCV
|
| 59 |
inpainted_bg = inpaint_background(image, np.array(image_raw.resize((new_width, new_height))))
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
depth_image = np.array(depth_image)
|
| 64 |
|
| 65 |
try:
|
| 66 |
-
gltf_path = create_3d_obj(np.array(image),
|
| 67 |
-
img = Image.fromarray(
|
| 68 |
return [img, gltf_path, gltf_path]
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Error reconstructing 3D model: {e}")
|
| 71 |
raise Exception("Error reconstructing 3D model")
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
def inpaint_background(image, original_image):
|
| 74 |
# Resize `image` to match `original_image` dimensions
|
| 75 |
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
|
@@ -80,7 +87,6 @@ def inpaint_background(image, original_image):
|
|
| 80 |
# Apply inpainting
|
| 81 |
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 82 |
return inpainted_image
|
| 83 |
-
|
| 84 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 85 |
# Create RGBD image in Open3D format
|
| 86 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
@@ -98,8 +104,8 @@ def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
|
| 98 |
# Create a 3D point cloud from the RGBD image
|
| 99 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
pcd.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.05], [0, 0, 0, 1]])
|
| 103 |
|
| 104 |
# Orient normals towards the camera
|
| 105 |
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
|
@@ -114,18 +120,21 @@ def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
|
| 114 |
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 115 |
)
|
| 116 |
|
| 117 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 119 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 120 |
voxel_size=voxel_size,
|
| 121 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 122 |
)
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
bbox = pcd.get_axis_aligned_bounding_box()
|
| 126 |
-
mesh_crop = mesh.crop(bbox)
|
| 127 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 128 |
-
o3d.io.write_triangle_mesh(gltf_path,
|
| 129 |
return gltf_path
|
| 130 |
|
| 131 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
|
|
|
| 12 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 13 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 14 |
|
| 15 |
+
from rembg import remove
|
| 16 |
+
|
| 17 |
def process_image(image_path, depth_map_path=None):
|
| 18 |
image_path = Path(image_path)
|
| 19 |
image_raw = Image.open(image_path)
|
|
|
|
| 27 |
# Determine if depth map is npy or image format
|
| 28 |
if depth_map_path.endswith(".npy"):
|
| 29 |
depth_image = np.load(depth_map_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
else:
|
| 31 |
depth_image_raw = Image.open(depth_map_path)
|
| 32 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 33 |
depth_image = np.array(depth_image)
|
| 34 |
|
| 35 |
+
# Normalize depth if needed
|
| 36 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 37 |
+
depth_image = (depth_image * 255).astype('uint8')
|
| 38 |
else:
|
| 39 |
# Generate depth using DPT if not provided
|
| 40 |
encoding = feature_extractor(image, return_tensors="pt")
|
|
|
|
| 50 |
).squeeze()
|
| 51 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 52 |
|
| 53 |
+
# Create a mask of the main subject using rembg
|
| 54 |
+
main_subject_mask = create_main_subject_mask(image)
|
| 55 |
+
|
| 56 |
+
# Apply mask to depth map: keep depth for main subject only, set background depth to zero
|
| 57 |
+
subject_depth_map = np.where(main_subject_mask == 255, depth_image, 0)
|
| 58 |
+
|
| 59 |
# Create inpainted background with OpenCV
|
| 60 |
inpainted_bg = inpaint_background(image, np.array(image_raw.resize((new_width, new_height))))
|
| 61 |
|
| 62 |
+
# Scale inpainted background slightly to fill view
|
| 63 |
+
inpainted_bg = cv2.resize(inpainted_bg, None, fx=1.05, fy=1.05, interpolation=cv2.INTER_LINEAR)
|
|
|
|
| 64 |
|
| 65 |
try:
|
| 66 |
+
gltf_path = create_3d_obj(np.array(image), subject_depth_map, image_path, inpainted_bg, main_subject_offset=0.2)
|
| 67 |
+
img = Image.fromarray(subject_depth_map)
|
| 68 |
return [img, gltf_path, gltf_path]
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Error reconstructing 3D model: {e}")
|
| 71 |
raise Exception("Error reconstructing 3D model")
|
| 72 |
|
| 73 |
+
def create_main_subject_mask(image):
|
| 74 |
+
"""Generates a binary mask for the main subject using rembg."""
|
| 75 |
+
# Remove background and create mask
|
| 76 |
+
subject_only = remove(image)
|
| 77 |
+
subject_mask = Image.fromarray((np.array(subject_only)[:, :, 3] > 0).astype(np.uint8) * 255)
|
| 78 |
+
return np.array(subject_mask)
|
| 79 |
+
|
| 80 |
def inpaint_background(image, original_image):
|
| 81 |
# Resize `image` to match `original_image` dimensions
|
| 82 |
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
|
|
|
| 87 |
# Apply inpainting
|
| 88 |
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 89 |
return inpainted_image
|
|
|
|
| 90 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 91 |
# Create RGBD image in Open3D format
|
| 92 |
depth_o3d = o3d.geometry.Image(depth_image)
|
|
|
|
| 104 |
# Create a 3D point cloud from the RGBD image
|
| 105 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 106 |
|
| 107 |
+
# Apply offset to main subject for panorama effect
|
| 108 |
+
pcd.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.05], [0, 0, 0, 1]])
|
| 109 |
|
| 110 |
# Orient normals towards the camera
|
| 111 |
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
|
|
|
| 120 |
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 121 |
)
|
| 122 |
|
| 123 |
+
# Flatten the back surface of the main subject
|
| 124 |
+
for vertex in np.asarray(mesh_raw.vertices):
|
| 125 |
+
if vertex[2] < -0.05: # Adjust based on the desired flatness level
|
| 126 |
+
vertex[2] = -0.05
|
| 127 |
+
|
| 128 |
+
# Simplify the mesh while keeping details
|
| 129 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 130 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 131 |
voxel_size=voxel_size,
|
| 132 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 133 |
)
|
| 134 |
|
| 135 |
+
# Remove bounding box crop to preserve background at full size
|
|
|
|
|
|
|
| 136 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 137 |
+
o3d.io.write_triangle_mesh(gltf_path, mesh, write_triangle_uvs=True)
|
| 138 |
return gltf_path
|
| 139 |
|
| 140 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|