File size: 15,212 Bytes
39c2c70
2c4e85f
202510d
4e9eaed
08736fe
79678f7
29119a7
79678f7
458a255
f7e7eba
78ce055
6613883
6a63980
0c6da48
 
 
fd48885
d305080
 
 
 
 
 
 
 
 
 
5d5b492
6b69d1e
e48bdc5
 
 
dad1a22
e48bdc5
0c6da48
e48bdc5
 
 
 
 
d305080
dad1a22
 
 
 
 
 
 
 
0c6da48
 
dad1a22
 
 
 
6b69d1e
dad1a22
 
 
 
d305080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd48885
379fc1f
dad1a22
 
 
 
 
 
fd48885
 
 
 
 
d7a7118
fd48885
dad1a22
 
 
 
d7a7118
 
 
 
 
 
dad1a22
 
 
2ab071c
 
dad1a22
 
 
 
 
 
 
 
 
 
 
 
d7a7118
 
 
 
 
dad1a22
 
d7a7118
a9b7776
caa521c
 
 
 
a9b7776
d7a7118
a9b7776
 
d7a7118
 
 
 
 
 
 
caa521c
a9b7776
c5a3fca
a9b7776
 
 
d7a7118
a9b7776
dad1a22
 
a9b7776
dad1a22
d7a7118
dad1a22
 
d7a7118
dad1a22
 
d7a7118
 
 
 
 
 
 
 
c152bc0
6a63980
d7a7118
fd48885
d7a7118
fd48885
d7a7118
fd48885
 
 
d7a7118
fd48885
966bb2a
d7a7118
 
966bb2a
 
d7a7118
 
 
 
dad1a22
69a0f41
dad1a22
 
fd48885
dad1a22
 
fd48885
dad1a22
 
 
 
d7a7118
dad1a22
 
caa521c
dad1a22
 
 
fd48885
2ab071c
 
cc0aabd
31da0af
ba13d9d
 
d7a7118
ba13d9d
d7a7118
 
caa521c
 
 
 
d7a7118
ba13d9d
6a63980
d7a7118
 
 
 
 
cc0aabd
0c6da48
cc0aabd
0c6da48
4420c39
0c6da48
 
31da0af
dad1a22
31da0af
0c6da48
d7a7118
8b7c07f
2b2708a
d7a7118
 
1e8ea34
 
a491b20
 
 
 
 
 
d7a7118
 
 
 
 
dad1a22
2ab071c
 
 
 
9bceed7
2b2708a
dad1a22
d7a7118
6a63980
 
d7a7118
6a63980
 
6613883
966bb2a
2ab071c
2b2708a
2ab071c
d7a7118
 
 
 
 
9bceed7
2ab071c
d7a7118
 
31da0af
d7a7118
f7e7eba
966bb2a
9bceed7
 
 
 
 
 
d7a7118
f7e7eba
966bb2a
2ab071c
 
d7a7118
78ce055
966bb2a
2ab071c
9bceed7
2ab071c
d7a7118
2ab071c
966bb2a
2ab071c
 
2b2708a
2ab071c
d7a7118
2ab071c
966bb2a
2ab071c
 
 
d7a7118
2ab071c
 
f7e7eba
5e4bf2c
2ab071c
887a4ad
dad1a22
 
 
 
 
966bb2a
dad1a22
966bb2a
dad1a22
 
 
2ab071c
966bb2a
cc0aabd
dad1a22
 
966bb2a
dad1a22
 
 
 
 
0b853b9
458a255
f7e7eba
cce4ce7
8b7c07f
 
cce4ce7
458a255
 
0c6da48
0b853b9
78ce055
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import gradio as gr
import diffusers
import torch
from PIL import Image
import numpy as np
import cv2
import os
from rembg import remove
import open3d as o3d
import tempfile
from skimage import filters
import gc
from scipy.ndimage import sobel
import os
import torch
import diffusers

# Handle GPU availability in Hugging Face Spaces with ZeroGPU
if os.environ.get("SPACES_ZERO_GPU") is not None:
    import spaces
else:
    class spaces:
        @staticmethod
        def GPU(func):
            def wrapper(*args, **kwargs):
                return func(*args, **kwargs)
            return wrapper


