codic commited on
Commit
35a9d43
·
verified ·
1 Parent(s): 50322fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -84
app.py CHANGED
@@ -9,34 +9,37 @@ import os
9
  import cv2
10
  from rembg import remove
11
 
12
- # Load the DPT model 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)
 
 
 
 
19
 
20
- # Resize image to 1600 width while maintaining aspect ratio
21
- new_width = 1600
22
- new_height = int(new_width * image_raw.size[1] / image_raw.size[0])
23
- image = image_raw.resize((new_width, new_height), Image.Resampling.LANCZOS)
24
 
 
25
  if depth_map_path:
26
- # Determine if depth map is npy or image format
27
- if depth_map_path.endswith(".npy"):
28
  depth_image = np.load(depth_map_path)
29
  else:
30
- depth_image_raw = Image.open(depth_map_path)
31
  depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
32
  depth_image = np.array(depth_image)
33
 
34
- # Normalize depth if needed
35
  depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
36
  depth_image = (depth_image * 255).astype('uint8')
37
  else:
38
- # Generate depth using DPT if not provided
39
- encoding = feature_extractor(image, return_tensors="pt")
40
  with torch.no_grad():
41
  outputs = model(**encoding)
42
  predicted_depth = outputs.predicted_depth
@@ -49,95 +52,103 @@ def process_image(image_path, depth_map_path=None):
49
  ).squeeze()
50
  depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
51
 
52
- # Create a mask of the main subject using rembg
53
- main_subject_mask = create_main_subject_mask(image)
 
 
 
 
 
54
 
55
- # Apply mask to depth map: keep depth for main subject only, set background depth to zero
56
- subject_depth_map = np.where(main_subject_mask == 255, depth_image, 0)
57
 
58
- # Create inpainted background with OpenCV
59
- inpainted_bg = inpaint_background(image, np.array(image_raw.resize((new_width, new_height))))
60
 
61
- # Scale inpainted background slightly to fill view
62
- inpainted_bg = cv2.resize(inpainted_bg, None, fx=1.05, fy=1.05, interpolation=cv2.INTER_LINEAR)
63
 
64
  try:
65
- gltf_path = create_3d_obj(np.array(image), subject_depth_map, image_path, inpainted_bg, main_subject_offset=0.2)
66
- img = Image.fromarray(subject_depth_map)
67
  return [img, gltf_path, gltf_path]
68
  except Exception as e:
69
- print(f"Detailed error: {e}")
70
- raise Exception("Error reconstructing 3D model") from e
71
-
72
- def create_main_subject_mask(image):
73
- """Generates a binary mask for the main subject using rembg."""
74
- # Remove background and create mask
75
- subject_only = remove(image)
76
- subject_mask = Image.fromarray((np.array(subject_only)[:, :, 3] > 0).astype(np.uint8) * 255)
77
- return np.array(subject_mask)
78
-
79
- def inpaint_background(image, original_image):
80
- # Resize `image` to match `original_image` dimensions
81
- resized_image = image.resize(original_image.shape[1::-1]) # Resize to (width, height)
82
-
83
- # Convert to grayscale and create the mask in `uint8` format
84
- mask = np.array(resized_image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
85
-
86
- # Apply inpainting
87
- inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
88
- return inpainted_image
89
-
90
- def extract_subject_depth(depth_image, image):
91
- # Assuming we have a mask or logic to isolate the main subject in the depth map
92
- # Only retain depth of main subject, setting background to zero
93
- mask = np.array(image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1")).astype(np.uint8)
94
- subject_depth_map = np.where(mask == 255, depth_image, 0) # Set bg depth to zero
95
- return subject_depth_map
96
-
97
- def create_3d_obj(image, depth_image, image_path, inpainted_bg, main_subject_offset=0.2):
98
- # Ensure depth_image has only main subject depth and no background depth
99
- depth_image = np.array(depth_image)
100
-
101
- # Print shapes and depth range for debugging
102
- print(f"Image shape: {image.shape}, Depth map shape: {depth_image.shape}")
103
- print(f"Depth map min/max: {depth_image.min()}/{depth_image.max()}")
104
-
105
- # Convert image and depth_image to Open3D format
106
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
107
- o3d.geometry.Image(image.astype(np.uint8)),
108
- o3d.geometry.Image(depth_image.astype(np.float32)),
109
- convert_rgb_to_intensity=False
110
  )
111
-
112
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, o3d.camera.PinholeCameraIntrinsic(
113
- width=image.shape[1], height=image.shape[0], fx=1.0, fy=1.0, cx=image.shape[1] / 2, cy=image.shape[0] / 2))
114
 
115
- # Flatten the back of the main subject
116
- for point in pcd.points:
117
- if point[2] < main_subject_offset:
118
- point[2] = main_subject_offset # Make the back flat
119
-
120
- # Bring main subject closer to the viewer
121
- for point in pcd.points:
122
- if point[2] > main_subject_offset:
123
- point[2] += main_subject_offset # Offset main subject depth
 
 
 
 
 
 
124
 
125
- # Avoid cropping: retain original size and save the entire model
126
- gltf_path = f"./{image_path.stem}.gltf"
127
- o3d.io.write_point_cloud(gltf_path, pcd) # Save as point cloud instead of mesh
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  return gltf_path
129
 
130
- title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
131
- description = (
132
- "Upload an RGB image and optionally a depth map (image or npy) to create a 3D model. "
133
- "Background remains unchanged and un-cropped, with a panoramic effect for a more immersive experience."
134
- )
135
 
