codic commited on
Commit
a71824a
·
verified ·
1 Parent(s): 7086037

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -46
app.py CHANGED
@@ -31,18 +31,15 @@ def process_image(image_path, depth_map_path=None):
31
  # Check if user-provided depth map is available
32
  if depth_map_path:
33
  if depth_map_path.endswith('.npy'):
34
- depth_image = np.load(depth_map_path)
35
- # Invert depth only for npy files
36
- depth_image = 1 - depth_image
37
  else:
38
  depth_image_raw = Image.open(depth_map_path).convert("L")
39
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
40
- depth_image = np.array(depth_image)
41
-
42
- # Normalize depth image to [0, 1] range
43
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
44
- depth_image = np.clip(depth_image, 0, 1)
45
- depth_image = img_as_ubyte(depth_image)
46
  else:
47
  # Generate depth map using DPT model
48
  encoding = feature_extractor(foreground, return_tensors="pt")
@@ -56,93 +53,107 @@ def process_image(image_path, depth_map_path=None):
56
  mode="bicubic",
57
  align_corners=False,
58
  ).squeeze()
59
- depth_image = prediction.cpu().numpy()
60
-
61
- # Normalize depth image to [0, 1] range before converting
62
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
63
- depth_image = np.clip(depth_image, 0, 1)
64
- depth_image = img_as_ubyte(depth_image)
65
 
66
- # Resize and apply lighter Gaussian smoothing for smoother transitions
67
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
68
- mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for transition
69
-
70
- # Ensure matching size and single channel for blending
71
- if len(depth_image.shape) == 3:
72
- depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
73
- if len(mask_blurred.shape) == 3:
74
- mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
75
 
76
- mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
 
77
 
78
- # Blend depth_image with mask_blurred_resized for smoother transition
79
- blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
 
 
80
 
81
- # Inpaint background where main subject was removed
 
 
 
 
82
  background = remove(image_raw, only_mask=True)
83
- background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR)
84
- background_inpainted = cv2.inpaint(np.array(image_raw), background[:, :, 0], inpaintRadius=3, flags=cv2.INPAINT_TELEA)
85
 
86
  try:
87
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path)
88
- img = Image.fromarray(blended_depth_image)
89
- return [img, gltf_path, gltf_path]
 
90
  except Exception as e:
91
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
92
- gltf_path = create_3d_obj(np.array(foreground), blended_depth_image, background_inpainted, image_path, depth=9)
93
- img = Image.fromarray(blended_depth_image)
94
- return [img, gltf_path, gltf_path]
 
95
 
96
 
97
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
 
98
  depth_image_resized = np.array(
99
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
100
- )
 
 
101
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
102
  depth_image_resized.max() - depth_image_resized.min()
103
- ) * 255
104
- depth_image_normalized = depth_image_normalized.astype(np.uint8)
105
 
106
- depth_o3d = o3d.geometry.Image(depth_image_normalized)
 
107
  image_o3d = o3d.geometry.Image(foreground)
 
 
108
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
109
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
110
  )
111
- w, h = foreground.shape[1], foreground.shape[0]
112
 
 
 
113
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
114
  camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
115
 
 
116
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
117
 
118
  if len(pcd.points) < 100:
119
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
120
 
 
121
  if not pcd.has_normals():
122
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
123
-
124
- if pcd.has_normals():
125
- pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
126
- else:
127
- raise RuntimeError("Failed to estimate normals for the point cloud.")
128
 
 
 
 
 
129
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
130
  pcd, depth=depth, width=0, scale=1.2, linear_fit=True
131
  )
132
 
 
133
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
134
  mesh = mesh_raw.simplify_vertex_clustering(
135
  voxel_size=voxel_size,
136
  contraction=o3d.geometry.SimplificationContraction.Average,
137
  )
138
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
 
 
139
  bbox = pcd.get_axis_aligned_bounding_box()
140
  mesh_crop = mesh.crop(bbox)
141
 
 
142
  gltf_path = f"./{image_path.stem}.gltf"
143
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
144
  return gltf_path
145
 
 
146
  # Gradio Interface
147
  title = "Depth Estimation & 3D Reconstruction Demo"
148
  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."
 
31
  # Check if user-provided depth map is available
32
  if depth_map_path:
33
  if depth_map_path.endswith('.npy'):
34
+ depth_image = np.load(depth_map_path).astype(np.float32)
35
+ depth_image = 1.0 - depth_image # Invert depth only for npy files
 
36
  else:
37
  depth_image_raw = Image.open(depth_map_path).convert("L")
38
+ depth_image = np.array(depth_image_raw.resize(image.size, Image.Resampling.NEAREST)).astype(np.float32)
39
+
40
+ # Normalize and process the depth image for details
41
+ depth_image = normalize_depth_image(depth_image)
42
+ depth_image = gaussian(depth_image, sigma=1.0)
 
 
43
  else:
