codic commited on
Commit
25f93b7
·
verified ·
1 Parent(s): eb4395c

Making the main subject

Browse files
Files changed (1) hide show
  1. app.py +15 -35
app.py CHANGED
@@ -1,5 +1,4 @@
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
@@ -24,7 +23,7 @@ def process_image(image_path, depth_map_path=None):
24
  Image.Resampling.LANCZOS,
25
  )
26
 
27
- # Remove background using rembg
28
  foreground = remove(image_raw)
29
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
30
 
@@ -32,19 +31,16 @@ def process_image(image_path, depth_map_path=None):
32
  if depth_map_path:
33
  if depth_map_path.endswith('.npy'):
34
  depth_image = np.load(depth_map_path)
35
- # Invert depth only for npy files
36
  depth_image = 1 - depth_image
37
  else:
38
  depth_image_raw = Image.open(depth_map_path).convert("L")
39
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
40
  depth_image = np.array(depth_image)
41
 
42
- # Normalize depth image to [0, 1] range
43
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
44
  depth_image = np.clip(depth_image, 0, 1)
45
  depth_image = img_as_ubyte(depth_image)
46
  else:
47
- # Generate depth map using DPT model
48
  encoding = feature_extractor(foreground, return_tensors="pt")
49
  with torch.no_grad():
50
  outputs = model(**encoding)
@@ -57,43 +53,35 @@ def process_image(image_path, depth_map_path=None):
57
  align_corners=False,
58
  ).squeeze()
59
  depth_image = prediction.cpu().numpy()
60
-
61
- # Normalize depth image to [0, 1] range before converting
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
 
66
- # Resize and apply lighter Gaussian smoothing for smoother transitions
67
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
68
- mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
69
-
70
- # Ensure matching size and single channel for blending
71
- if len(depth_image.shape) == 3:
72
- depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
73
- if len(mask_blurred.shape) == 3:
74
- mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
75
 
76
- mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
 
77
 
78
- # Blend depth_image with mask_blurred_resized for smoother transition
79
- blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
80
-
81
- # Commenting out the background inpainting section
82
  # background = remove(image_raw, only_mask=True)
83
  # background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
84
  # background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
85
 
86
  try:
87
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, None, image_path)
88
- img = Image.fromarray(blended_depth_image)
 
89
  return [img, gltf_path, gltf_path]
90
  except Exception as e:
91
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
92
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, None, image_path, depth=9)
93
- img = Image.fromarray(blended_depth_image)
94
  return [img, gltf_path, gltf_path]
95
 
96
-
97
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
98
  depth_image_resized = np.array(
99
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
@@ -130,7 +118,6 @@ def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
130
  pcd, depth=depth, width=0, scale=1.2, linear_fit=True
131
  )
132
 
133
- # Flatten the back of the model from the zero point
134
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
135
  mesh = mesh_raw.simplify_vertex_clustering(
136
  voxel_size=voxel_size,
@@ -152,15 +139,8 @@ examples = [["examples/" + img] for img in os.listdir("examples/")]
152
 
153
  iface = gr.Interface(
154
  fn=process_image,
155
- inputs=[
156
- gr.Image(type="filepath", label="Input Image"),
157
- gr.File(type="filepath", label="Input Depth Map (optional)"),
158
- ],
159
- outputs=[
160
- gr.Image(label="Predicted Depth", type="pil"),
161
- gr.Model3D(label="3D Mesh Reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),
162
- gr.File(label="3D gLTF File"),
163
- ],
164
  title=title,
165
  description=description,
166
  examples=examples,
 
1
  from skimage import img_as_ubyte
 
2
  from skimage.segmentation import clear_border
3
  import gradio as gr
4
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
 
23
  Image.Resampling.LANCZOS,
24
  )
25
 
26
+ # Remove background and retain only the main subject
27
  foreground = remove(image_raw)
28
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
29
 
 
31
  if depth_map_path:
32
  if depth_map_path.endswith('.npy'):
33
  depth_image = np.load(depth_map_path)
 
34
  depth_image = 1 - depth_image
35
  else:
36
  depth_image_raw = Image.open(depth_map_path).convert("L")
37
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
38
  depth_image = np.array(depth_image)
39
 
 
40
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
41
  depth_image = np.clip(depth_image, 0, 1)
42
  depth_image = img_as_ubyte(depth_image)
43
  else:
 
44
  encoding = feature_extractor(foreground, return_tensors="pt")
45
  with torch.no_grad():
46
  outputs = model(**encoding)
 
53
  align_corners=False,
54
  ).squeeze()
55
  depth_image = prediction.cpu().numpy()
56
+
 
57
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
58
  depth_image = np.clip(depth_image, 0, 1)
59
  depth_image = img_as_ubyte(depth_image)
60
 
61
+ # Ensure sharp edges for the subject by skipping Gaussian blur
62
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
63
+ mask_sharp = clear_border((depth_image > 0).astype(np.uint8)) # Mask for clear boundary
64
+ mask_sharp_resized = cv2.resize(mask_sharp, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
 
 
 
 
 
65
 
66
+ # Apply the mask directly to obtain sharp edges
67
+ sharp_depth_image = cv2.bitwise_and(depth_image, depth_image, mask=mask_sharp_resized)
68
 
69
+ # Comment out background inpainting section
 
 
 
70
  # background = remove(image_raw, only_mask=True)
71
  # background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
72
  # background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
73
 
74
  try:
75
+ # Pass sharp_depth_image without background
76
+ gltf_path = create_3d_obj(np.array(foreground), sharp_depth_image, None, image_path)
77
+ img = Image.fromarray(sharp_depth_image)
78
  return [img, gltf_path, gltf_path]
79
  except Exception as e:
80
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
81
+ gltf_path = create_3d_obj(np.array(foreground), sharp_depth_image, None, image_path, depth=9)
82
+ img = Image.fromarray(sharp_depth_image)
83
  return [img, gltf_path, gltf_path]
84
 
 
85
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
86
  depth_image_resized = np.array(
87
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
 
118
  pcd, depth=depth, width=0, scale=1.2, linear_fit=True
119
  )
120
 
 
121
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
122
  mesh = mesh_raw.simplify_vertex_clustering(
123
  voxel_size=voxel_size,
 
139
 
140
  iface = gr.Interface(
141
  fn=process_image,
142
+ inputs=[gr.Image(type="filepath", label="Input Image"), gr.File(type="filepath", label="Input Depth Map (optional)")],
143
+ 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")],
 
 
 
 
 
 
 
144
  title=title,
145
  description=description,
146
  examples=examples,