136
  iface = gr.Interface(
137
  fn=process_image,
138
  inputs=[
139
  gr.Image(type="filepath", label="Input Image"),
140
- gr.File(type="filepath", label="Input Depth Map (optional)"), # Changed to File
141
  ],
142
  outputs=[
143
  gr.Image(label="Predicted Depth", type="pil"),
@@ -146,8 +157,8 @@ iface = gr.Interface(
146
  ],
147
  title=title,
148
  description=description,
 
149
  allow_flagging="never",
150
  cache_examples=False,
151
  )
152
-
153
  iface.launch(debug=True, show_api=True, share=True)
 
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
 
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
+ mask_blurred = cv2.GaussianBlur(depth_image, (3, 3), 0.8) # Lighter blur for more detail
58
+
59
+ # Ensure matching size and single channel for blending
60
+ if len(depth_image.shape) == 3:
61
+ depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2GRAY)
62
 
63
+ if len(mask_blurred.shape) == 3:
64
+ mask_blurred = cv2.cvtColor(mask_blurred, cv2.COLOR_BGR2GRAY)
65
 
66
+ # Resize mask_blurred to match depth_image dimensions
67
+ mask_blurred_resized = cv2.resize(mask_blurred, (depth_image.shape[1], depth_image.shape[0]), interpolation=cv2.INTER_LINEAR)
68
 
69
+ # Blend depth_image with mask_blurred_resized
70
+ blended_depth_image = cv2.addWeighted(depth_image, 0.8, mask_blurred_resized, 0.2, 0)
71
 
72
  try:
73
+ gltf_path = create_3d_obj(np.array(image), blended_depth_image, image_path)
74
+ img = Image.fromarray(blended_depth_image)
75
  return [img, gltf_path, gltf_path]
76
  except Exception as e:
77
+ print(f"Error with default depth: {str(e)}. Retrying with a shallower depth.")
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
+
82
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
83
+ # Resize and normalize the depth image
84
+ depth_image_resized = np.array(
85
+ Image.fromarray(depth_image).resize(rgb_image.shape[:2][::-1], Image.LANCZOS)
86
+ )
87
+ depth_image_normalized = (depth_image_resized - depth_image_resized.min()) / (
88
+ depth_image_resized.max() - depth_image_resized.min()
89
+ )
90
+ depth_image_inverted = (1 - depth_image_normalized) * 255
91
+ depth_image_inverted = depth_image_inverted.astype(np.uint8)
92
+
93
+ depth_o3d = o3d.geometry.Image(depth_image_inverted)
94
+ image_o3d = o3d.geometry.Image(rgb_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
96
+ image_o3d, depth_o3d, convert_rgb_to_intensity=False
 
 
97
  )
98
+ w, h = rgb_image.shape[1], rgb_image.shape[0]
 
 
99
 
100
+ # Camera intrinsic setup
101
+ camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
102
+ camera_intrinsic.set_intrinsics(w, h, 1500, 1500, w / 2, h / 2)
103
+
104
+ # Create Point Cloud from RGBD Image
105
+ pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
106
+
107
+ # Check if the point cloud has enough points
108
+ if len(pcd.points) < 100:
109
+ raise RuntimeError("Insufficient points in the point cloud for normals estimation.")
110
+
111
+ # Estimate and orient normals
112
+ if not pcd.has_normals():
113
+ print("Estimating normals with increased search radius for sparse data...")
114
+ pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.25, max_nn=50))
115
 
116
+ if pcd.has_normals():
117
+ pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1500.0]))
118
+ else:
119
+ raise RuntimeError("Failed to estimate normals for the point cloud.")
120
+
121
+ # Poisson Surface Reconstruction
122
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
123
+ pcd, depth=depth, width=0, scale=1.2, linear_fit=True
124
+ )
125
+
126
+ # Mesh simplification and reduced smoothing for better detail
127
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 400 # Decreased voxel size for finer detail
128
+ mesh = mesh_raw.simplify_vertex_clustering(
129
+ voxel_size=voxel_size,
130
+ contraction=o3d.geometry.SimplificationContraction.Average,
131
+ )
132
+ mesh = mesh.filter_smooth_simple(number_of_iterations=3) # Reduced smoothing iterations for sharpness
133
+ bbox = pcd.get_axis_aligned_bounding_box()
134
+ mesh_crop = mesh.crop(bbox)
135
+
136
+ # Save GLTF
137
+ gltf_path = f"./{image_path.stem}.gltf" # Ensure to use .gltf extension and proper file naming
138
+ o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
139
  return gltf_path
140
 
141
+ # Gradio Interface
142
+ title = "Depth Estimation & 3D Reconstruction Demo"
143
+ 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."
144
+
145
+ examples = [["examples/" + img] for img in os.listdir("examples/")]
146
 
147
  iface = gr.Interface(
148
  fn=process_image,
149
  inputs=[
150
  gr.Image(type="filepath", label="Input Image"),
151
+ gr.File(type="filepath", label="Input Depth Map (optional)"),
152
  ],
153
  outputs=[
154
  gr.Image(label="Predicted Depth", type="pil"),
 
157
  ],
158
  title=title,
159
  description=description,
160
+ examples=examples,
161
  allow_flagging="never",
162
  cache_examples=False,
163
  )
 
164
  iface.launch(debug=True, show_api=True, share=True)