codic commited on
Commit
c6fdf9b
·
verified ·
1 Parent(s): 572fff2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -29
app.py CHANGED
@@ -7,8 +7,10 @@ import open3d as o3d
7
  from pathlib import Path
8
  import os
9
 
 
10
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
11
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
 
12
  def process_image(image_path, depth_map_path=None):
13
  image_path = Path(image_path)
14
  image_raw = Image.open(image_path)
@@ -22,17 +24,12 @@ def process_image(image_path, depth_map_path=None):
22
  depth_image_raw = Image.open(depth_map_path)
23
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
24
  depth_image = np.array(depth_image)
25
-
26
- # Adjust the depth map based on the Depth-Anything-V2 format
27
- # Normalize depth if needed (assuming values are not scaled to 0-255)
28
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
29
  depth_image = (depth_image * 255).astype('uint8')
30
-
31
- # Optionally invert the depth map if it's inverse (like MiDaS)
32
- # depth_image = np.max(depth_image) - depth_image
33
-
34
  else:
35
- # Automatically generate the depth map using the model (if no depth map provided)
36
  encoding = feature_extractor(image, return_tensors="pt")
37
  with torch.no_grad():
38
  outputs = model(**encoding)
@@ -52,12 +49,10 @@ def process_image(image_path, depth_map_path=None):
52
  img = Image.fromarray(depth_image)
53
  return [img, gltf_path, gltf_path]
54
  except Exception as e:
 
55
  gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
56
  img = Image.fromarray(depth_image)
57
  return [img, gltf_path, gltf_path]
58
- except:
59
- print("Error reconstructing 3D model")
60
- raise Exception("Error reconstructing 3D model")
61
 
62
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
63
  depth_o3d = o3d.geometry.Image(depth_image)
@@ -65,53 +60,58 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
65
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
66
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
67
  )
 
68
  w = int(depth_image.shape[1])
69
  h = int(depth_image.shape[0])
70
 
 
71
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
72
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
73
 
 
74
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
75
-
76
- print("normals")
77
- pcd.normals = o3d.utility.Vector3dVector(
78
- np.zeros((1, 3))
79
- ) # invalidate existing normals
80
  pcd.estimate_normals(
81
- search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
82
  )
83
  pcd.orient_normals_towards_camera_location(
84
  camera_location=np.array([0.0, 0.0, 1000.0])
85
  )
 
 
86
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
87
- pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
88
 
89
- print("run Poisson surface reconstruction")
90
- with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
91
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
92
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
93
  )
94
 
95
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
96
- print(f"voxel_size = {voxel_size:e}")
97
  mesh = mesh_raw.simplify_vertex_clustering(
98
  voxel_size=voxel_size,
99
  contraction=o3d.geometry.SimplificationContraction.Average,
100
  )
101
 
102
- # Apply smoothing
103
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
104
 
 
105
  bbox = pcd.get_axis_aligned_bounding_box()
106
  mesh_crop = mesh.crop(bbox)
 
 
107
  gltf_path = f"./{image_path.stem}.gltf"
108
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
109
  return gltf_path
110
 
111
 
112
-
113
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
114
- description = "This demo allows users to provide an RGB image and optionally a depth map to create a 3D object. If no depth map is provided, the DPT model will generate it."
115
  examples = [["examples/" + img] for img in os.listdir("examples/")]
116
 
117
  iface = gr.Interface(
@@ -131,4 +131,4 @@ iface = gr.Interface(
131
  allow_flagging="never",
132
  cache_examples=False,
133
  )
134
- iface.launch(debug=True, show_api=True, share=True)
 
7
  from pathlib import Path
8
  import os
9
 
10
+ # Initialize model and feature extractor
11
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
12
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
13
+
14
  def process_image(image_path, depth_map_path=None):
15
  image_path = Path(image_path)
16
  image_raw = Image.open(image_path)
 
24
  depth_image_raw = Image.open(depth_map_path)
25
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
26
  depth_image = np.array(depth_image)
27
+
28
+ # Normalize depth if needed
 
29
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
30
  depth_image = (depth_image * 255).astype('uint8')
 
 
 
 
31
  else:
32
+ # Automatically generate the depth map using the model
33
  encoding = feature_extractor(image, return_tensors="pt")
34
  with torch.no_grad():
35
  outputs = model(**encoding)
 
49
  img = Image.fromarray(depth_image)
50
  return [img, gltf_path, gltf_path]
51
  except Exception as e:
52
+ # Retry with a reduced depth setting in case of failure
53
  gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
54
  img = Image.fromarray(depth_image)
55
  return [img, gltf_path, gltf_path]
 
 
 
56
 
57
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
58
  depth_o3d = o3d.geometry.Image(depth_image)
 
60
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
61
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
62
  )
63
+
64
  w = int(depth_image.shape[1])
65
  h = int(depth_image.shape[0])
66
 
67
+ # Set up camera intrinsics
68
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
69
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
70
 
71
+ # Create point cloud from RGBD image
72
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
73
+
74
+ # Estimate normals with increased detail
75
+ pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Reset normals
 
 
76
  pcd.estimate_normals(
77
+ search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.03, max_nn=50) # Smaller radius, more neighbors
78
  )
79
  pcd.orient_normals_towards_camera_location(
80
  camera_location=np.array([0.0, 0.0, 1000.0])
81
  )
82
+
83
+ # Transform point cloud for correct orientation
84
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
 
85
 
86
+ # Apply Poisson surface reconstruction with increased depth
87
+ with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
88
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
89
+ pcd, depth=12, width=0, scale=1.1, linear_fit=True # Adjust depth for finer detail
90
  )
91
 
92
+ # Reduce voxel size for a denser mesh
93
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 1024 # Smaller voxel size
94
  mesh = mesh_raw.simplify_vertex_clustering(
95
  voxel_size=voxel_size,
96
  contraction=o3d.geometry.SimplificationContraction.Average,
97
  )
98
 
99
+ # Apply minimal smoothing to retain details
100
+ mesh = mesh.filter_smooth_simple(number_of_iterations=1)
101
 
102
+ # Crop mesh to fit within the bounding box of the point cloud
103
  bbox = pcd.get_axis_aligned_bounding_box()
104
  mesh_crop = mesh.crop(bbox)
105
+
106
+ # Save as GLTF file
107
  gltf_path = f"./{image_path.stem}.gltf"
108
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
109
  return gltf_path
110
 
111
 
112
+ # Gradio interface setup
113
+ title = "Demo: Enhanced Depth Estimation & 3D Reconstruction"
114
+ description = "Upload an image (and optionally a depth map) to generate a detailed 3D object."
115
  examples = [["examples/" + img] for img in os.listdir("examples/")]
116
 
117
  iface = gr.Interface(
 
131
  allow_flagging="never",
132
  cache_examples=False,
133
  )
134
+ iface.launch(debug=True, show_api=True, share=True)