codic commited on
Commit
00fb9bb
·
verified ·
1 Parent(s): 5b99b62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -67
app.py CHANGED
@@ -6,42 +6,46 @@ from PIL import Image
6
  import open3d as o3d
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")
14
  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")
19
  image = image_raw.resize(
20
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
21
  Image.Resampling.LANCZOS,
22
  )
23
 
24
- # Generate or load depth map
25
  if depth_map_path:
26
- # Check if depth map is in .npy format
27
- if depth_map_path.endswith(".npy"):
28
- # Load the depth map directly as a NumPy array
29
- depth_image = np.load(depth_map_path)
30
- else:
31
- # Load and resize non-npy depth map to match the RGB image size
32
  depth_image_raw = Image.open(depth_map_path)
33
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
34
  depth_image = np.array(depth_image)
 
 
 
 
 
 
35
 
36
- # Normalize depth map to 0–255 range if needed
37
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
38
  depth_image = (depth_image * 255).astype('uint8')
 
39
  else:
40
- # Generate depth map using DPT model if not provided
41
  encoding = feature_extractor(image, return_tensors="pt")
42
  with torch.no_grad():
43
  outputs = model(**encoding)
44
  predicted_depth = outputs.predicted_depth
 
 
45
  prediction = torch.nn.functional.interpolate(
46
  predicted_depth.unsqueeze(1),
47
  size=image.size[::-1],
@@ -50,91 +54,75 @@ def process_image(image_path, depth_map_path=None):
50
  ).squeeze()
51
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
52
 
53
- # Make sure depth image matches dimensions and mode of RGB image for compositing
54
- depth_rgba = Image.fromarray(depth_image).convert("RGBA").resize(image.size)
55
- image_rgba = image.convert("RGBA")
56
-
57
- # Composite depth onto the RGB image background
58
- bg_with_depth = Image.alpha_composite(image_rgba, depth_rgba)
59
-
60
  try:
61
- # Create 3D object from depth and RGB image
62
  gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
63
- return [Image.fromarray(depth_image), gltf_path, gltf_path]
 
64
  except Exception as e:
65
- print("Error reconstructing 3D model:", e)
 
 
 
 
66
  raise Exception("Error reconstructing 3D model")
67
 
68
- def create_3d_obj(rgb_image, depth_image, image_path, depth=8):
69
- # Resize and normalize the depth image
70
- depth_image_resized = np.array(
71
- Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
72
- )
73
- depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
74
- depth_image_resized.max() - depth_image_resized.min()
75
- )
76
- depth_image_inverted = (1 - depth_image_normalized) * 255
77
- depth_image_inverted = depth_image_inverted.astype(np.uint8)
78
-
79
- depth_o3d = o3d.geometry.Image(depth_image_inverted)
80
  image_o3d = o3d.geometry.Image(rgb_image)
81
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
82
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
83
  )
84
- w, h = rgb_image.shape[1], rgb_image.shape[0]
 
85
 
86
- # Camera intrinsic setup
87
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
88
- camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
89
 
90
- # Create Point Cloud from RGBD Image
91
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
92
 
93
- # Check if the point cloud has enough points
94
- if len(pcd.points) < 100:
95
- raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
96
-
97
- # Estimate and orient normals
98
- if not pcd.has_normals():
99
- print("Estimating normals with increased search radius for sparse data...")
100
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.15, max_nn=40))
101
-
102
- if pcd.has_normals():
103
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
104
- else:
105
- raise RuntimeError("Failed to estimate normals for the point cloud.")
106
-
107
- # Poisson Surface Reconstruction
108
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
109
- pcd, depth=depth, width=0, scale=1.2, linear_fit=True
110
  )
 
 
111
 
112
- # Mesh simplification and reduced smoothing for better detail
113
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 612
 
 
 
 
 
 
114
  mesh = mesh_raw.simplify_vertex_clustering(
115
  voxel_size=voxel_size,
116
  contraction=o3d.geometry.SimplificationContraction.Average,
117
  )
 
 
118
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
 
119
  bbox = pcd.get_axis_aligned_bounding_box()
120
  mesh_crop = mesh.crop(bbox)
121
-
122
- # Save GLTF
123
  gltf_path = f"./{image_path.stem}.gltf"
124
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
125
  return gltf_path
126
 
127
- # Gradio Interface
128
- title = "Depth Estimation & 3D Reconstruction Demo"
129
- description = "Upload an image and optionally a depth map (in .npy or image format) to generate a 3D model. If no depth map is provided, the DPT model will generate it."
130
-
131
- examples = [["examples/" + img] for img in os.listdir("examples/")]
132
 
