codic commited on
Commit
c07e900
·
verified ·
1 Parent(s): 6be6fc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -58
app.py CHANGED
@@ -16,92 +16,104 @@ from rembg import remove
16
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
17
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
18
 
 
 
19
  def process_image(image_path, depth_map_path=None):
 
 
 
 
 
 
 
20
  image_path = Path(image_path)
21
  image_raw = Image.open(image_path).convert("RGB")
22
- image = image_raw.resize(
23
- (3072, int(3072 * image_raw.size[1] / image_raw.size[0])),
24
- Image.Resampling.LANCZOS,
 
 
 
 
 
25
  )
26
 
27
- # Remove background to isolate the main subject
28
  foreground = remove(image_raw)
29
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
30
 
31
- # Load or generate depth map
32
  if depth_map_path:
 
33
  if depth_map_path.endswith('.npy'):
34
  depth_image = np.load(depth_map_path).astype(np.float32)
35
  depth_image = 1 - depth_image # Invert depth for npy files
36
  else:
37
  depth_image_raw = Image.open(depth_map_path).convert("L")
38
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
39
  depth_image = np.array(depth_image, dtype=np.float32)
40
 
41
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
42
- depth_image = np.clip(depth_image, 0, 1)
43
- else:
44
- # Generate depth map using DPT model
45
- encoding = feature_extractor(foreground, return_tensors="pt")
46
- with torch.no_grad():
47
- outputs = model(**encoding)
48
- predicted_depth = outputs.predicted_depth
49
-
50
- prediction = torch.nn.functional.interpolate(
51
- predicted_depth.unsqueeze(1),
52
- size=image.size[::-1],
53
- mode="bicubic",
54
- align_corners=False,
55
- ).squeeze()
56
- depth_image = prediction.cpu().numpy().astype(np.float32)
57
 
 
58
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
59
  depth_image = np.clip(depth_image, 0, 1)
60
-
61
- # Step 1: Depth refinement (Morphological closing)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  kernel = np.ones((3, 3), np.uint8)
63
  depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
64
-
65
- # Step 2: Edge-preserving filter (Enhance small structures)
66
- depth_image = cv2.edgePreservingFilter(
67
- (depth_image_cleaned * 255).astype(np.uint8), flags=1, sigma_s=13, sigma_r=0.3
68
- )
69
- depth_image = depth_image.astype(np.float32) / 255 # Normalize back to [0, 1]
70
-
71
- # Step 3: Smooth depth map with Gaussian filter
72
- depth_image = cv2.GaussianBlur(depth_image, (5, 5), sigmaX=3, sigmaY=3)
73
 
74
- # Step 4: Bilateral filter for detail preservation
75
- depth_image = cv2.bilateralFilter((depth_image * 255).astype(np.uint8), 7, 60, 60).astype(np.float32) / 255
76
-
77
- # Step 5: Resize the depth map to match the foreground size
78
- depth_image = cv2.resize(depth_image, (foreground.size[0], foreground.size[1]), interpolation=cv2.INTER_LANCZOS4) # High-quality interpolation for resizing
79
-
80
- # Step 6: Create an edge-aware mask (if needed for further processing)
81
- mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1) # Create a mask where the foreground is not black
82
- # Improved edge detection for the main subject
83
- edges = cv2.Canny(img_as_ubyte(mask), threshold1=30, threshold2=150) # Adjust thresholds for edges
84
- edges_dilated = cv2.dilate(edges, np.ones((9, 9), np.uint8), iterations=4) # Larger kernel, fewer gaps
85
  edges_eroded = cv2.erode(edges_dilated, np.ones((9, 9), np.uint8), iterations=2)
86
 
87
- # Use the refined edge mask to clean up the depth map
88
- depth_subject_only = np.where(edges_eroded == 0, depth_image * mask, 0)
89
- depth_subject_only[~mask] = 0 # Ensure background areas are zeroed out
90
 
91
- # Generate the final depth image with reduced blur artifacts
92
  depth_display = img_as_ubyte(depth_subject_only)
93
-
94
  try:
95
- # Generate the 3D model
96
- gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path)
97
- img = Image.fromarray(depth_display)
98
- return [img, gltf_path, gltf_path]
99
  except Exception as e:
