codic commited on
Commit
59928cb
·
verified ·
1 Parent(s): b4a2ed6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -22
app.py CHANGED
@@ -7,7 +7,7 @@ import open3d as o3d
7
  from pathlib import Path
8
  import os
9
  import cv2
10
- from rembg import remove # Import the rembg library for background removal
11
 
12
  # Initialize model and feature extractor for depth estimation
13
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
@@ -15,27 +15,26 @@ model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
15
 
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") # Ensure the image is in RGB format
19
  image = image_raw.resize(
20
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
21
  Image.Resampling.LANCZOS,
22
  )
23
 
24
  # Remove background using rembg
25
- foreground = remove(image_raw) # Remove background
26
- foreground = Image.fromarray(np.array(foreground)) # Convert back to PIL Image
27
- foreground = foreground.convert("RGB") # Ensure the foreground is in RGB format
28
 
29
  # Check if user-provided depth map is available
30
  if depth_map_path:
31
  if depth_map_path.endswith('.npy'):
32
  depth_image = np.load(depth_map_path)
33
  else:
34
- depth_image_raw = Image.open(depth_map_path).convert("L") # Convert to grayscale
35
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
36
  depth_image = np.array(depth_image)
37
 
38
- # Normalize depth image to match expected format
39
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
40
  depth_image = (depth_image * 255).astype('uint8')
41
  else:
@@ -53,31 +52,28 @@ def process_image(image_path, depth_map_path=None):
53
  ).squeeze()
54
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
55
 
56
- # Resize depth map to match RGB image dimensions
57
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
58
 
59
- # Step 1: Apply Gaussian smoothing on the depth map
60
  smoothed_depth_map = cv2.GaussianBlur(depth_image, (5, 5), 0)
61
 
62
  try:
63
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path)
64
  img = Image.fromarray(smoothed_depth_map)
65
  return [img, gltf_path, gltf_path]
66
- except Exception as e:
67
  print("Error with default depth. Retrying with a shallower depth.")
68
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path, depth=8)
69
  img = Image.fromarray(smoothed_depth_map)
70
  return [img, gltf_path, gltf_path]
71
- except:
72
- print("Error reconstructing 3D model")
73
- raise Exception("Error reconstructing 3D model")
74
 
75
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
76
- # Resize and normalize the depth image if needed
77
  depth_image_resized = np.array(
78
  Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.NEAREST)
79
  )
80
- # Invert depth values (make closer objects lighter)
81
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
82
  depth_image_resized.max() - depth_image_resized.min()
83
  )
@@ -98,14 +94,16 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
98
  # Create Point Cloud from RGBD Image
99
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
100
 
101
- # Ensure normals are estimated before orienting them
 
 
 
 
102
  if not pcd.has_normals():
103
  print("Estimating normals with increased search radius for sparse data...")
104
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=50))
105
-
106
- # Confirm if normals are present
107
  if pcd.has_normals():
108
- print("Orienting normals towards camera location...")
109
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
110
  else:
111
  raise RuntimeError("Failed to estimate normals for the point cloud.")
@@ -121,7 +119,7 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
121
  voxel_size=voxel_size,
122
  contraction=o3d.geometry.SimplificationContraction.Average,
123
  )
124
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
125
  bbox = pcd.get_axis_aligned_bounding_box()
126
  mesh_crop = mesh.crop(bbox)
127
 
@@ -140,7 +138,7 @@ iface = gr.Interface(
140
  fn=process_image,
141
  inputs=[
142
  gr.Image(type="filepath", label="Input Image"),
143
- gr.File(type="filepath", label="Input Depth Map (optional)"), # Changed input type to allow .npy
144
  ],
145
  outputs=[
146
  gr.Image(label="Predicted Depth", type="pil"),
 
7
  from pathlib import Path
8
  import os
9
  import cv2
10
+ from rembg import remove
11
 
12
  # Initialize model and feature extractor for depth estimation
13
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
 
15
 
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
  image = image_raw.resize(
20
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
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
  else:
33
+ depth_image_raw = Image.open(depth_map_path).convert("L")
34
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
35
  depth_image = np.array(depth_image)
36
 
37
+ # Normalize depth image
38
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
39
  depth_image = (depth_image * 255).astype('uint8')
40
  else:
 
52
  ).squeeze()
53
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
54
 
55
+ # Resize depth map
56
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
57
 
58
+ # Apply Gaussian smoothing
59
  smoothed_depth_map = cv2.GaussianBlur(depth_image, (5, 5), 0)
60
 
61
  try:
62
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path)
63
  img = Image.fromarray(smoothed_depth_map)
64
  return [img, gltf_path, gltf_path]
65
+ except Exception:
66
  print("Error with default depth. Retrying with a shallower depth.")
67
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path, depth=8)
68
  img = Image.fromarray(smoothed_depth_map)
69
  return [img, gltf_path, gltf_path]
 
 
 
70
 
71
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
72
+ # Resize and normalize the depth image
73
  depth_image_resized = np.array(
74
  Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.NEAREST)
75
  )
76
+ # Invert depth values
77
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
78
  depth_image_resized.max() - depth_image_resized.min()
79
  )
 
94
  # Create Point Cloud from RGBD Image
95
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
96
 
97
+ # Check if the point cloud has enough points
98
+ if len(pcd.points) < 100:
99
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
100
+
101
+ # Estimate and orient normals
102
  if not pcd.has_normals():
103
  print("Estimating normals with increased search radius for sparse data...")
104
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))
105
+
 
106
  if pcd.has_normals():
 
107
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
108
  else:
109
  raise RuntimeError("Failed to estimate normals for the point cloud.")
 
119
  voxel_size=voxel_size,
120
  contraction=o3d.geometry.SimplificationContraction.Average,
121
  )
122
+ mesh = mesh.filter_smooth_simple(number_of_iterations=5)
123
  bbox = pcd.get_axis_aligned_bounding_box()
124
  mesh_crop = mesh.crop(bbox)
125
 
 
138
  fn=process_image,
139
  inputs=[
140
  gr.Image(type="filepath", label="Input Image"),
141
+ gr.File(type="filepath", label="Input Depth Map (optional)"),
142
  ],
143
  outputs=[
144
  gr.Image(label="Predicted Depth", type="pil"),