133
  iface = gr.Interface(
134
  fn=process_image,
135
  inputs=[
136
  gr.Image(type="filepath", label="Input Image"),
137
- gr.File(type="filepath", label="Input Depth Map (optional)"),
138
  ],
139
  outputs=[
140
  gr.Image(label="Predicted Depth", type="pil"),
@@ -143,7 +131,6 @@ iface = gr.Interface(
143
  ],
144
  title=title,
145
  description=description,
146
- examples=examples,
147
  allow_flagging="never",
148
  cache_examples=False,
149
  )
 
6
  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
 
13
  def process_image(image_path, depth_map_path=None):
14
  image_path = Path(image_path)
15
+ image_raw = Image.open(image_path)
16
  image = image_raw.resize(
17
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
18
  Image.Resampling.LANCZOS,
19
  )
20
 
21
+ depth_image = None
22
  if depth_map_path:
23
+ # Check if the provided depth map is an image or .npy file
24
+ depth_map_path = Path(depth_map_path)
25
+ if depth_map_path.suffix in ['.jpg', '.jpeg', '.png']:
26
+ # Load and resize depth map image to match the RGB image size
 
 
27
  depth_image_raw = Image.open(depth_map_path)
28
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
29
  depth_image = np.array(depth_image)
30
+ elif depth_map_path.suffix == '.npy':
31
+ # Load depth map from .npy file and resize
32
+ depth_image = np.load(depth_map_path)
33
+ depth_image = np.interp(depth_image, (depth_image.min(), depth_image.max()), (0, 255))
34
+ depth_image = depth_image.astype('uint8')
35
+ depth_image = np.array(Image.fromarray(depth_image).resize(image.size, Image.Resampling.NEAREST))
36
 
37
+ # Normalize depth image if needed
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
+
41
  else:
42
+ # Automatically generate the depth map using the model if no depth map is provided
43
  encoding = feature_extractor(image, return_tensors="pt")
44
  with torch.no_grad():
45
  outputs = model(**encoding)
46
  predicted_depth = outputs.predicted_depth
47
+
48
+ # Interpolate to the original image size
49
  prediction = torch.nn.functional.interpolate(
50
  predicted_depth.unsqueeze(1),
51
  size=image.size[::-1],
 
54
  ).squeeze()
55
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
56
 
 
 
 
 
 
 
 
57
  try:
 
58
  gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
59
+ img = Image.fromarray(depth_image)
60
+ return [img, gltf_path, gltf_path]
61
  except Exception as e:
62
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
63
+ img = Image.fromarray(depth_image)
64
+ return [img, gltf_path, gltf_path]
65
+ except:
66
+ print("Error reconstructing 3D model")
67
  raise Exception("Error reconstructing 3D model")
68
 
69
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
70
+ depth_o3d = o3d.geometry.Image(depth_image)
 
 
 
 
 
 
 
 
 
 
71
  image_o3d = o3d.geometry.Image(rgb_image)
72
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
73
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
74
  )
75
+ w = int(depth_image.shape[1])
76
+ h = int(depth_image.shape[0])
77
 
 
78
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
79
+ camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
80
 
 
81
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
82
 
83
+ print("normals")
84
+ pcd.normals = o3d.utility.Vector3dVector(
85
+ np.zeros((1, 3))
86
+ ) # invalidate existing normals
87
+ pcd.estimate_normals(
88
+ search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
89
+ )
90
+ pcd.orient_normals_towards_camera_location(
91
+ camera_location=np.array([0.0, 0.0, 1000.0])
 
 
 
 
 
 
 
 
92
  )
93
+ pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
94
+ pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
95
 
96
+ print("run Poisson surface reconstruction")
97
+ with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
98
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
99
+ pcd, depth=depth, width=0, scale=1.1, linear_fit=True
100
+ )
101
+
102
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
103
+ print(f"voxel_size = {voxel_size:e}")
104
  mesh = mesh_raw.simplify_vertex_clustering(
105
  voxel_size=voxel_size,
106
  contraction=o3d.geometry.SimplificationContraction.Average,
107
  )
108
+
109
+ # Apply smoothing
110
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
111
+
112
  bbox = pcd.get_axis_aligned_bounding_box()
113
  mesh_crop = mesh.crop(bbox)
 
 
114
  gltf_path = f"./{image_path.stem}.gltf"
115
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
116
  return gltf_path
117
 
118
+ title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
119
+ description = "This demo allows users to provide an RGB image and optionally a depth map as either an image or .npy file to create a 3D object."
 
 
 
120
 
121
  iface = gr.Interface(
122
  fn=process_image,
123
  inputs=[
124
  gr.Image(type="filepath", label="Input Image"),
125
+ gr.File(label="Input Depth Map (optional: Image or .npy)"),
126
  ],
127
  outputs=[
128
  gr.Image(label="Predicted Depth", type="pil"),
 
131
  ],
132
  title=title,
133
  description=description,
 
134
  allow_flagging="never",
135
  cache_examples=False,
136
  )