Update app.py
Browse files
app.py
CHANGED
|
@@ -13,67 +13,61 @@ from rembg import remove
|
|
| 13 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 14 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 15 |
|
| 16 |
-
def
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# Apply offset to main subject for panorama effect
|
| 37 |
-
pcd.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.05], [0, 0, 0, 1]])
|
| 38 |
-
|
| 39 |
-
# Orient normals towards the camera
|
| 40 |
-
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 41 |
-
pcd.estimate_normals(
|
| 42 |
-
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 43 |
-
)
|
| 44 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
| 45 |
-
|
| 46 |
-
# Poisson reconstruction with a flat back surface
|
| 47 |
-
print("Starting Poisson reconstruction...")
|
| 48 |
-
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
|
| 49 |
-
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 50 |
-
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
if not mesh_raw.has_triangles():
|
| 54 |
-
raise ValueError("Poisson reconstruction failed: No triangles were created in the mesh.")
|
| 55 |
-
|
| 56 |
-
# Flatten the back surface of the main subject
|
| 57 |
-
for vertex in np.asarray(mesh_raw.vertices):
|
| 58 |
-
if vertex[2] < -0.05:
|
| 59 |
-
vertex[2] = -0.05
|
| 60 |
-
|
| 61 |
-
# Simplify the mesh while keeping details
|
| 62 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 63 |
-
mesh = mesh_raw.simplify_vertex_clustering(
|
| 64 |
-
voxel_size=voxel_size,
|
| 65 |
-
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
# Save model
|
| 69 |
-
gltf_path = f"./{image_path.stem}.gltf"
|
| 70 |
-
o3d.io.write_triangle_mesh(gltf_path, mesh, write_triangle_uvs=True)
|
| 71 |
-
print("3D model successfully reconstructed and saved.")
|
| 72 |
-
return gltf_path
|
| 73 |
-
|
| 74 |
except Exception as e:
|
| 75 |
-
print(f"Error
|
| 76 |
-
raise Exception("Error reconstructing 3D model")
|
| 77 |
|
| 78 |
def create_main_subject_mask(image):
|
| 79 |
"""Generates a binary mask for the main subject using rembg."""
|
|
@@ -152,8 +146,9 @@ def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
|
| 152 |
return gltf_path
|
| 153 |
|
| 154 |
except Exception as e:
|
| 155 |
-
print(f"Error
|
| 156 |
-
raise
|
|
|
|
| 157 |
|
| 158 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
| 159 |
description = (
|
|
|
|
| 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."""
|
|
|
|
| 146 |
return gltf_path
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
+
print(f"Error encountered: {e}")
|
| 150 |
+
raise Exception("Error reconstructing 3D model") from e
|
| 151 |
+
|
| 152 |
|
| 153 |
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
| 154 |
description = (
|