44
  # Generate depth map using DPT model
45
  encoding = feature_extractor(foreground, return_tensors="pt")
 
53
  mode="bicubic",
54
  align_corners=False,
55
  ).squeeze()
56
+
57
+ # Normalize and process the depth image for details
58
+ depth_image = prediction.cpu().numpy().astype(np.float32)
59
+ depth_image = normalize_depth_image(depth_image)
60
+ depth_image = gaussian(depth_image, sigma=1.0)
 
61
 
62
+ # Resize and apply Gaussian smoothing for smoother transitions
63
  depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
64
+ mask_blurred = cv2.GaussianBlur(depth_image, (5, 5), 1.0).astype(np.float32)
 
 
 
 
 
 
65
 
66
+ # Blend depth_image with mask_blurred for smoother transition
67
+ blended_depth_image = cv2.addWeighted(depth_image, 0.7, mask_blurred, 0.3, 0)
68
 
69
+ # Sharpen subject edges slightly for better detail
70
+ foreground_edges = cv2.Canny(np.array(foreground), 100, 200)
71
+ foreground_edges_resized = cv2.resize(foreground_edges, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
72
+ blended_depth_image[foreground_edges_resized > 0] *= 1.2
73
 
74
+ # Create mask for the main subject
75
+ mask = (depth_image > 0).astype(np.float32) # Keep as float32
76
+ mask = clear_border(mask) # Clear objects touching the border
77
+
78
+ # Inpaint background where the main subject was removed
79
  background = remove(image_raw, only_mask=True)
80
+ background = cv2.cvtColor(np.array(background), cv2.COLOR_GRAY2BGR).astype(np.float32)
81
+ background_inpainted = inpaint_background(np.array(image_raw).astype(np.float32), mask)
82
 
83
  try:
84
+ gltf_path = create_3d_obj(np.array(foreground).astype(np.float32), blended_depth_image, background_inpainted, image_path)
85
+ # Convert to uint8 only for display
86
+ img = Image.fromarray(img_as_ubyte(blended_depth_image))
87
+ return [img, gr.Model3D(), gltf_path]
88
  except Exception as e:
89
  print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
90
+ gltf_path = create_3d_obj(np.array(foreground).astype(np.float32), blended_depth_image, background_inpainted, image_path, depth=9)
91
+ img = Image.fromarray(img_as_ubyte(blended_depth_image))
92
+ return [img, gr.Model3D(), gltf_path]
93
+
94
 
95
 
96
  def create_3d_obj(foreground, depth_image, background, image_path, depth=10):
97
+ # Resize and normalize the depth image, keeping it as float32
98
  depth_image_resized = np.array(
99
  Image.fromarray(depth_image).resize(foreground.shape[:2][::-1], Image.LANCZOS)
100
+ ).astype(np.float32) # Keep as float32 for precision
101
+
102
+ # Normalize depth values to the range [0, 1]
103
  depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
104
  depth_image_resized.max() - depth_image_resized.min()
105
+ )
 
106
 
107
+ # Create Open3D images with float32 depth
108
+ depth_o3d = o3d.geometry.Image((depth_image_normalized * 255).astype(np.uint8)) # For compatibility with Open3D
109
  image_o3d = o3d.geometry.Image(foreground)
110
+
111
+ # Create RGBD image directly using the Open3D images
112
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
113
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
114
  )
 
115
 
116
+ # Get width and height for camera intrinsic setup
117
+ w, h = foreground.shape[1], foreground.shape[0]
118
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
119
  camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
120
 
121
+ # Create the point cloud from the RGBD image
122
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
123
 
124
  if len(pcd.points) < 100:
125
  raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
126
 
127
+ # Estimate normals if they are not present
128
  if not pcd.has_normals():
129
  pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
 
 
 
 
 
130
 
131
+ # Orient normals towards the camera location
132
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
133
+
134
+ # Create mesh using Poisson reconstruction
135
  mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
136
  pcd, depth=depth, width=0, scale=1.2, linear_fit=True
137
  )
138
 
139
+ # Simplify and smooth the mesh
140
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400
141
  mesh = mesh_raw.simplify_vertex_clustering(
142
  voxel_size=voxel_size,
143
  contraction=o3d.geometry.SimplificationContraction.Average,
144
  )
145
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
146
+
147
+ # Crop the mesh to fit the bounding box of the point cloud
148
  bbox = pcd.get_axis_aligned_bounding_box()
149
  mesh_crop = mesh.crop(bbox)
150
 
151
+ # Save the triangle mesh to a GLTF file
152
  gltf_path = f"./{image_path.stem}.gltf"
153
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
154
  return gltf_path
155
 
156
+
157
  # Gradio Interface
158
  title = "Depth Estimation & 3D Reconstruction Demo"
159
  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."