codic commited on
Commit
946feeb
·
verified ·
1 Parent(s): d4d2343

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -28
app.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import gradio as gr
2
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
3
  import torch
@@ -21,26 +24,24 @@ def process_image(image_path, depth_map_path=None):
21
  Image.Resampling.LANCZOS,
22
  )
23
 
24
- # Remove background using rembg
25
  foreground = remove(image_raw)
26
- foreground = Image.fromarray(np.array(foreground)).convert("RGB")
 
27
 
28
  # Check if user-provided depth map is available
29
  if depth_map_path:
30
  if depth_map_path.endswith('.npy'):
31
  depth_image = np.load(depth_map_path)
32
- # Invert depth only for npy files
33
  depth_image = 1 - depth_image
34
  else:
35
  depth_image_raw = Image.open(depth_map_path).convert("L")
36
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
37
  depth_image = np.array(depth_image)
38
 
39
- # Normalize depth image
40
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
41
- depth_image = (depth_image * 255).astype('uint8')
42
  else:
43
- # Generate depth map using DPT model
44
  encoding = feature_extractor(foreground, return_tensors="pt")
45
  with torch.no_grad():
46
  outputs = model(**encoding)
@@ -52,36 +53,31 @@ def process_image(image_path, depth_map_path=None):
52
  mode="bicubic",
53
  align_corners=False,
54
  ).squeeze()
55
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
56
 
57
- # Resize and apply lighter Gaussian smoothing for smoother transitions
58
- depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
59
- mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
60
 
61
- # Ensure matching size and single channel for blending
62
- if len(depth_image.shape) == 3:
63
- depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
64
- if len(mask_blurred.shape) == 3:
65
- mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
66
-
67
- mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
68
-
69
- # Blend depth_image with mask_blurred_resized for smoother transition
70
- blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
71
-
72
- # Inpaint background where main subject was removed
73
  background = remove(image_raw, only_mask=True)
74
- background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
75
- background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
 
 
 
 
 
76
 
 
77
  try:
78
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path)
79
- img = Image.fromarray(blended_depth_image)
80
  return [img, gltf_path, gltf_path]
81
  except Exception as e:
82
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
83
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path, depth=9)
84
- img = Image.fromarray(blended_depth_image)
85
  return [img, gltf_path, gltf_path]
86
 
87
 
 
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
 
24
  Image.Resampling.LANCZOS,
25
  )
26
 
27
+ # Remove background using rembg and apply clear_border
28
  foreground = remove(image_raw)
29
+ foreground = clear_border(np.array(foreground))
30
+ foreground = Image.fromarray(img_as_ubyte(foreground)).convert("RGB")
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
  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
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
43
+ depth_image = img_as_ubyte(depth_image)
44
  else:
 
45
  encoding = feature_extractor(foreground, return_tensors="pt")
46
  with torch.no_grad():
47
  outputs = model(**encoding)
 
53
  mode="bicubic",
54
  align_corners=False,
55
  ).squeeze()
56
+ depth_image = img_as_ubyte(prediction.cpu().numpy() / np.max(prediction.cpu().numpy()))
57
 
58
+ # Apply Gaussian smoothing to depth map
59
+ depth_image = gaussian(depth_image, sigma=0.8, preserve_range=True)
60
+ depth_image = img_as_ubyte(depth_image)
61
 
62
+ # Inpaint background where the main subject was removed
 
 
 
 
 
 
 
 
 
 
 
63
  background = remove(image_raw, only_mask=True)
64
+ background = clear_border(np.array(background))
65
+ background_inpainted = cv2.inpaint(
66
+ np.array(image_raw),
67
+ background[:, :, 0],
68
+ inpaintRadius=3,
69
+ flags=cv2.INPAINT_TELEA
70
+ )
71
 
72
+ # Call create_3d_obj and return processed images and 3D model
73
  try:
74
+ gltf_path = create_3d_obj(np.array(foreground), depth_image, background_inpainted, image_path)
75
+ img = Image.fromarray(depth_image)
76
  return [img, gltf_path, gltf_path]
77
  except Exception as e:
78
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
79
+ gltf_path = create_3d_obj(np.array(foreground), depth_image, background_inpainted, image_path, depth=9)
80
+ img = Image.fromarray(depth_image)
81
  return [img, gltf_path, gltf_path]
82
 
83