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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -24
app.py CHANGED
@@ -25,7 +25,6 @@ def process_image(image_path, depth_map_path=None):
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)
@@ -34,11 +33,9 @@ def process_image(image_path, depth_map_path=None):
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:
41
- # Generate depth map using DPT model
42
  encoding = feature_extractor(foreground, return_tensors="pt")
43
  with torch.no_grad():
44
  outputs = model(**encoding)
@@ -52,28 +49,24 @@ def process_image(image_path, depth_map_path=None):
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
  )
@@ -87,28 +80,20 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
87
  )
88
  w, h = rgb_image.shape[1], rgb_image.shape[0]
89
 
90
- # Camera intrinsic setup
91
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
92
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
93
 
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.")
110
 
111
- # Poisson Surface Reconstruction
112
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
113
  pcd, depth=depth, width=0, scale=1.1, linear_fit=True
114
  )
@@ -119,7 +104,7 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
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
 
@@ -151,4 +136,5 @@ iface = gr.Interface(
151
  allow_flagging="never",
152
  cache_examples=False,
153
  )
 
154
  iface.launch(debug=True, show_api=True, share=True)
 
25
  foreground = remove(image_raw)
26
  foreground = Image.fromarray(np.array(foreground)).convert("RGB")
27
 
 
28
  if depth_map_path:
29
  if depth_map_path.endswith('.npy'):
30
  depth_image = np.load(depth_map_path)
 
33
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
34
  depth_image = np.array(depth_image)
35
 
 
36
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
37
  depth_image = (depth_image * 255).astype('uint8')
38
  else:
 
39
  encoding = feature_extractor(foreground, return_tensors="pt")
40
  with torch.no_grad():
41
  outputs = model(**encoding)
 
49
  ).squeeze()
50
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
51
 
 
52
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
 
 
53
  smoothed_depth_map = cv2.GaussianBlur(depth_image, (5, 5), 0)
54
 
55
  try:
56
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path)
57
  img = Image.fromarray(smoothed_depth_map)
58
  return [img, gltf_path, gltf_path]
59
+ except Exception as e:
60
  print("Error with default depth. Retrying with a shallower depth.")
61
  gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path, depth=8)
62
  img = Image.fromarray(smoothed_depth_map)
63
  return [img, gltf_path, gltf_path]
64
 
65
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
 
66
  depth_image_resized = np.array(
67
  Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.NEAREST)
68
  )
69
+
70
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
71
  depth_image_resized.max() - depth_image_resized.min()
72
  )
 
80
  )
81
  w, h = rgb_image.shape[1], rgb_image.shape[0]
82
 
 
83
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
84
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
85
 
 
86
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
87
 
 
 
 
 
 
88
  if not pcd.has_normals():
89
+ print("Estimating normals...")
90
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
91
+
92
  if pcd.has_normals():
93
+ print("Orienting normals towards camera location...")
94
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 0.0])) # Adjusted camera position
 
95
 
96
+ # Apply Poisson Surface Reconstruction with adjusted depth for better detail
97
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
98
  pcd, depth=depth, width=0, scale=1.1, linear_fit=True
99
  )
 
104
  voxel_size=voxel_size,
105
  contraction=o3d.geometry.SimplificationContraction.Average,
106
  )
107
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3)
108
  bbox = pcd.get_axis_aligned_bounding_box()
109
  mesh_crop = mesh.crop(bbox)
110
 
 
136
  allow_flagging="never",
137
  cache_examples=False,
138
  )
139
+
140
  iface.launch(debug=True, show_api=True, share=True)