# Check if CUDA is available
if torch.cuda.is_available():
    print("CUDA is available")
else:
    print("CUDA is not available")

# Set device (GPU or CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Reset CUDA environment
torch.cuda.empty_cache()

try:
    print("Loading depth pipeline...")
    pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
        "prs-eth/marigold-depth-lcm-v1-0",
        variant="fp16",
        torch_dtype=torch.float16
    ).to(device)
    print("Pipeline loaded successfully.")
    
    # Load the custom VAE
    print("Loading custom VAE...")
    pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
        "madebyollin/taesd",
        torch_dtype=torch.float16
    ).to(device)
    print("Custom VAE loaded.")
except Exception as e:
    print(f"Error loading depth pipeline: {type(e).__name__} - {e}")
    raise
# # Enable XFormers if using GPU
# if device.type == "cuda":
#     try:
#         from xformers.ops import memory_efficient_attention
#         print("xformers is installed and operational!")
#         print("Enabling XFormers...")
#         pipe.enable_xformers_memory_efficient_attention()
#         print("XFormers enabled.")
#     except AttributeError:
#         print("XFormers is not supported in the installed version of diffusers or model.")
#     except ImportError:
#         print("XFormers library is not installed. Run `pip install xformers`.")
#     except Exception as e:
#         print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
# else:
#     print("XFormers not enabled as the device is CPU.")

@spaces.GPU(enable_queue=True)
def predict_depth(image: Image.Image):
    """Predict depth from an image and return refined depth map."""
    try:
        print("Processing input image...")
        image = image.convert("RGB")

        # Resize image if larger than 2K
        if max(image.size) > 2000:
            scale_factor = 2000 / max(image.size)
            new_size = (int(image.size[0] * scale_factor), int(image.size[1] * scale_factor))
            image = image.resize(new_size, Image.LANCZOS)
            print(f"Image resized to {new_size}")

        # Step 1: Remove background to isolate the main subject
        print("Removing background...")
        foreground = remove(image)
        foreground = Image.fromarray(np.array(foreground)).convert("RGB")
        print("Background removal completed.")

        # Save foreground for debugging
        foreground_debug_path = "debug_foreground.png"
        foreground.save(foreground_debug_path)
        print(f"Foreground saved at {foreground_debug_path}")

        # Depth prediction
        print("Predicting depth...")
        ensemble_size = 30
        num_inference_steps = 5  # Optimized for LCM Scheduler
        depth = pipe(
            foreground,
            ensemble_size=ensemble_size,
            num_inference_steps=num_inference_steps,
            output_uncertainty=True
        )
        print("Depth prediction completed.")

        # Export depth as a 16-bit PNG
        depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
        depth_16bit_image = depth_16bit[0]

        # Save depth map as 16-bit PNG for debugging
        depth_16bit_debug_path = "debug_depth_16bit.png"
        depth_16bit_image.save(depth_16bit_debug_path)
        print(f"Depth map saved at {depth_16bit_debug_path}")

        # Convert depth map to float for filtering
        depth_array = np.array(depth_16bit_image, dtype=np.float32)
        print(f"Depth map converted to array with shape {depth_array.shape}")

        # Validate depth map dimensions
        if depth_array.size == 0:
            raise ValueError("Depth map is empty or invalid.")

        # Step 2: Refine depth map using bilateral and edge-aware filters
        print("Refining depth map with bilateral filter...")
        depth_bilateral = cv2.bilateralFilter((depth_array / 65535 * 255).astype(np.uint8), d=12, sigmaColor=90, sigmaSpace=90)
        depth_bilateral = depth_bilateral.astype(np.float32) / 255 * 65535  # Back to 16-bit scale
        print("Bilateral filtering completed.")

        # Visualize bilateral filtered depth map
        bilateral_debug_path = "debug_bilateral_depth.png"
        Image.fromarray((depth_bilateral / 65535 * 255).astype(np.uint8)).save(bilateral_debug_path)
        print(f"Bilateral filtered depth map saved at {bilateral_debug_path}")

        # Apply Laplacian sharpening
        laplacian = cv2.Laplacian(depth_bilateral, cv2.CV_32F)
        depth_sharpened = cv2.addWeighted(depth_bilateral, 1.6, laplacian, -0.5, 0)

        # Normalize to 16-bit for consistent scaling
        depth_normalized = cv2.normalize(depth_sharpened, None, 0, 65535, cv2.NORM_MINMAX, dtype=cv2.CV_16U)
        print("Depth sharpening and normalization completed.")

        # Resize depth map to match the foreground size
        depth_resized = cv2.resize(
            depth_normalized, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4
        )
        print(f"Depth map resized to match foreground: {depth_resized.shape}")

        # Apply a foreground mask
        print("Applying foreground mask to depth map...")
        mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
        depth_subject_only = np.where(mask, depth_resized, 0)
        print("Foreground mask applied.")

        # Visualize depth map with mask applied
        masked_debug_path = "debug_masked_depth.png"
        Image.fromarray((depth_subject_only / 65535 * 255).astype(np.uint8)).save(masked_debug_path)
        print(f"Masked depth map saved at {masked_debug_path}")

        # Convert to float depth map for further processing
        depth_image_cleaned = depth_subject_only
        depth_image = depth_image_cleaned.astype(np.float32) / 255

        # Step 3: Smooth depth map with Gaussian filter
        print("Smoothing depth map with Gaussian filter...")
        depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
        print("Gaussian smoothing completed.")

        # Step 4: Bilateral filter for detail preservation
        depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
        print("Final bilateral filtering completed.")

        # Step 5: Resize the depth map to match the foreground size
        depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4)
        print("Depth map resized to final dimensions.")

        # Step 6: Create an edge-aware mask (if needed for further processing)
        mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
        depth_image[~mask] = 0
        print("Edge-aware mask applied to depth map.")

        # Keep a non-inverted depth for mesh processing
        depth_non_inverted = depth_image.copy()

        # Invert the depth map for display
        depth_image = 1.0 - depth_image

        # Generate normalized depth for visualization
        depth_display = np.clip(depth_image * 255, 0, 255).astype(np.uint8)  # 8-bit display

        # Save visualizations
        depth_image_path = "depth_image.png"
        Image.fromarray(depth_display).save(depth_image_path)
        print(f"Depth display saved at {depth_image_path}")

        # Return both non-inverted and inverted depths
        return depth_non_inverted, depth_image_path
    except Exception as e:
        print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
        return None, None

