File size: 8,979 Bytes
572fff2
2c5d8ea
202510d
 
9348575
8f5830b
932c3e0
ba672d1
f463c64
7fe26c4
3588283
 
 
202510d
35a9d43
572fff2
c53c092
de7156a
18951ff
6255974
35a9d43
 
 
 
 
18951ff
35a9d43
 
 
6255974
ddf5562
 
 
 
 
 
35a9d43
6255974
35a9d43
6255974
466f88e
6255974
35a9d43
6255974
 
 
35a9d43
6255974
152e057
6255974
35a9d43
 
6255974
 
 
 
 
 
 
 
 
 
152e057
 
6255974
3588283
35a9d43
ddf5562
35a9d43
ddf5562
 
 
 
 
6255974
3588283
fa6bffd
 
466f88e
 
3588283
 
fa6bffd
ddf5562
 
 
 
 
6255974
ddf5562
 
cc940b9
6255974
35a9d43
ddf5562
 
cc940b9
35a9d43
fa6bffd
152e057
 
 
a3c5d97
5e58814
fa6bffd
5e58814
ddf5562
 
5e58814
 
ddf5562
ba4f35f
 
 
 
 
babed9f
 
152e057
a3c5d97
152e057
 
 
 
 
fa6bffd
413b1a7
 
5e58814
 
 
 
babed9f
413b1a7
babed9f
ba4f35f
babed9f
ba4f35f
 
 
5e58814
babed9f
5e58814
ba4f35f
5e58814
 
babed9f
a3c5d97
 
 
5e58814
a3c5d97
 
 
35a9d43
a3c5d97
5e58814
 
 
674c30c
ba4f35f
 
 
 
a3c5d97
fa6bffd
5e58814
 
 
 
fa6bffd
466f88e
a3c5d97
cc940b9
 
5fcdff5
cc940b9
 
 
 
 
674c30c
cc940b9
a3c5d97
eac0fd7
 
 
 
 
f5d7995
 
 
0b853b9
450d66c
f5d7995
eac0fd7
450d66c
0b853b9
f5d7995
 
 
0b853b9
f5d7995
 
 
 
 
0b853b9
f5d7995
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import gradio as gr
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
import torch
import numpy as np
from PIL import Image
import open3d as o3d
from pathlib import Path
import os
import cv2
from rembg import remove
from skimage import img_as_ubyte
from skimage.filters import gaussian
from skimage.segmentation import clear_border

# Initialize model and feature extractor for depth estimation
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")

def process_image(image_path, depth_map_path=None):
    image_path = Path(image_path)
    image_raw = Image.open(image_path).convert("RGB")
    image = image_raw.resize(
        (2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
        Image.Resampling.LANCZOS,
    )

    # Remove background using rembg
    foreground = remove(image_raw)
    foreground = Image.fromarray(np.array(foreground)).convert("RGB")

    # Create a binary mask of the foreground
    foreground_edges = cv2.Canny(np.array(foreground), 100, 200)

    # Resize foreground edges to match depth image dimensions
    foreground_edges_resized = cv2.resize(foreground_edges, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)

    # Check if user-provided depth map is available
    if depth_map_path:
        if depth_map_path.endswith('.npy'):
            depth_image = np.load(depth_map_path)
            depth_image = 1 - depth_image  # Invert depth only for npy files
        else:
            depth_image_raw = Image.open(depth_map_path).convert("L")
            depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
            depth_image = np.array(depth_image)

        # Normalize depth image
        depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
        depth_image = depth_image.astype('float32')  # Directly convert to float32
    else:
        # Generate depth map using DPT model
        encoding = feature_extractor(foreground, return_tensors="pt")
        with torch.no_grad():
            outputs = model(**encoding)
            predicted_depth = outputs.predicted_depth

        prediction = torch.nn.functional.interpolate(
            predicted_depth.unsqueeze(1),
            size=image.size[::-1],
            mode="bicubic",
            align_corners=False,
        ).squeeze()
        depth_image = (prediction.cpu().numpy() - np.min(prediction.cpu().numpy())) / (np.max(prediction.cpu().numpy()) - np.min(prediction.cpu().numpy()))  # Normalize depth values
        depth_image = depth_image.astype("float32")  # Changed to float32

    # Resize and apply Gaussian smoothing for smoother transitions
    depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
    mask_blurred = cv2.GaussianBlur(depth_image, (5, 5), 1.0)

    # Blend depth_image with mask_blurred for smoother transition
    blended_depth_image = cv2.addWeighted(depth_image, 0.7, mask_blurred, 0.3, 0)

    # Sharpen subject edges slightly
    depth_image[foreground_edges_resized > 0] = depth_image[foreground_edges_resized > 0] * 1.2

    # Inpaint background where the main subject was removed
    background = remove(image_raw, only_mask=True)
    background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
    background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=5, flags=cv2.INPAINT_TELEA)

    # Scale up background to prevent cropping and maintain colors
    bg_scaled = cv2.resize(background_inpainted, (int(image.width * 1.2), int(image.height * 1.2)))

    # Optionally, adjust the foreground position and flatten the back
    foreground_flat = np.array(foreground)
    foreground_flat = foreground_flat[:, :, :3]  # Keep only RGB channels
    foreground_flat = np.insert(foreground_flat, 2, values=0, axis=2)  # Add a zero channel for depth

    try:
        gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path)
        img = Image.fromarray(blended_depth_image)
        return [img, gltf_path]
    except Exception as e:
        print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
        gltf_path = create_3d_obj(foreground_flat, blended_depth_image, bg_scaled, image_path, depth=9)
        img = Image.fromarray(blended_depth_image)
        return [img, gltf_path]

