codic commited on
Commit
fd48885
·
verified ·
1 Parent(s): 2ab071c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -9
app.py CHANGED
@@ -11,6 +11,7 @@ import tempfile
11
  from skimage import filters
12
  import gc
13
  import xformers
 
14
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
15
  if os.environ.get("SPACES_ZERO_GPU") is not None:
16
  import spaces
@@ -60,7 +61,7 @@ except ImportError:
60
  print("XFormers library is not installed. Run `pip install xformers`.")
61
  except Exception as e:
62
  print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
63
-
64
  @spaces.GPU(enable_queue=True)
65
  def predict_depth(image: Image.Image):
66
  """Predict depth from an image and return refined depth map."""
@@ -68,6 +69,12 @@ def predict_depth(image: Image.Image):
68
  print("Processing input image...")
69
  image = image.convert("RGB")
70
 
 
 
 
 
 
 
71
  # Step 1: Remove background to isolate the main subject
72
  print("Removing background...")
73
  foreground = remove(image)
@@ -110,14 +117,30 @@ def predict_depth(image: Image.Image):
110
  mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
111
  depth_subject_only = np.where(mask, depth_resized, 0)
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  # Keep a non-inverted depth for mesh processing
114
- depth_non_inverted = depth_subject_only.copy()
115
 
116
  # Invert the depth map for display
117
- depth_subject_only = 1.0 - (depth_subject_only / 65535.0)
118
 
119
  # Generate normalized depth for visualization
120
- depth_display = np.clip(depth_subject_only * 255, 0, 255).astype(np.uint8) # 8-bit display
121
 
122
  # Save visualizations
123
  depth_image_path = "depth_image.png"
@@ -129,14 +152,19 @@ def predict_depth(image: Image.Image):
129
  except Exception as e:
130
  print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
131
  return None, None
 
132
  def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray):
133
  """Generate a 3D mesh with high-resolution texturing from the depth map."""
134
  try:
 
 
 
135
  print("Resizing depth image...")
136
- depth_image_resized = Image.fromarray(depth.astype(np.uint16)) # No re-normalization
137
-
138
- if image.size != depth_image_resized.size:
139
- image = image.resize(depth_image_resized.size, Image.Resampling.LANCZOS)
 
140
 
141
  print("Converting depth and image to Open3D format...")
142
  depth_o3d = o3d.geometry.Image(depth.astype(np.float32) / 65535.0) # Non-inverted scale
@@ -170,7 +198,6 @@ def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray)
170
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
171
  pcd, depth=12, width=0, scale=4, linear_fit=True
172
  )
173
-
174
  # Filter mesh by density
175
  density_threshold = np.quantile(np.asarray(densities), 0.06)
176
  vertices_to_remove = densities < density_threshold
 
11
  from skimage import filters
12
  import gc
13
  import xformers
14
+
15
  # Handle GPU availability in Hugging Face Spaces with ZeroGPU
16
  if os.environ.get("SPACES_ZERO_GPU") is not None:
17
  import spaces
 
61
  print("XFormers library is not installed. Run `pip install xformers`.")
62
  except Exception as e:
63
  print(f"Unexpected error enabling XFormers: {type(e).__name__} - {e}")
64
+
65
  @spaces.GPU(enable_queue=True)
66
  def predict_depth(image: Image.Image):
67
  """Predict depth from an image and return refined depth map."""
 
69
  print("Processing input image...")
70
  image = image.convert("RGB")
71
 
72
+ # Resize image if larger than 2K
73
+ if max(image.size) > 2000:
74
+ scale_factor = 2000 / max(image.size)
75
+ new_size = (int(image.size[0] * scale_factor), int(image.size[1] * scale_factor))
76
+ image = image.resize(new_size, Image.LANCZOS)
77
+
78
  # Step 1: Remove background to isolate the main subject
79
  print("Removing background...")
80
  foreground = remove(image)
 
117
  mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
118
  depth_subject_only = np.where(mask, depth_resized, 0)
119
 
120
+ # Step 1: Depth refinement (Morphological closing)
121
+ kernel = np.ones((3, 3), np.uint8)
122
+ depth_image_cleaned = cv2.morphologyEx(depth_subject_only, cv2.MORPH_CLOSE, kernel)
123
+
124
+ # Step 2: Edge-preserving filter (Enhance small structures)
125
+ depth_image = cv2.edgePreservingFilter(
126
+ (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
127
+ )
128
+ depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
129
+
130
+ # Step 3: Smooth depth map with Gaussian filter
131
+ depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
132
+
133
+ # Step 4: Bilateral filter for detail preservation
134
+ depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
135
+
136
  # Keep a non-inverted depth for mesh processing
137
+ depth_non_inverted = depth_image.copy()
138
 
139
  # Invert the depth map for display
140
+ depth_image = 1.0 - depth_image
141
 
142
  # Generate normalized depth for visualization
143
+ depth_display = np.clip(depth_image * 255, 0, 255).astype(np.uint8) # 8-bit display
144
 
145
  # Save visualizations
146
  depth_image_path = "depth_image.png"
 
152
  except Exception as e:
153
  print(f"Error in depth prediction or processing: {type(e).__name__} - {e}")
154
  return None, None
155
+
156
  def get_mesh(image: Image.Image, depth, image_path: str, foreground: np.ndarray):
157
  """Generate a 3D mesh with high-resolution texturing from the depth map."""
158
  try:
159
+ print("Normalizing depth map...")
160
+ # Normalize depth map and set background to zero (remove background noise)
161
+ depth_image_normalized = ((depth - depth.min()) / (depth.max() - depth.min()) * 255.0).astype(np.float32)
162
  print("Resizing depth image...")
163
+ depth_image_resized = np.array(
164
+ Image.fromarray((depth_image_normalized).astype(np.uint8)).resize(foreground.shape[:2][::-1], Image.LANCZOS)
165
+ )
166
+ # Convert depth map to float for filtering
167
+ depth_image_resized = depth_image_resized.astype(np.float32) # No re-normalization
168
 
169
  print("Converting depth and image to Open3D format...")
170
  depth_o3d = o3d.geometry.Image(depth.astype(np.float32) / 65535.0) # Non-inverted scale
 
198
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
199
  pcd, depth=12, width=0, scale=4, linear_fit=True
200
  )
 
201
  # Filter mesh by density
202
  density_threshold = np.quantile(np.asarray(densities), 0.06)
203
  vertices_to_remove = densities < density_threshold