def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray):
    """Generate a 3D mesh with high-resolution texturing from the depth map."""
    global model
    try:
        # Resize and normalize depth image to align with the foreground dimensions
        depth_image_resized = np.array(
            Image.fromarray((depth * 255).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
        )
        print(f"Depth image resized shape: {depth_image_resized.shape}")
        
        # Validate dimensions
        if depth_image_resized.shape != foreground.shape[:2]:
            raise ValueError("Depth image and foreground dimensions do not match.")
        
        # Normalize depth map and set background to zero (remove background noise)
        depth_image_normalized = ((depth_image_resized - depth_image_resized.min()) / 
            (depth_image_resized.max() - depth_image_resized.min()) * 255.0).astype(np.float32)
        print("Depth image normalization completed.")
        
        # Visualize normalized depth map for debugging
        Image.fromarray(depth_image_normalized.astype(np.uint8)).save("debug_depth_normalized.png")

        # Ensure the foreground is RGB (remove alpha channel if present)
        if foreground.shape[2] == 4:
            foreground = foreground[:, :, :3]

        # Create Open3D RGBD image
        depth_o3d = o3d.geometry.Image(np.ascontiguousarray(depth_image_normalized))
        image_o3d = o3d.geometry.Image(np.ascontiguousarray(foreground))
        rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
            image_o3d, depth_o3d, convert_rgb_to_intensity=False
        )

        print("RGBD image creation completed.")
        # Camera intrinsics
        w, h = foreground.shape[1], foreground.shape[0]
        camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(w, h, 2000, 2000, w / 2, h / 2)
        print(f"Camera intrinsics: {camera_intrinsic}")
        print(f"foreground: {foreground.shape}")
        print(f"depth_image_sharpened: {depth_image_sharpened.shape}")
        try:
            # Generate point cloud
            pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
            print(f"Point cloud generated with {len(pcd.points)} points.")
        except Exception as e:
            print(f"Error Point cloud generated: {type(e).__name__} - {e}")
        # Visualize point cloud for debugging
        if len(pcd.points) > 0:
            o3d.visualization.draw_geometries([pcd])
        else:
            raise RuntimeError("Generated point cloud is empty.")

        # Check minimum point count for normals estimation
        if len(pcd.points) < 100:
            raise RuntimeError("Insufficient points in the point cloud for normals estimation.")

        # Estimate normals and orient them
        pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=100))
        pcd.orient_normals_consistent_tangent_plane(k=10)
        print("Normals estimation completed.")
        try:
            pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 2000.0]))
            print("Normals oriented towards camera.")
        except Exception as e:
            print(f"Error orienting normals: {type(e).__name__} - {e}")

        # Generate Poisson mesh
        mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
            pcd, depth=12, width=0, scale=2, linear_fit=True
        )
        print("Poisson mesh generation completed.")

        # Visualize densities for debugging
        densities_array = np.asarray(densities)
        print(f"Mesh densities range: {densities_array.min()} - {densities_array.max()}")

        # Filter mesh by density
        density_threshold = np.quantile(densities_array, 0.06)
        vertices_to_remove = densities_array < density_threshold
        mesh_raw.remove_vertices_by_mask(vertices_to_remove)
        print("Mesh filtered by density.")

        # Simplify and smooth the mesh
        voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 6200
        mesh = mesh_raw.simplify_vertex_clustering(
            voxel_size=voxel_size,
            contraction=o3d.geometry.SimplificationContraction.Average,
        )
        mesh = mesh.filter_smooth_laplacian(number_of_iterations=4)
        print("Mesh simplification and smoothing completed.")

        # Crop mesh to bounding box
        bbox = pcd.get_axis_aligned_bounding_box()
        mesh_crop = mesh.crop(bbox)
        print("Mesh cropping to bounding box completed.")

        # Compute UV mapping for texture
        mesh_crop.compute_vertex_normals()
        uvs = np.array([[v[0] / w, 1 - v[1] / h] for v in np.asarray(mesh_crop.vertices)])
        mesh_crop.triangle_uvs = o3d.utility.Vector2dVector(np.repeat(uvs, 3, axis=0))
        print("UV mapping computed.")

        # Save high-resolution texture image
        texture_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_texture_highres.png"
        foreground_pil = Image.fromarray(foreground)
        high_res_texture = foreground_pil.resize((2000, 2000), Image.LANCZOS)
        high_res_texture.save(texture_path)
        print(f"High-resolution texture saved at: {texture_path}")

        # Apply texture and export mesh
        mesh_crop.textures = [o3d.geometry.Image(np.array(high_res_texture))]
        gltf_path = f"./{os.path.splitext(os.path.basename(image_path))[0]}_model.gltf"
        o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
        print(f"GLTF model saved at: {gltf_path}")

        return gltf_path, texture_path
    except Exception as e:
        print(f"Error generating 3D mesh: {type(e).__name__} - {e}")
        return None, None

def process_image(image_path):
    try:
        image_raw = Image.open(image_path).convert("RGB")

        # Predict and refine depth
        depth_non_inverted, depth_16bit_path = predict_depth(image_raw)

        if depth_non_inverted is None or depth_16bit_path is None:
            raise ValueError("Depth prediction or refinement failed.")

        # Generate 3D mesh and retrieve the GLTF path
        foreground = np.array(remove(image_raw))
        gltf_path, texture_path = get_mesh(image_raw, depth_non_inverted, image_path, foreground)
    
        return depth_16bit_path, gltf_path
    except Exception as e:
        print(f"Error processing image: {type(e).__name__} - {e}")
        return None, None
# Gradio Interface
title = "Depth Estimation & 3D Reconstruction"
description = "Upload an image to generate a depth map and 3D model."

iface = gr.Interface(
    fn=process_image,
    inputs=gr.Image(type="filepath", label="Input Image"),
    outputs=[
        gr.File(label="Refined Depth Image (16-bit)"),
        gr.File(label="3D Model (GLTF)"),
    ],
    title=title,
    description=description,
    flagging_mode="manual"
)
iface.launch(debug=True, share=True)