Update app.py
Browse files
app.py
CHANGED
|
@@ -16,6 +16,25 @@ from skimage.segmentation import clear_border
|
|
| 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")
|
|
@@ -44,9 +63,8 @@ def process_image(image_path, depth_map_path=None):
|
|
| 44 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 45 |
depth_image = np.array(depth_image)
|
| 46 |
|
| 47 |
-
# Normalize depth image
|
| 48 |
-
depth_image = (depth_image
|
| 49 |
-
depth_image = depth_image.astype('float32') # Directly convert to float32
|
| 50 |
else:
|
| 51 |
# Generate depth map using DPT model
|
| 52 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
@@ -61,7 +79,7 @@ def process_image(image_path, depth_map_path=None):
|
|
| 61 |
align_corners=False,
|
| 62 |
).squeeze()
|
| 63 |
depth_image = (prediction.cpu().numpy() - np.min(prediction.cpu().numpy())) / (np.max(prediction.cpu().numpy()) - np.min(prediction.cpu().numpy())) # Normalize depth values
|
| 64 |
-
depth_image =
|
| 65 |
|
| 66 |
# Resize and apply Gaussian smoothing for smoother transitions
|
| 67 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
|
@@ -73,10 +91,14 @@ def process_image(image_path, depth_map_path=None):
|
|
| 73 |
# Sharpen subject edges slightly
|
| 74 |
depth_image[foreground_edges_resized > 0] = depth_image[foreground_edges_resized > 0] * 1.2
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
# Inpaint background where the main subject was removed
|
| 77 |
background = remove(image_raw, only_mask=True)
|
| 78 |
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 79 |
-
background_inpainted =
|
| 80 |
|
| 81 |
# Scale up background to prevent cropping and maintain colors
|
| 82 |
bg_scaled = cv2.resize(background_inpainted, (int(image.width * 1.2), int(image.height * 1.2)))
|
|
@@ -158,59 +180,26 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
|
| 158 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 159 |
|
| 160 |
# Estimate normals and orient
|
| 161 |
-
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.
|
| 162 |
-
pcd.orient_normals_towards_camera_location(camera_location=np.array([0
|
| 163 |
|
| 164 |
-
#
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
if not mesh_raw.has_triangles():
|
| 171 |
-
raise RuntimeError("No triangles found in the generated mesh. Check the point cloud data.")
|
| 172 |
-
|
| 173 |
-
# Simplify and smooth the mesh
|
| 174 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 175 |
-
mesh = mesh_raw.simplify_vertex_clustering(
|
| 176 |
-
voxel_size=voxel_size,
|
| 177 |
-
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 178 |
-
)
|
| 179 |
-
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 180 |
-
|
| 181 |
-
# Validate the mesh before cropping
|
| 182 |
-
if mesh.is_empty():
|
| 183 |
-
raise RuntimeError("The mesh is empty after processing.")
|
| 184 |
-
|
| 185 |
-
# Save mesh to GLTF format
|
| 186 |
-
output_dir = Path("output")
|
| 187 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
| 188 |
-
gltf_path = output_dir / f"{image_path.stem}.gltf"
|
| 189 |
-
o3d.io.write_triangle_mesh(str(gltf_path), mesh)
|
| 190 |
-
|
| 191 |
-
return str(gltf_path)
|
| 192 |
|
| 193 |
# Gradio Interface
|
| 194 |
-
|
| 195 |
-
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."
|
| 196 |
-
|
| 197 |
-
examples = [["examples/" + img] for img in os.listdir("examples/")]
|
| 198 |
-
|
| 199 |
-
iface = gr.Interface(
|
| 200 |
fn=process_image,
|
| 201 |
inputs=[
|
| 202 |
-
gr.Image(type="filepath", label="Input Image"),
|
| 203 |
-
gr.File(
|
| 204 |
],
|
| 205 |
outputs=[
|
| 206 |
-
gr.Image(label="
|
| 207 |
-
gr.
|
| 208 |
-
gr.File(label="3D gLTF File"),
|
| 209 |
],
|
| 210 |
-
title=
|
| 211 |
-
description=
|
| 212 |
-
|
| 213 |
-
allow_flagging="never",
|
| 214 |
-
cache_examples=False,
|
| 215 |
-
)
|
| 216 |
-
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 16 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 17 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 18 |
|
| 19 |
+
def normalize_depth_image(depth_image):
|
| 20 |
+
depth_image_min = np.min(depth_image)
|
| 21 |
+
depth_image_max = np.max(depth_image)
|
| 22 |
+
normalized_image = (depth_image - depth_image_min) / (depth_image_max - depth_image_min)
|
| 23 |
+
return normalized_image
|
| 24 |
+
|
| 25 |
+
def process_depth_image(depth_image):
|
| 26 |
+
# Normalize depth image
|
| 27 |
+
normalized_depth_image = normalize_depth_image(depth_image)
|
| 28 |
+
|
| 29 |
+
# Apply Gaussian smoothing to normalized depth image
|
| 30 |
+
smoothed_depth_image = gaussian(normalized_depth_image, sigma=1.0) # Adjust sigma for smoothness
|
| 31 |
+
return smoothed_depth_image
|
| 32 |
+
|
| 33 |
+
def inpaint_background(original_image, mask):
|
| 34 |
+
# Inpainting to fill the background
|
| 35 |
+
inpainted_image = cv2.inpaint(original_image, mask.astype(np.uint8), inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 36 |
+
return inpainted_image
|
| 37 |
+
|
| 38 |
def process_image(image_path, depth_map_path=None):
|
| 39 |
image_path = Path(image_path)
|
| 40 |
image_raw = Image.open(image_path).convert("RGB")
|
|
|
|
| 63 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 64 |
depth_image = np.array(depth_image)
|
| 65 |
|
| 66 |
+
# Normalize and process the depth image
|
| 67 |
+
depth_image = process_depth_image(depth_image) # Apply processing
|
|
|
|
| 68 |
else:
|
| 69 |
# Generate depth map using DPT model
|
| 70 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
|
|
|
| 79 |
align_corners=False,
|
| 80 |
).squeeze()
|
| 81 |
depth_image = (prediction.cpu().numpy() - np.min(prediction.cpu().numpy())) / (np.max(prediction.cpu().numpy()) - np.min(prediction.cpu().numpy())) # Normalize depth values
|
| 82 |
+
depth_image = process_depth_image(depth_image) # Apply processing
|
| 83 |
|
| 84 |
# Resize and apply Gaussian smoothing for smoother transitions
|
| 85 |
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
|
|
|
| 91 |
# Sharpen subject edges slightly
|
| 92 |
depth_image[foreground_edges_resized > 0] = depth_image[foreground_edges_resized > 0] * 1.2
|
| 93 |
|
| 94 |
+
# Create mask for the main subject
|
| 95 |
+
mask = (depth_image > 0).astype(np.uint8) # Create a binary mask for the subject
|
| 96 |
+
mask = clear_border(mask) # Clear objects touching the border
|
| 97 |
+
|
| 98 |
# Inpaint background where the main subject was removed
|
| 99 |
background = remove(image_raw, only_mask=True)
|
| 100 |
background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
|
| 101 |
+
background_inpainted = inpaint_background(np.array(image_raw), mask)
|
| 102 |
|
| 103 |
# Scale up background to prevent cropping and maintain colors
|
| 104 |
bg_scaled = cv2.resize(background_inpainted, (int(image.width * 1.2), int(image.height * 1.2)))
|
|
|
|
| 180 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 181 |
|
| 182 |
# Estimate normals and orient
|
| 183 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))
|
| 184 |
+
pcd.orient_normals_towards_camera_location(camera_location=np.array([0, 0, 0]))
|
| 185 |
|
| 186 |
+
# Save the point cloud to a GLB file
|
| 187 |
+
output_path = os.path.join(Path(image_path).parent, "3D_Model.glb")
|
| 188 |
+
o3d.io.write_triangle_mesh(output_path, pcd)
|
|
|
|
| 189 |
|
| 190 |
+
return output_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
# Gradio Interface
|
| 193 |
+
gr.Interface(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
fn=process_image,
|
| 195 |
inputs=[
|
| 196 |
+
gr.inputs.Image(type="filepath", label="Input Image"),
|
| 197 |
+
gr.inputs.File(label="Depth Map (optional, .npy or image)"),
|
| 198 |
],
|
| 199 |
outputs=[
|
| 200 |
+
gr.outputs.Image(label="Processed Depth Image"),
|
| 201 |
+
gr.outputs.File(label="3D Model (GLB)"),
|
|
|
|
| 202 |
],
|
| 203 |
+
title="3D Reconstruction with Depth Estimation",
|
| 204 |
+
description="Upload an image and optionally a depth map to generate a 3D model."
|
| 205 |
+
).launch()
|
|
|
|
|
|
|
|
|
|
|
|