codic commited on
Commit
3e257f9
·
verified ·
1 Parent(s): 1b86059

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -46
app.py CHANGED
@@ -6,39 +6,44 @@ from PIL import Image
6
  import open3d as o3d
7
  from pathlib import Path
8
  import os
 
 
9
 
10
- # Load the DPT model and feature extractor for depth estimation
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)
17
  image = image_raw.resize(
18
- (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
19
  Image.Resampling.LANCZOS,
20
  )
21
 
22
- # Check if a depth map is provided; support both .npy and image formats
 
 
 
 
23
  if depth_map_path:
24
  if depth_map_path.endswith('.npy'):
25
  depth_image = np.load(depth_map_path)
26
  else:
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
 
31
- # Normalize and adjust the depth map to improve visualization
32
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
33
  depth_image = (depth_image * 255).astype('uint8')
34
  else:
35
- # Automatically generate a depth map if none is provided
36
- encoding = feature_extractor(image, return_tensors="pt")
37
  with torch.no_grad():
38
  outputs = model(**encoding)
39
  predicted_depth = outputs.predicted_depth
40
 
41
- # Resize depth map to the original image size
42
  prediction = torch.nn.functional.interpolate(
43
  predicted_depth.unsqueeze(1),
44
  size=image.size[::-1],
@@ -47,71 +52,90 @@ def process_image(image_path, depth_map_path=None):
47
  ).squeeze()
48
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
49
 
 
 
 
 
50
  try:
51
- # Create the 3D object from the image and depth map
52
- gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
53
- img = Image.fromarray(depth_image)
54
  return [img, gltf_path, gltf_path]
55
- except Exception as e:
56
- # Retry with a different Poisson depth if initial attempt fails
57
- gltf_path = create_3d_obj(np.array(image), depth_image, image_path, depth=8)
58
- img = Image.fromarray(depth_image)
59
  return [img, gltf_path, gltf_path]
60
 
61
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
62
- # Convert depth and RGB images to Open3D format
63
- depth_o3d = o3d.geometry.Image(depth_image)
 
 
 
 
 
 
 
 
 
64
  image_o3d = o3d.geometry.Image(rgb_image)
65
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
66
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
67
  )
68
- w, h = depth_image.shape[1], depth_image.shape[0]
69
 
70
- # Set camera intrinsics for depth estimation
71
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
72
- camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
73
 
74
- # Generate a point cloud from the RGBD image
75
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
76
 
77
- # Normalize and orient point cloud
78
- pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
79
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
80
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
81
- pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
82
- pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
83
-
84
- # Poisson surface reconstruction for creating a 3D mesh from the point cloud
85
- with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
86
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
87
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
88
- )
89
-
90
- # Simplify and smooth the mesh to improve visual quality
91
- voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
 
 
 
 
 
 
92
  mesh = mesh_raw.simplify_vertex_clustering(
93
  voxel_size=voxel_size,
94
  contraction=o3d.geometry.SimplificationContraction.Average,
95
  )
96
- mesh = mesh.filter_smooth_simple(number_of_iterations=3)
97
-
98
- # Crop the mesh to the bounding box for alignment
99
  bbox = pcd.get_axis_aligned_bounding_box()
100
  mesh_crop = mesh.crop(bbox)
 
 
101
  gltf_path = f"./{image_path.stem}.gltf"
102
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
103
  return gltf_path
104
 
105
- # Gradio interface configuration
106
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
107
- description = "This demo allows users to provide an RGB image and optionally a depth map (in image or .npy format) to create a 3D object. If no depth map is provided, the DPT model will generate it."
 
108
  examples = [["examples/" + img] for img in os.listdir("examples/")]
109
 
