Update app.py
Browse files
app.py
CHANGED
|
@@ -8,32 +8,33 @@ from pathlib import Path
|
|
| 8 |
import os
|
| 9 |
import cv2
|
| 10 |
|
|
|
|
| 11 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 12 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 13 |
|
| 14 |
def process_image(image_path, depth_map_path=None):
|
| 15 |
image_path = Path(image_path)
|
| 16 |
image_raw = Image.open(image_path)
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
image = image_raw.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 22 |
|
| 23 |
if depth_map_path:
|
| 24 |
-
#
|
| 25 |
if depth_map_path.endswith(".npy"):
|
| 26 |
depth_image = np.load(depth_map_path)
|
|
|
|
| 27 |
else:
|
| 28 |
depth_image_raw = Image.open(depth_map_path)
|
| 29 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 30 |
depth_image = np.array(depth_image)
|
| 31 |
|
| 32 |
-
# Normalize depth
|
| 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 |
-
# Generate depth using DPT if
|
| 37 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 38 |
with torch.no_grad():
|
| 39 |
outputs = model(**encoding)
|
|
@@ -48,76 +49,75 @@ def process_image(image_path, depth_map_path=None):
|
|
| 48 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 49 |
|
| 50 |
# Create inpainted background with OpenCV
|
| 51 |
-
inpainted_bg = inpaint_background(image, np.array(image_raw
|
| 52 |
-
|
| 53 |
-
# Ensure depth_image matches final image dimensions
|
| 54 |
-
depth_image = Image.fromarray(depth_image).resize((new_width, new_height), Image.Resampling.NEAREST)
|
| 55 |
-
depth_image = np.array(depth_image)
|
| 56 |
|
| 57 |
try:
|
| 58 |
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, inpainted_bg)
|
| 59 |
img = Image.fromarray(depth_image)
|
| 60 |
return [img, gltf_path, gltf_path]
|
| 61 |
except Exception as e:
|
| 62 |
-
print(f"Error
|
| 63 |
raise Exception("Error reconstructing 3D model")
|
| 64 |
|
| 65 |
def inpaint_background(image, original_image):
|
| 66 |
-
# Resize
|
| 67 |
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
| 68 |
|
| 69 |
-
# Convert to grayscale
|
| 70 |
mask = np.array(resized_image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
|
| 71 |
|
| 72 |
-
# Apply inpainting
|
| 73 |
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 74 |
return inpainted_image
|
| 75 |
|
| 76 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
|
|
|
| 77 |
depth_o3d = o3d.geometry.Image(depth_image)
|
| 78 |
image_o3d = o3d.geometry.Image(rgb_image)
|
| 79 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 80 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 81 |
)
|
|
|
|
| 82 |
w, h = depth_image.shape[1], depth_image.shape[0]
|
| 83 |
|
|
|
|
| 84 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 85 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 86 |
|
|
|
|
| 87 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 88 |
|
| 89 |
-
#
|
|
|
|
|
|
|
|
|
|
| 90 |
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 91 |
pcd.estimate_normals(
|
| 92 |
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 93 |
)
|
| 94 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
| 95 |
-
pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
|
| 96 |
-
pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 97 |
|
| 98 |
-
# Poisson reconstruction
|
| 99 |
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
|
| 100 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 101 |
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 102 |
)
|
| 103 |
-
|
|
|
|
| 104 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 105 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 106 |
voxel_size=voxel_size,
|
| 107 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 108 |
)
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
mesh = mesh.filter_smooth_simple(number_of_iterations=3)
|
| 112 |
-
|
| 113 |
-
# Apply bounding box crop and save mesh
|
| 114 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 115 |
mesh_crop = mesh.crop(bbox)
|
| 116 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 117 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 118 |
return gltf_path
|
| 119 |
|
| 120 |
-
title = "3D Reconstruction with Panorama Background"
|
| 121 |
description = (
|
| 122 |
"Upload an RGB image and optionally a depth map (image or npy) to create a 3D model. "
|
| 123 |
"Background remains unchanged and un-cropped, with a panoramic effect for a more immersive experience."
|
|
@@ -140,5 +140,4 @@ iface = gr.Interface(
|
|
| 140 |
cache_examples=False,
|
| 141 |
)
|
| 142 |
|
| 143 |
-
|
| 144 |
iface.launch(debug=True, show_api=True, share=True)
|
|
|
|
| 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 |
def process_image(image_path, depth_map_path=None):
|
| 16 |
image_path = Path(image_path)
|
| 17 |
image_raw = Image.open(image_path)
|
| 18 |
+
image = image_raw.resize(
|
| 19 |
+
(1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
|
| 20 |
+
Image.Resampling.LANCZOS,
|
| 21 |
+
)
|
|
|
|
| 22 |
|
| 23 |
if depth_map_path:
|
| 24 |
+
# Load depth map from file, invert if needed
|
| 25 |
if depth_map_path.endswith(".npy"):
|
| 26 |
depth_image = np.load(depth_map_path)
|
| 27 |
+
depth_image = np.max(depth_image) - depth_image # Invert depth
|
| 28 |
else:
|
| 29 |
depth_image_raw = Image.open(depth_map_path)
|
| 30 |
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 31 |
depth_image = np.array(depth_image)
|
| 32 |
|
| 33 |
+
# Normalize the depth map to 0-255 range
|
| 34 |
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 35 |
depth_image = (depth_image * 255).astype('uint8')
|
| 36 |
else:
|
| 37 |
+
# Generate depth map using DPT if none is provided
|
| 38 |
encoding = feature_extractor(image, return_tensors="pt")
|
| 39 |
with torch.no_grad():
|
| 40 |
outputs = model(**encoding)
|
|
|
|
| 49 |
depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
|
| 50 |
|
| 51 |
# Create inpainted background with OpenCV
|
| 52 |
+
inpainted_bg = inpaint_background(image, np.array(image_raw))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
try:
|
| 55 |
gltf_path = create_3d_obj(np.array(image), depth_image, image_path, inpainted_bg)
|
| 56 |
img = Image.fromarray(depth_image)
|
| 57 |
return [img, gltf_path, gltf_path]
|
| 58 |
except Exception as e:
|
| 59 |
+
print(f"Error: {e}")
|
| 60 |
raise Exception("Error reconstructing 3D model")
|
| 61 |
|
| 62 |
def inpaint_background(image, original_image):
|
| 63 |
+
# Resize image to match the original background's dimensions
|
| 64 |
resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
|
| 65 |
|
| 66 |
+
# Convert to grayscale, then create a mask in `uint8` format for inpainting
|
| 67 |
mask = np.array(resized_image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
|
| 68 |
|
| 69 |
+
# Apply inpainting to fill background
|
| 70 |
inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
|
| 71 |
return inpainted_image
|
| 72 |
|
| 73 |
def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
|
| 74 |
+
# Create RGBD image in Open3D format
|
| 75 |
depth_o3d = o3d.geometry.Image(depth_image)
|
| 76 |
image_o3d = o3d.geometry.Image(rgb_image)
|
| 77 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 78 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 79 |
)
|
| 80 |
+
|
| 81 |
w, h = depth_image.shape[1], depth_image.shape[0]
|
| 82 |
|
| 83 |
+
# Set camera intrinsic parameters
|
| 84 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 85 |
camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
|
| 86 |
|
| 87 |
+
# Create a 3D point cloud from the RGBD image
|
| 88 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 89 |
|
| 90 |
+
# Offset main subject forward
|
| 91 |
+
pcd.transform([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.05], [0, 0, 0, 1]]) # Adjusted for panorama effect
|
| 92 |
+
|
| 93 |
+
# Orient normals towards the camera
|
| 94 |
pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
|
| 95 |
pcd.estimate_normals(
|
| 96 |
search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
|
| 97 |
)
|
| 98 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
# Poisson reconstruction with a flat back surface
|
| 101 |
with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
|
| 102 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 103 |
pcd, depth=depth, width=0, scale=1.1, linear_fit=True
|
| 104 |
)
|
| 105 |
+
|
| 106 |
+
# Keep a flat back surface, simplify the model
|
| 107 |
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
|
| 108 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 109 |
voxel_size=voxel_size,
|
| 110 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
| 111 |
)
|
| 112 |
|
| 113 |
+
# Apply a bounding box crop and save the model
|
|
|
|
|
|
|
|
|
|
| 114 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 115 |
mesh_crop = mesh.crop(bbox)
|
| 116 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 117 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 118 |
return gltf_path
|
| 119 |
|
| 120 |
+
title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
|
| 121 |
description = (
|
| 122 |
"Upload an RGB image and optionally a depth map (image or npy) to create a 3D model. "
|
| 123 |
"Background remains unchanged and un-cropped, with a panoramic effect for a more immersive experience."
|
|
|
|
| 140 |
cache_examples=False,
|
| 141 |
)
|
| 142 |
|
|
|
|
| 143 |
iface.launch(debug=True, show_api=True, share=True)
|