codic commited on
Commit
5e7fd88
·
verified ·
1 Parent(s): c6fdf9b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -34
app.py CHANGED
@@ -3,33 +3,48 @@ from transformers import DPTFeatureExtractor, DPTForDepthEstimation
3
  import torch
4
  import numpy as np
5
  from PIL import Image
 
6
  import open3d as o3d
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)
 
 
17
  image = image_raw.resize(
18
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
19
  Image.Resampling.LANCZOS,
20
  )
21
 
 
 
 
 
 
 
22
  if depth_map_path:
23
- # Load and resize the user-provided depth map to match the RGB image size
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)
@@ -44,15 +59,21 @@ def process_image(image_path, depth_map_path=None):
44
  ).squeeze()
45
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
46
 
 
 
 
 
 
 
 
 
47
  try:
48
- gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
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,58 +81,53 @@ def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
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,4 +147,4 @@ iface = gr.Interface(
131
  allow_flagging="never",
132
  cache_examples=False,
133
  )
134
- iface.launch(debug=True, show_api=True, share=True)
 
3
  import torch
4
  import numpy as np
5
  from PIL import Image
6
+ from rembg import remove # Add this to use rembg for background separation
7
  import open3d as o3d
8
  from pathlib import Path
9
  import os
10
 
 
11
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
12
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
13
+ from rembg import remove # Add this to use rembg for background separation
14
+ from PIL import Image
15
+ from pathlib import Path
16
+ import numpy as np
17
+ import torch
18
 
19
+ # Update process_image function
20
  def process_image(image_path, depth_map_path=None):
21
  image_path = Path(image_path)
22
  image_raw = Image.open(image_path)
23
+
24
+ # Resize the input image
25
  image = image_raw.resize(
26
  (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
27
  Image.Resampling.LANCZOS,
28
  )
29
 
30
+ # Separate the main subject from the background
31
+ main_subject = remove(image_raw.convert("RGBA")) # Convert to RGBA for transparency
32
+ background = image_raw.convert("RGBA").copy()
33
+ background.paste((255, 255, 255, 0), main_subject.getbbox()) # Make background mostly transparent
34
+
35
+ # Generate or load depth map
36
  if depth_map_path:
37
+ # Load user-provided depth map
38
  depth_image_raw = Image.open(depth_map_path)
39
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
40
  depth_image = np.array(depth_image)
41
+
42
+ # Normalize and adjust the depth map
43
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
44
  depth_image = (depth_image * 255).astype('uint8')
45
+
46
  else:
47
+ # Automatically generate the depth map using the DPT model
48
  encoding = feature_extractor(image, return_tensors="pt")
49
  with torch.no_grad():
50
  outputs = model(**encoding)
 
59
  ).squeeze()
60
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
61
 
62
+ # Apply minimal depth to the background for the panorama effect
63
+ subject_depth = np.array(main_subject.split()[3]) # Use the alpha channel of main_subject as a mask
64
+ depth_image_background = np.zeros_like(subject_depth) + 50 # Minimal depth for background
65
+
66
+ # Combine the subject and background depth maps
67
+ depth_image_combined = np.where(subject_depth > 0, depth_image, depth_image_background)
68
+
69
+ # Continue with 3D object creation using the combined depth map
70
  try:
71
+ gltf_path = create_3d_obj(np.array(image), depth_image_combined, image_path)
72
+ img = Image.fromarray(depth_image_combined)
73
  return [img, gltf_path, gltf_path]
74
  except Exception as e:
75
+ print(f"Error reconstructing 3D model: {e}")
76
+ raise
 
 
77
 
78
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
79
  depth_o3d = o3d.geometry.Image(depth_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 = int(depth_image.shape[1])
85
  h = int(depth_image.shape[0])
86
 
 
87
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
88
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
89
 
 
90
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
91
+
92
+ print("normals")
93
+ pcd.normals = o3d.utility.Vector3dVector(
94
+ np.zeros((1, 3))
95
+ ) # invalidate existing normals
96
  pcd.estimate_normals(
97
+ search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
98
  )
99
  pcd.orient_normals_towards_camera_location(
100
  camera_location=np.array([0.0, 0.0, 1000.0])
101
  )
 
 
102
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
103
+ pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
104
 
105
+ print("run Poisson surface reconstruction")
106
+ with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
107
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
108
+ pcd, depth=depth, width=0, scale=1.1, linear_fit=True
109
  )
110
 
111
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
112
+ print(f"voxel_size = {voxel_size:e}")
113
  mesh = mesh_raw.simplify_vertex_clustering(
114
  voxel_size=voxel_size,
115
  contraction=o3d.geometry.SimplificationContraction.Average,
116
  )
117
 
118
+ # Apply smoothing
119
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3)
120
 
 
121
  bbox = pcd.get_axis_aligned_bounding_box()
122
  mesh_crop = mesh.crop(bbox)
 
 
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
 
128
+
129
+ title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
130
+ 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."
131
  examples = [["examples/" + img] for img in os.listdir("examples/")]
132
 
133
  iface = gr.Interface(
 
147
  allow_flagging="never",
148
  cache_examples=False,
149
  )
150
+ iface.launch(debug=True, show_api=True, share=True)