110
  iface = gr.Interface(
111
  fn=process_image,
112
  inputs=[
113
  gr.Image(type="filepath", label="Input Image"),
114
- gr.Image(type="filepath", label="Input Depth Map (optional)"),
115
  ],
116
  outputs=[
117
  gr.Image(label="Predicted Depth", type="pil"),
@@ -124,5 +148,4 @@ iface = gr.Interface(
124
  allow_flagging="never",
125
  cache_examples=False,
126
  )
127
-
128
  iface.launch(debug=True, show_api=True, share=True)
 
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
+ (2048, int(2048 * 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:
41
+ # Generate depth map using DPT model
42
+ encoding = feature_extractor(foreground, return_tensors="pt")
43
  with torch.no_grad():
44
  outputs = model(**encoding)
45
  predicted_depth = outputs.predicted_depth
46
 
 
47
  prediction = torch.nn.functional.interpolate(
48
  predicted_depth.unsqueeze(1),
49
  size=image.size[::-1],
 
52
  ).squeeze()
53
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
54
 
55
+ # Resize and apply lighter Gaussian smoothing
56
+ depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
57
+ smoothed_depth_map = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for more detail
58
+
59
  try:
60
+ gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path)
61
+ img = Image.fromarray(smoothed_depth_map)
 
62
  return [img, gltf_path, gltf_path]
63
+ except Exception:
64
+ print("Error with default depth. Retrying with a shallower depth.")
65
+ gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path, depth=9)
66
+ img = Image.fromarray(smoothed_depth_map)
67
  return [img, gltf_path, gltf_path]
68
 
69
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
70
+ # Resize and normalize the depth image
71
+ depth_image_resized = np.array(
72
+ Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
73
+ )
74
+ depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
75
+ depth_image_resized.max() - depth_image_resized.min()
76
+ )
77
+ depth_image_inverted = (1 - depth_image_normalized) * 255
78
+ depth_image_inverted = depth_image_inverted.astype(np.uint8)
79
+
80
+ depth_o3d = o3d.geometry.Image(depth_image_inverted)
81
  image_o3d = o3d.geometry.Image(rgb_image)
82
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
83
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
84
  )
85
+ w, h = rgb_image.shape[1], rgb_image.shape[0]
86
 
87
+ # Camera intrinsic setup
88
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
89
+ camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
90
 
91
+ # Create Point Cloud from RGBD Image
92
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
93
 
94
+ # Check if the point cloud has enough points
95
+ if len(pcd.points) < 100:
96
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
97
+
98
+ # Estimate and orient normals
99
+ if not pcd.has_normals():
100
+ print("Estimating normals with increased search radius for sparse data...")
101
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
102
+
103
+ if pcd.has_normals():
104
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
105
+ else:
106
+ raise RuntimeError("Failed to estimate normals for the point cloud.")
107
+
108
+ # Poisson Surface Reconstruction
109
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
110
+ pcd, depth=depth, width=0, scale=1.2, linear_fit=True
111
+ )
112
+
113
+ # Mesh simplification and reduced smoothing for better detail
114
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400 # Decreased voxel size for finer detail
115
  mesh = mesh_raw.simplify_vertex_clustering(
116
  voxel_size=voxel_size,
117
  contraction=o3d.geometry.SimplificationContraction.Average,
118
  )
119
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3) # Reduced smoothing iterations for sharpness
 
 
120
  bbox = pcd.get_axis_aligned_bounding_box()
121
  mesh_crop = mesh.crop(bbox)
122
+
123
+ # Save GLTF
124
  gltf_path = f"./{image_path.stem}.gltf"
125
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
126
  return gltf_path
127
 
128
+ # Gradio Interface
129
+ title = "Depth Estimation & 3D Reconstruction Demo"
130
+ 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."
131
+
132
  examples = [["examples/" + img] for img in os.listdir("examples/")]
133
 
134
  iface = gr.Interface(
135
  fn=process_image,
136
  inputs=[
137
  gr.Image(type="filepath", label="Input Image"),
138
+ gr.File(type="filepath", label="Input Depth Map (optional)"),
139
  ],
140
  outputs=[
141
  gr.Image(label="Predicted Depth", type="pil"),
 
148
  allow_flagging="never",
149
  cache_examples=False,
150
  )
 
151
  iface.launch(debug=True, show_api=True, share=True)