codic commited on
Commit
8cd6e80
·
verified ·
1 Parent(s): 1ef4dc8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -49
app.py CHANGED
@@ -6,106 +6,112 @@ 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 # Import the rembg library for background removal
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") # Ensure the image is in RGB format
19
  image = image_raw.resize(
20
- (640, int(640 * image_raw.size[1] / image_raw.size[0])), # Resizing for speed
21
  Image.Resampling.LANCZOS,
22
  )
23
 
24
- # Remove background using rembg
25
- foreground = remove(image_raw) # Remove background
26
- foreground = Image.fromarray(np.array(foreground)) # Convert back to PIL Image
27
- foreground = foreground.convert("RGB") # Ensure the foreground is in RGB format
 
28
 
29
- # Generate depth map
30
- depth_image = generate_depth(foreground, depth_map_path, image.size)
 
 
31
 
32
- # Apply Gaussian smoothing on the depth map
33
- smoothed_depth_map = cv2.GaussianBlur(depth_image, (5, 5), 0)
34
 
35
- # Create 3D object from RGB and depth images
36
- try:
37
- gltf_path = create_3d_obj(np.array(image), smoothed_depth_map, image_path)
38
- img = Image.fromarray(smoothed_depth_map)
39
- return [img, gltf_path, gltf_path]
40
- except Exception as e:
41
- print(f"Error reconstructing 3D model: {e}")
42
- raise Exception("Error reconstructing 3D model")
43
-
44
- def generate_depth(foreground, depth_map_path, size):
45
- if depth_map_path:
46
- depth_image_raw = Image.open(depth_map_path).convert("L") # Convert to grayscale
47
- depth_image = depth_image_raw.resize(size, Image.Resampling.NEAREST)
48
- depth_image = np.array(depth_image)
49
  else:
50
- encoding = feature_extractor(foreground, return_tensors="pt")
 
51
  with torch.no_grad():
52
  outputs = model(**encoding)
53
  predicted_depth = outputs.predicted_depth
54
 
 
55
  prediction = torch.nn.functional.interpolate(
56
  predicted_depth.unsqueeze(1),
57
- size=size[::-1],
58
  mode="bicubic",
59
  align_corners=False,
60
  ).squeeze()
61
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
62
 
63
- # Normalize depth image to match expected format
64
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
65
- return (depth_image * 255).astype('uint8')
 
 
 
 
 
 
 
 
66
 
67
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
68
- # Step 1: Create Open3D images
69
  depth_o3d = o3d.geometry.Image(depth_image)
70
  image_o3d = o3d.geometry.Image(rgb_image)
71
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
72
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
73
  )
74
- w, h = depth_image.shape[1], depth_image.shape[0]
 
75
 
76
- # Camera intrinsic setup for 3D point cloud
77
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
78
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
79
 
80
- # Point Cloud and Normals
81
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
82
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
83
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
84
 
85
- # Poisson Surface Reconstruction
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
- # Step 3: Mesh simplification and smoothing
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
  bbox = pcd.get_axis_aligned_bounding_box()
98
  mesh_crop = mesh.crop(bbox)
99
-
100
- # Save GLTF
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
106
- title = "Depth Estimation & 3D Reconstruction Demo"
107
- description = "Upload an image and optionally a depth map to generate a 3D model. If no depth map is provided, the DPT model will generate it."
108
 
 
 
 
109
  examples = [["examples/" + img] for img in os.listdir("examples/")]
110
 
111
  iface = gr.Interface(
@@ -125,4 +131,4 @@ iface = gr.Interface(
125
  allow_flagging="never",
126
  cache_examples=False,
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
 
 
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)
15
  image = image_raw.resize(
16
+ (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
17
  Image.Resampling.LANCZOS,
18
  )
19
 
20
+ if depth_map_path:
21
+ # Load and resize the user-provided depth map to match the RGB image size
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)
39
  predicted_depth = outputs.predicted_depth
40
 
41
+ # Interpolate to original size
42
  prediction = torch.nn.functional.interpolate(
43
  predicted_depth.unsqueeze(1),
44
+ size=image.size[::-1],
45
  mode="bicubic",
46
  align_corners=False,
47
  ).squeeze()
48
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
49
 
50
+ try:
51
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
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)
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 = 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
  allow_flagging="never",
132
  cache_examples=False,
133
  )
134
+ iface.launch(debug=True, show_api=True, share=True)