100
- print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
101
- gltf_path = create_3d_obj(np.array(foreground), depth_subject_only, image_path, depth=9)
102
- img = Image.fromarray(depth_display)
103
- return [img, gltf_path, gltf_path]
104
-
105
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
106
  """
107
  Generates a 3D model by combining an image and a masked depth map focused only on the main subject.
 
16
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
17
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
18
 
19
+ @spaces.GPU(duration=120)
20
+ @torch.no_grad()
21
  def process_image(image_path, depth_map_path=None):
22
+ from pathlib import Path
23
+ from PIL import Image
24
+ import numpy as np
25
+ import cv2
26
+ from skimage.util import img_as_ubyte
27
+
28
+ # Load the raw image
29
  image_path = Path(image_path)
30
  image_raw = Image.open(image_path).convert("RGB")
31
+
32
+ # Step 1: Downscale input image for depth prediction
33
+ max_dimension = 768
34
+ scaled_width = max_dimension
35
+ scaled_height = int(max_dimension * image_raw.size[1] / image_raw.size[0])
36
+ scaled_image = image_raw.resize(
37
+ (scaled_width, scaled_height),
38
+ Image.Resampling.LANCZOS
39
  )
40
 
41
+ # Step 2: Remove background to isolate the main subject
42
  foreground = remove(image_raw)
43
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
44
 
45
+ # Step 3: Handle depth map input or prediction
46
  if depth_map_path:
47
+ # Load precomputed depth map
48
  if depth_map_path.endswith('.npy'):
49
  depth_image = np.load(depth_map_path).astype(np.float32)
50
  depth_image = 1 - depth_image # Invert depth for npy files
51
  else:
52
  depth_image_raw = Image.open(depth_map_path).convert("L")
53
+ depth_image = depth_image_raw.resize((scaled_width, scaled_height), Image.Resampling.NEAREST)
54
  depth_image = np.array(depth_image, dtype=np.float32)
55
 
56
+ # Ensure depth map matches scaled image dimensions
57
+ if depth_image.shape != (scaled_height, scaled_width):
58
+ depth_image = cv2.resize(
59
+ depth_image,
60
+ (scaled_width, scaled_height), # Width, Height
61
+ interpolation=cv2.INTER_LINEAR
62
+ ).astype(np.float32)
 
 
 
 
 
 
 
 
 
63
 
64
+ # Normalize depth map
65
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image) + 1e-3)
66
  depth_image = np.clip(depth_image, 0, 1)
67
+ else:
68
+ # Predict depth using the pipeline
69
+ depth_output = pipe(
70
+ scaled_image,
71
+ num_inference_steps=4,
72
+ ensemble_size=5,
73
+ output_uncertainty=True
74
+ )
75
+ depth_image = depth_output.prediction[0].cpu().numpy() if isinstance(depth_output.prediction[0], torch.Tensor) else depth_output.prediction[0]
76
+ uncertainty = depth_output.uncertainty
77
+
78
+ # Visualize depth and uncertainty
79
+ depth_vis = pipe.image_processor.visualize_depth(depth_image)
80
+ uncertainty_vis = pipe.image_processor.visualize_uncertainty(uncertainty)
81
+ depth_vis[0].save(f"{image_path.stem}_depth_visualized.png")
82
+ uncertainty_vis[0].save(f"{image_path.stem}_uncertainty_visualized.png")
83
+
84
+ # Step 4: Scale depth map back to match original image dimensions
85
+ original_width, original_height = image_raw.size
86
+ depth_image = cv2.resize(
87
+ depth_image,
88
+ (original_width, original_height), # Width, Height
89
+ interpolation=cv2.INTER_LINEAR
90
+ ).astype(np.float32)
91
+
92
+ # Step 5: Refine depth map
93
  kernel = np.ones((3, 3), np.uint8)
94
  depth_image_cleaned = cv2.morphologyEx(depth_image, cv2.MORPH_CLOSE, kernel)
95
+ depth_image = cv2.GaussianBlur(depth_image_cleaned, (5, 5), sigmaX=3, sigmaY=3)
 
 
 
 
 
 
 
 
96
 
97
+ # Step 6: Use edge mask for subject isolation
98
+ mask = np.all(np.array(foreground) != [0, 0, 0], axis=-1)
99
+ edges = cv2.Canny(img_as_ubyte(mask), threshold1=60, threshold2=100)
100
+ edges_dilated = cv2.dilate(edges, np.ones((9, 9), np.uint8), iterations=4)
 
 
 
 
 
 
 
101
  edges_eroded = cv2.erode(edges_dilated, np.ones((9, 9), np.uint8), iterations=2)
102
 
103
+ # Combine depth with edge mask
104
+ depth_subject_only = np.where(edges_eroded == 0, depth_image * mask, 0).astype(np.float32)
105
+ depth_subject_only[~mask] = 0
106
 
107
+ # Step 7: Create 3D model
108
  depth_display = img_as_ubyte(depth_subject_only)
 
109
  try:
110
+ gltf_path = create_3d_obj(np.array(image_raw), depth_subject_only, image_path)
111
+ return [Image.fromarray(depth_display), gltf_path, gltf_path]
 
 
112
  except Exception as e:
113
+ print(f"Error creating 3D model: {e}. Retrying with shallower depth.")
114
+ gltf_path = create_3d_obj(np.array(image_raw), depth_subject_only, image_path, depth=9)
115
+ return [Image.fromarray(depth_display), gltf_path, gltf_path]
116
+
 
117
  def create_3d_obj(foreground, depth_image, image_path, depth=12, edge_strength=0.15):
118
  """
119
  Generates a 3D model by combining an image and a masked depth map focused only on the main subject.