def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
    # Resize background to match the original image size (no cropping)
    background_resized = cv2.resize(background, (foreground.shape[1], foreground.shape[0]), interpolation=cv2.INTER_LINEAR)

    # Resize and normalize the depth image
    depth_image_resized = np.array(
        Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
    )

    # Normalize depth for float32 representation
    depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
        depth_image_resized.max() - depth_image_resized.min()
    )

    # Ensure depth image is valid
    if np.all(depth_image_normalized == 0):
        raise RuntimeError("Depth image normalization resulted in all zeros.")

    depth_image_normalized = depth_image_normalized.astype(np.float32)

    # Create flat background depth with a small gap for empty space
    background_depth = np.zeros_like(depth_image_normalized) + 1.5

    # Combine depths to create the illusion of an empty space
    combined_depth = np.maximum(depth_image_normalized * 0.5, background_depth)

    depth_o3d = o3d.geometry.Image(combined_depth)
    image_o3d = o3d.geometry.Image(foreground)
    
    # Create RGBD image directly without using width and height
    rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
        image_o3d, depth_o3d, convert_rgb_to_intensity=False
    )

    # Get dimensions of the rgbd_image
    rgbd_width, rgbd_height = rgbd_image.color.shape[1], rgbd_image.color.shape[0]

    # Check if the depth and foreground sizes are compatible
    if rgbd_width != foreground.shape[1] or rgbd_height != foreground.shape[0]:
        raise RuntimeError("RGBD image dimensions do not match foreground dimensions.")

    # Camera intrinsic setup
    camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
    camera_intrinsic.set_intrinsics(rgbd_width, rgbd_height, 1500, 1500, rgbd_width / 2, rgbd_height / 2)

    # Create the point cloud
    pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)

    # Check if the point cloud is valid
    print(f"Point Cloud Size: {len(pcd.points)}")
    if len(pcd.points) < 100:
        raise RuntimeError("Insufficient points in the point cloud for normals estimation.")

    # Estimate normals and orient
    pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
    pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))

    # Generate 3D mesh using Poisson reconstruction
    mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
        pcd, depth=depth, width=0, scale=1.2, linear_fit=True
    )

    # Validate mesh creation
    if not mesh_raw.has_triangles():
        raise RuntimeError("No triangles found in the generated mesh. Check the point cloud data.")

    # Simplify and smooth the mesh
    voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
    mesh = mesh_raw.simplify_vertex_clustering(
        voxel_size=voxel_size,
        contraction=o3d.geometry.SimplificationContraction.Average,
    )
    mesh = mesh.filter_smooth_simple(number_of_iterations=3)

    # Validate the mesh before cropping
    if mesh.is_empty():
        raise RuntimeError("The mesh is empty after processing.")

    # Save mesh to GLTF format
    output_dir = Path("output")
    output_dir.mkdir(parents=True, exist_ok=True)
    gltf_path = output_dir / f"{image_path.stem}.gltf"
    o3d.io.write_triangle_mesh(str(gltf_path), mesh)

    return str(gltf_path)


# Gradio Interface
title = "Depth Estimation & 3D Reconstruction Demo"
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."

examples = [["examples/" + img] for img in os.listdir("examples/")]

iface = gr.Interface(
    fn=process_image,
    inputs=[
        gr.Image(type="filepath", label="Input Image"),
        gr.File(type="filepath", label="Input Depth Map (optional)"),
    ],
    outputs=[
        gr.Image(label="Predicted Depth", type="pil"),
        gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
        gr.File(label="3D gLTF File"),
    ],
    title=title,
    description=description,
    examples=examples,
    allow_flagging="never",
    cache_examples=False,
)
iface.launch(debug=True, show_api=True, share=True)