codic commited on
Commit
09a82dd
·
verified ·
1 Parent(s): 644965a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -9
app.py CHANGED
@@ -25,6 +25,7 @@ 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
  if depth_map_path:
29
  if depth_map_path.endswith('.npy'):
30
  depth_image = np.load(depth_map_path)
@@ -33,9 +34,11 @@ def process_image(image_path, depth_map_path=None):
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,14 +52,17 @@ def process_image(image_path, depth_map_path=None):
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)
@@ -95,29 +101,31 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
95
  # Estimate and orient normals
96
  if not pcd.has_normals():
97
  print("Estimating normals with increased search radius for sparse data...")
98
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))
99
-
100
  if pcd.has_normals():
101
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
102
  else:
103
  raise RuntimeError("Failed to estimate normals for the point cloud.")
104
 
105
- # Poisson Surface Reconstruction with a suitable depth
106
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
107
  pcd, depth=depth, width=0, scale=1.1, linear_fit=True
108
  )
109
 
110
- # Increase mesh quality by reducing voxel size
111
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 256 # Reduced for higher detail
112
  mesh = mesh_raw.simplify_vertex_clustering(
113
  voxel_size=voxel_size,
114
  contraction=o3d.geometry.SimplificationContraction.Average,
115
  )
116
  mesh = mesh.filter_smooth_simple(number_of_iterations=5)
 
 
117
 
118
- # Save the mesh without cropping
119
  gltf_path = f"./{image_path.stem}.gltf"
120
- o3d.io.write_triangle_mesh(gltf_path, mesh, write_triangle_uvs=True)
121
  return gltf_path
122
 
123
  # Gradio Interface
@@ -143,5 +151,4 @@ iface = gr.Interface(
143
  allow_flagging="never",
144
  cache_examples=False,
145
  )
146
-
147
  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
+ # 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
  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
  ).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)
 
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.2, 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
  )
115
 
116
+ # Mesh simplification and smoothing
117
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 256
118
  mesh = mesh_raw.simplify_vertex_clustering(
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
 
126
+ # Save GLTF
127
  gltf_path = f"./{image_path.stem}.gltf"
128
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
129
  return gltf_path
130
 
131
  # Gradio Interface
 
151
  allow_flagging="never",
152
  cache_examples=False,
153
  )
 
154
  iface.launch(debug=True, show_api=True, share=True)