codic commited on
Commit
aa18bbe
·
verified ·
1 Parent(s): ae34221

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -53
app.py CHANGED
@@ -16,76 +16,47 @@ model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
16
  def process_image(image_path, depth_map_path=None):
17
  image_path = Path(image_path)
18
  image_raw = Image.open(image_path).convert("RGB")
19
-
20
- # Resize the main image for consistent depth estimation size
21
  image = image_raw.resize(
22
  (2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
23
  Image.Resampling.LANCZOS,
24
  )
25
 
26
  # Remove background using rembg
27
- foreground = Image.fromarray(np.array(remove(image_raw))).convert("RGBA") # Convert foreground to RGBA
 
 
 
 
 
28
 
29
- # Duplicate the background, adding depth to one and keeping the other flat
30
- bg_copy = image_raw.convert("RGBA") # Ensure background is also in RGBA mode
31
- image_combined = Image.alpha_composite(bg_copy, foreground)
32
 
33
- # Check if a user-provided depth map is available
34
  if depth_map_path:
35
- if depth_map_path.endswith('.npy'):
36
- depth_image = np.load(depth_map_path)
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 the depth image
43
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
44
- depth_image = (depth_image * 255).astype('uint8')
45
  else:
46
- # Generate a depth map using the DPT model
47
- encoding = feature_extractor(foreground, return_tensors="pt")
48
  with torch.no_grad():
49
  outputs = model(**encoding)
50
  predicted_depth = outputs.predicted_depth
 
51
 
52
- # Interpolate the depth map to match image dimensions
53
- prediction = torch.nn.functional.interpolate(
54
- predicted_depth.unsqueeze(1),
55
- size=image.size[::-1],
56
- mode="bicubic",
57
- align_corners=False,
58
- ).squeeze()
59
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
60
-
61
- # Resize and apply a lighter Gaussian blur for minimal depth on background
62
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
63
- mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur
64
-
65
- # Ensure matching size and single channel for blending
66
- if len(depth_image.shape) == 3:
67
- depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
68
-
69
- if len(mask_blurred.shape) == 3:
70
- mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
71
-
72
- # Resize mask_blurred to match depth_image dimensions
73
- mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
74
 
75
- # Blend depth_image with mask_blurred_resized
76
- blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
77
 
78
- try:
79
- gltf_path = create_3d_obj(np.array(image_combined), blended_depth_image, image_path)
80
- img = Image.fromarray(blended_depth_image)
81
- return [img, gltf_path, gltf_path]
82
- except Exception:
83
- print("Error with default depth. Retrying with a shallower depth.")
84
- gltf_path = create_3d_obj(np.array(image_combined), blended_depth_image, image_path, depth=12)
85
- img = Image.fromarray(blended_depth_image)
86
- return [img, gltf_path, gltf_path]
87
 
88
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
89
  # Resize and normalize the depth image
90
  depth_image_resized = np.array(
91
  Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
@@ -135,7 +106,7 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
135
  voxel_size=voxel_size,
136
  contraction=o3d.geometry.SimplificationContraction.Average,
137
  )
138
- mesh = mesh.filter_smooth_simple(number_of_iterations=2)
139
  bbox = pcd.get_axis_aligned_bounding_box()
140
  mesh_crop = mesh.crop(bbox)
141
 
 
16
  def process_image(image_path, depth_map_path=None):
17
  image_path = Path(image_path)
18
  image_raw = Image.open(image_path).convert("RGB")
19
+ # Resizing image to ensure background duplicates match the full size
 
20
  image = image_raw.resize(
21
  (2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
22
  Image.Resampling.LANCZOS,
23
  )
24
 
25
  # Remove background using rembg
26
+ foreground = remove(image_raw)
27
+ foreground = Image.fromarray(np.array(foreground)).convert("RGBA") # Convert to RGBA for transparency support
28
+
29
+ # Create a duplicate background and apply small depth adjustments
30
+ bg_copy = image.convert("RGBA")
31
+ bg_copy_no_depth = image.convert("RGBA") # Background without depth for flat appearance
32
 
33
+ # Composite the foreground over the background copy
34
+ bg_with_depth = Image.alpha_composite(bg_copy, foreground) # First background with slight depth
 
35
 
36
+ # Normalize depth and convert to high quality texture
37
  if depth_map_path:
38
+ depth_image = np.load(depth_map_path) if depth_map_path.endswith('.npy') else np.array(Image.open(depth_map_path).convert("L"))
 
 
 
 
 
 
 
 
 
39
  else:
40
+ # Generate depth map with DPT model if none provided
41
+ encoding = feature_extractor(foreground.convert("RGB"), return_tensors="pt")
42
  with torch.no_grad():
43
  outputs = model(**encoding)
44
  predicted_depth = outputs.predicted_depth
45
+ depth_image = (predicted_depth.cpu().numpy() * 255 / np.max(predicted_depth.cpu().numpy())).astype("uint8")
46
 
47
+ # Resize and blend depth image for final compositing
 
 
 
 
 
 
 
 
 
48
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
49
+ depth_blur = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for texture detail
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Composite with background without depth effects
52
+ bg_final = Image.alpha_composite(bg_copy_no_depth, Image.fromarray(depth_blur).convert("RGBA"))
53
 
54
+ # Return the final blended depth and 3D model path
55
+ blended_image = Image.alpha_composite(bg_final, foreground)
56
+ img = Image.fromarray(depth_blur)
57
+ return [img, blended_image]
 
 
 
 
 
58
 
59
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=8):
60
  # Resize and normalize the depth image
61
  depth_image_resized = np.array(
62
  Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
 
106
  voxel_size=voxel_size,
107
  contraction=o3d.geometry.SimplificationContraction.Average,
108
  )
109
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3)
110
  bbox = pcd.get_axis_aligned_bounding_box()
111
  mesh_crop = mesh.crop(bbox)
112