codic commited on
Commit
5e58814
·
verified ·
1 Parent(s): 674c30c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -61
app.py CHANGED
@@ -29,6 +29,8 @@ def process_image(image_path, depth_map_path=None):
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)
@@ -78,73 +80,66 @@ def process_image(image_path, depth_map_path=None):
78
  gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path, depth=9)
79
  img = Image.fromarray(blended_depth_image)
80
  return [img, gltf_path, gltf_path]
81
- def process_image(image_path, depth_map_path=None):
82
- image_path = Path(image_path)
83
- image_raw = Image.open(image_path).convert("RGB")
84
- image = image_raw.resize(
85
- (2048, int(2048 * image_raw.size[1] / image_raw.size[0])),
86
- Image.Resampling.LANCZOS,
87
- )
88
 
89
- # Remove background using rembg
90
- foreground = remove(image_raw)
91
- foreground = Image.fromarray(np.array(foreground)).convert("RGB")
92
 
93
- # Check if user-provided depth map is available
94
- if depth_map_path:
95
- if depth_map_path.endswith('.npy'):
96
- depth_image = np.load(depth_map_path)
97
- # Invert depth only for npy files
98
- depth_image = 1 - depth_image
99
- else:
100
- depth_image_raw = Image.open(depth_map_path).convert("L")
101
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
102
- depth_image = np.array(depth_image)
103
 
104
- # Normalize depth image
105
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
106
- depth_image = (depth_image * 255).astype('uint8')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  else:
108
- # Generate depth map using DPT model
109
- encoding = feature_extractor(foreground, return_tensors="pt")
110
- with torch.no_grad():
111
- outputs = model(**encoding)
112
- predicted_depth = outputs.predicted_depth
113
 
114
- prediction = torch.nn.functional.interpolate(
115
- predicted_depth.unsqueeze(1),
116
- size=image.size[::-1],
117
- mode="bicubic",
118
- align_corners=False,
119
- ).squeeze()
120
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
121
-
122
- # Resize and apply lighter Gaussian smoothing
123
- depth_image = cv2.resize(depth_image, (image.size[0], image.size[1]), interpolation=cv2.INTER_CUBIC)
124
- mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for more detail
125
-
126
- # Ensure matching size and single channel for blending
127
- if len(depth_image.shape) == 3:
128
- depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
129
-
130
- if len(mask_blurred.shape) == 3:
131
- mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
132
-
133
- # Resize mask_blurred to match depth_image dimensions
134
- mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
135
 
136
- # Blend depth_image with mask_blurred_resized
137
- blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
 
 
 
 
 
 
 
138
 
139
- try:
140
- gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path)
141
- img = Image.fromarray(blended_depth_image)
142
- return [img, gltf_path, gltf_path]
143
- except Exception as e:
144
- print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
145
- gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path, depth=9)
146
- img = Image.fromarray(blended_depth_image)
147
- return [img, gltf_path, gltf_path]
148
 
149
  # Gradio Interface
150
  title = "Depth Estimation & 3D Reconstruction Demo"
@@ -169,4 +164,4 @@ iface = gr.Interface(
169
  allow_flagging="never",
170
  cache_examples=False,
171
  )
172
- iface.launch(debug=True, show_api=True, share=True)
 
29
  if depth_map_path:
30
  if depth_map_path.endswith('.npy'):
31
  depth_image = np.load(depth_map_path)
32
+ # Invert depth only for npy files
33
+ depth_image = 1 - depth_image
34
  else:
35
  depth_image_raw = Image.open(depth_map_path).convert("L")
36
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
 
80
  gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path, depth=9)
81
  img = Image.fromarray(blended_depth_image)
82
  return [img, gltf_path, gltf_path]
 
 
 
 
 
 
 
83
 
 
 
 
84
 
85
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
86
+ # Resize and normalize the depth image
87
+ depth_image_resized = np.array(
88
+ Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
89
+ )
90
+ depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
91
+ depth_image_resized.max() - depth_image_resized.min()
92
+ )
93
+ depth_image_inverted = (1 - depth_image_normalized) * 255
94
+ depth_image_inverted = depth_image_inverted.astype(np.uint8)
95
 
96
+ depth_o3d = o3d.geometry.Image(depth_image_inverted)
97
+ image_o3d = o3d.geometry.Image(rgb_image)
98
+ rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
99
+ image_o3d, depth_o3d, convert_rgb_to_intensity=False
100
+ )
101
+ w, h = rgb_image.shape[1], rgb_image.shape[0]
102
+
103
+ # Camera intrinsic setup
104
+ camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
105
+ camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
106
+
107
+ # Create Point Cloud from RGBD Image
108
+ pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
109
+
110
+ # Check if the point cloud has enough points
111
+ if len(pcd.points) < 100:
112
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
113
+
114
+ # Estimate and orient normals
115
+ if not pcd.has_normals():
116
+ print("Estimating normals with increased search radius for sparse data...")
117
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
118
+
119
+ if pcd.has_normals():
120
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
121
  else:
122
+ raise RuntimeError("Failed to estimate normals for the point cloud.")
 
 
 
 
123
 
124
+ # Poisson Surface Reconstruction
125
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
126
+ pcd, depth=depth, width=0, scale=1.2, linear_fit=True
127
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
+ # Mesh simplification and reduced smoothing for better detail
130
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400 # Decreased voxel size for finer detail
131
+ mesh = mesh_raw.simplify_vertex_clustering(
132
+ voxel_size=voxel_size,
133
+ contraction=o3d.geometry.SimplificationContraction.Average,
134
+ )
135
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3) # Reduced smoothing iterations for sharpness
136
+ bbox = pcd.get_axis_aligned_bounding_box()
137
+ mesh_crop = mesh.crop(bbox)
138
 
139
+ # Save GLTF
140
+ gltf_path = f"./{image_path.stem}.gltf" # Ensure to use .gltf extension and proper file naming
141
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
142
+ return gltf_path
 
 
 
 
 
143
 
144
  # Gradio Interface
145
  title = "Depth Estimation & 3D Reconstruction Demo"
 
164
  allow_flagging="never",
165
  cache_examples=False,
166
  )
167
+ iface.launch(debug=True, show_api=True, share=True)