back to the werid cut
Browse files
app.py
CHANGED
|
@@ -1,22 +1,40 @@
|
|
| 1 |
-
from skimage import img_as_ubyte
|
| 2 |
from skimage.filters import gaussian
|
| 3 |
-
from skimage.transform import resize
|
| 4 |
from skimage.segmentation import clear_border
|
| 5 |
-
|
| 6 |
-
from rembg import remove
|
| 7 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 8 |
import torch
|
| 9 |
import numpy as np
|
| 10 |
from PIL import Image
|
| 11 |
import open3d as o3d
|
| 12 |
-
import gradio as gr
|
| 13 |
-
import cv2
|
| 14 |
from pathlib import Path
|
| 15 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Initialize model and feature extractor for depth estimation
|
| 18 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 19 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def process_image(image_path, depth_map_path=None):
|
| 22 |
image_path = Path(image_path)
|
|
@@ -26,19 +44,26 @@ def process_image(image_path, depth_map_path=None):
|
|
| 26 |
Image.Resampling.LANCZOS,
|
| 27 |
)
|
| 28 |
|
| 29 |
-
# Remove background
|
| 30 |
-
foreground =
|
| 31 |
|
| 32 |
# Check if user-provided depth map is available
|
| 33 |
if depth_map_path:
|
| 34 |
if depth_map_path.endswith('.npy'):
|
| 35 |
depth_image = np.load(depth_map_path)
|
| 36 |
-
|
|
|
|
| 37 |
else:
|
| 38 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 39 |
-
depth_image =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
else:
|
| 41 |
-
# Generate depth map using DPT model
|
| 42 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 43 |
with torch.no_grad():
|
| 44 |
outputs = model(**encoding)
|
|
@@ -52,33 +77,27 @@ def process_image(image_path, depth_map_path=None):
|
|
| 52 |
).squeeze()
|
| 53 |
depth_image = prediction.cpu().numpy()
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
|
| 60 |
-
# Resize
|
| 61 |
-
|
| 62 |
-
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# Blend smoothly within interior areas
|
| 73 |
-
depth_float = img_as_float(depth_image_resized)
|
| 74 |
-
mask_blurred_float = img_as_float(depth_image_smoothed)
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
blended_depth_image =
|
| 78 |
-
depth_float * edge_mask + mask_blurred_float * (1 - edge_mask)
|
| 79 |
-
)
|
| 80 |
|
| 81 |
-
# Clear border for a
|
| 82 |
blended_depth_image = clear_border(blended_depth_image)
|
| 83 |
|
| 84 |
try:
|
|
@@ -87,61 +106,48 @@ def process_image(image_path, depth_map_path=None):
|
|
| 87 |
return [img, gltf_path, gltf_path]
|
| 88 |
except Exception as e:
|
| 89 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 90 |
-
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, None, image_path, depth=
|
| 91 |
img = Image.fromarray(blended_depth_image)
|
| 92 |
return [img, gltf_path, gltf_path]
|
| 93 |
|
| 94 |
-
def create_3d_obj(foreground, depth_image, background, image_path, depth=
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
if max_depth - min_depth == 0:
|
| 103 |
-
raise ValueError("Depth image has no variation; cannot normalize.")
|
| 104 |
-
|
| 105 |
-
depth_image_normalized = (depth_image_resized - min_depth) / (max_depth - min_depth)
|
| 106 |
-
depth_image_normalized = np.clip(depth_image_normalized, 0, 1) # Ensure values are between 0 and 1
|
| 107 |
-
|
| 108 |
-
# Convert to 8-bit unsigned integers using OpenCV
|
| 109 |
-
depth_image_resized_uint8 = (depth_image_normalized * 255).astype(np.uint8)
|
| 110 |
|
| 111 |
-
|
| 112 |
-
depth_o3d = o3d.geometry.Image(depth_image_resized_uint8)
|
| 113 |
image_o3d = o3d.geometry.Image(foreground)
|
| 114 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 115 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 116 |
)
|
| 117 |
-
|
| 118 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 119 |
|
| 120 |
-
# Set up the camera intrinsic parameters
|
| 121 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 122 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 123 |
|
| 124 |
-
# Create point cloud from RGBD image
|
| 125 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 126 |
|
| 127 |
if len(pcd.points) < 100:
|
| 128 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 129 |
|
| 130 |
if not pcd.has_normals():
|
| 131 |
-
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.
|
| 132 |
|
| 133 |
if pcd.has_normals():
|
| 134 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 135 |
else:
|
| 136 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 137 |
|
| 138 |
-
# Generate the mesh using Poisson reconstruction
|
| 139 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 140 |
-
pcd, depth=depth, width=
|
| 141 |
)
|
| 142 |
|
| 143 |
# Flatten the back of the model from the zero point
|
| 144 |
-
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) /
|
| 145 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 146 |
voxel_size=voxel_size,
|
| 147 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
@@ -150,10 +156,8 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=12):
|
|
| 150 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 151 |
mesh_crop = mesh.crop(bbox)
|
| 152 |
|
| 153 |
-
# Save the mesh to a GLTF file
|
| 154 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 155 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
| 156 |
-
|
| 157 |
return gltf_path
|
| 158 |
|
| 159 |
# Gradio Interface
|
|
@@ -179,5 +183,4 @@ iface = gr.Interface(
|
|
| 179 |
allow_flagging="never",
|
| 180 |
cache_examples=False,
|
| 181 |
)
|
| 182 |
-
|
| 183 |
-
iface.launch(debug=True, show_api=True)
|
|
|
|
| 1 |
+
from skimage import img_as_ubyte
|
| 2 |
from skimage.filters import gaussian
|
|
|
|
| 3 |
from skimage.segmentation import clear_border
|
| 4 |
+
import gradio as gr
|
|
|
|
| 5 |
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 6 |
import torch
|
| 7 |
import numpy as np
|
| 8 |
from PIL import Image
|
| 9 |
import open3d as o3d
|
|
|
|
|
|
|
| 10 |
from pathlib import Path
|
| 11 |
import os
|
| 12 |
+
import cv2
|
| 13 |
+
from rembg import remove
|
| 14 |
+
from gradio_client import Client, handle_file
|
| 15 |
+
import requests
|
| 16 |
+
from io import BytesIO
|
| 17 |
|
| 18 |
# Initialize model and feature extractor for depth estimation
|
| 19 |
feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 20 |
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 21 |
+
background_removal_client = Client("not-lain/background-removal")
|
| 22 |
+
|
| 23 |
+
def remove_background_with_api(image):
|
| 24 |
+
# Step 1: Use the `not-lain/background-removal` API
|
| 25 |
+
result_url = background_removal_client.predict(
|
| 26 |
+
f=handle_file(image),
|
| 27 |
+
api_name="/png"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Step 2: Download the image returned by the API
|
| 31 |
+
response = requests.get(result_url)
|
| 32 |
+
foreground = Image.open(BytesIO(response.content)).convert("RGBA")
|
| 33 |
+
|
| 34 |
+
# Step 3: Apply `rmbg` for additional cleanup
|
| 35 |
+
cleaned_foreground = remove(foreground)
|
| 36 |
+
|
| 37 |
+
return Image.fromarray(np.array(cleaned_foreground)).convert("RGB")
|
| 38 |
|
| 39 |
def process_image(image_path, depth_map_path=None):
|
| 40 |
image_path = Path(image_path)
|
|
|
|
| 44 |
Image.Resampling.LANCZOS,
|
| 45 |
)
|
| 46 |
|
| 47 |
+
# Remove background using the API + rmbg combination
|
| 48 |
+
foreground = remove_background_with_api(image_path)
|
| 49 |
|
| 50 |
# Check if user-provided depth map is available
|
| 51 |
if depth_map_path:
|
| 52 |
if depth_map_path.endswith('.npy'):
|
| 53 |
depth_image = np.load(depth_map_path)
|
| 54 |
+
# Invert depth only for npy files
|
| 55 |
+
depth_image = 1 - depth_image
|
| 56 |
else:
|
| 57 |
depth_image_raw = Image.open(depth_map_path).convert("L")
|
| 58 |
+
depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
|
| 59 |
+
depth_image = np.array(depth_image)
|
| 60 |
+
|
| 61 |
+
# Normalize depth image to [0, 1] range
|
| 62 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 63 |
+
depth_image = np.clip(depth_image, 0, 1)
|
| 64 |
+
depth_image = img_as_ubyte(depth_image)
|
| 65 |
else:
|
| 66 |
+
# Generate depth map using DPT model
|
| 67 |
encoding = feature_extractor(foreground, return_tensors="pt")
|
| 68 |
with torch.no_grad():
|
| 69 |
outputs = model(**encoding)
|
|
|
|
| 77 |
).squeeze()
|
| 78 |
depth_image = prediction.cpu().numpy()
|
| 79 |
|
| 80 |
+
# Normalize depth image to [0, 1] range before converting
|
| 81 |
+
depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
|
| 82 |
+
depth_image = np.clip(depth_image, 0, 1)
|
| 83 |
+
depth_image = img_as_ubyte(depth_image)
|
| 84 |
|
| 85 |
+
# Resize and apply lighter Gaussian smoothing for smoother transitions
|
| 86 |
+
depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
|
| 87 |
+
mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
|
| 88 |
|
| 89 |
+
# Ensure matching size and single channel for blending
|
| 90 |
+
if len(depth_image.shape) == 3:
|
| 91 |
+
depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
|
| 92 |
+
if len(mask_blurred.shape) == 3:
|
| 93 |
+
mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
|
| 94 |
+
|
| 95 |
+
mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# Blend depth_image with mask_blurred_resized for smoother transition
|
| 98 |
+
blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
# Clear border for a smooth edge around main subject
|
| 101 |
blended_depth_image = clear_border(blended_depth_image)
|
| 102 |
|
| 103 |
try:
|
|
|
|
| 106 |
return [img, gltf_path, gltf_path]
|
| 107 |
except Exception as e:
|
| 108 |
print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
|
| 109 |
+
gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, None, image_path, depth=9)
|
| 110 |
img = Image.fromarray(blended_depth_image)
|
| 111 |
return [img, gltf_path, gltf_path]
|
| 112 |
|
| 113 |
+
def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
|
| 114 |
+
depth_image_resized = np.array(
|
| 115 |
+
Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
|
| 116 |
+
)
|
| 117 |
+
depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
|
| 118 |
+
depth_image_resized.max() - depth_image_resized.min()
|
| 119 |
+
) * 255
|
| 120 |
+
depth_image_normalized = depth_image_normalized.astype(np.uint8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
depth_o3d = o3d.geometry.Image(depth_image_normalized)
|
|
|
|
| 123 |
image_o3d = o3d.geometry.Image(foreground)
|
| 124 |
rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
|
| 125 |
image_o3d, depth_o3d, convert_rgb_to_intensity=False
|
| 126 |
)
|
|
|
|
| 127 |
w, h = foreground.shape[1], foreground.shape[0]
|
| 128 |
|
|
|
|
| 129 |
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
|
| 130 |
camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
|
| 131 |
|
|
|
|
| 132 |
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
|
| 133 |
|
| 134 |
if len(pcd.points) < 100:
|
| 135 |
raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
|
| 136 |
|
| 137 |
if not pcd.has_normals():
|
| 138 |
+
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
|
| 139 |
|
| 140 |
if pcd.has_normals():
|
| 141 |
pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
|
| 142 |
else:
|
| 143 |
raise RuntimeError("Failed to estimate normals for the point cloud.")
|
| 144 |
|
|
|
|
| 145 |
mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
|
| 146 |
+
pcd, depth=depth, width=0, scale=1.2, linear_fit=True
|
| 147 |
)
|
| 148 |
|
| 149 |
# Flatten the back of the model from the zero point
|
| 150 |
+
voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
|
| 151 |
mesh = mesh_raw.simplify_vertex_clustering(
|
| 152 |
voxel_size=voxel_size,
|
| 153 |
contraction=o3d.geometry.SimplificationContraction.Average,
|
|
|
|
| 156 |
bbox = pcd.get_axis_aligned_bounding_box()
|
| 157 |
mesh_crop = mesh.crop(bbox)
|
| 158 |
|
|
|
|
| 159 |
gltf_path = f"./{image_path.stem}.gltf"
|
| 160 |
o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
|
|
|
|
| 161 |
return gltf_path
|
| 162 |
|
| 163 |
# Gradio Interface
|
|
|
|
| 183 |
allow_flagging="never",
|
| 184 |
cache_examples=False,
|
| 185 |
)
|
| 186 |
+
iface.launch(debug=True, show_api=True, share=True)
|
|
|