codic commited on
Commit
f463c64
·
verified ·
1 Parent(s): 4fd66ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -87
app.py CHANGED
@@ -6,132 +6,121 @@ from PIL import Image
6
  import open3d as o3d
7
  from pathlib import Path
8
  import os
9
- import cv2 # For inpainting
10
- from rembg import remove # For background removal
11
 
12
- # Initialize depth estimation model
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
- try:
18
- image_path = Path(image_path)
19
- image_raw = Image.open(image_path)
20
- image = image_raw.resize(
21
- (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
22
- Image.Resampling.LANCZOS,
23
- )
24
 
25
- # Step 1: Separate the main subject
26
- print("Removing background...")
27
- image_np = np.array(image)
28
- subject = remove(image_np) # Removes background
29
-
30
- # Ensure subject is in RGB format
31
- if len(subject.shape) == 2 or subject.shape[2] != 3:
32
- if subject.shape[2] == 4: # If the image has 4 channels (RGBA)
33
- subject = cv2.cvtColor(subject, cv2.COLOR_RGBA2RGB)
34
- else:
35
- subject = cv2.cvtColor(subject, cv2.COLOR_GRAY2RGB) # Ensure it's RGB if grayscale
36
-
37
- # Step 2: Inpaint the background
38
- print("Inpainting background...")
39
- mask = cv2.inRange(subject, (0, 0, 0), (0, 0, 0)) # Binary mask
40
- background_inpainted = cv2.inpaint(image_np, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
41
-
42
- # Convert back to PIL format
43
- subject_image = Image.fromarray(subject)
44
- inpainted_bg_image = Image.fromarray(background_inpainted)
45
-
46
- # Step 3: Generate or use existing depth map
47
- if depth_map_path:
48
- print("Loading depth map...")
49
- # Check if the depth map path is a .npy file or an image
50
- if depth_map_path.endswith('.npy'):
51
- # Load the depth map from a .npy file
52
- depth_image = np.load(depth_map_path)
53
- # Normalize and invert depth map
54
- depth_image = 255 - (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image)) * 255
55
- depth_image = depth_image.astype('uint8')
56
- else:
57
- # Resize user-provided depth map to match RGB size
58
- depth_image_raw = Image.open(depth_map_path)
59
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
60
- depth_image = np.array(depth_image)
61
- # Normalize depth image
62
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
63
- depth_image = (depth_image * 255).astype('uint8')
64
  else:
65
- print("Generating depth map using the model...")
66
- # Generate depth map using the model
67
- encoding = feature_extractor(image, return_tensors="pt")
68
- with torch.no_grad():
69
- outputs = model(**encoding)
70
- predicted_depth = outputs.predicted_depth
71
- prediction = torch.nn.functional.interpolate(
72
- predicted_depth.unsqueeze(1),
73
- size=image.size[::-1],
74
- mode="bicubic",
75
- align_corners=False,
76
- ).squeeze()
77
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
78
-
79
- # Step 4: Apply depth to main subject only
80
- print("Creating 3D object...")
81
- gltf_path = create_3d_obj(np.array(subject_image), depth_image, image_path)
 
 
 
 
 
 
 
 
 
 
82
  img = Image.fromarray(depth_image)
83
- print("3D model reconstruction successful.")
84
  return [img, gltf_path, gltf_path]
85
  except Exception as e:
86
- print("Error reconstructing 3D model:", e)
87
- raise Exception("Error reconstructing 3D model") from e
 
 
 
 
 
 
 
 
 
88
 
89
- def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
90
- # Your existing create_3d_obj implementation...
91
  depth_o3d = o3d.geometry.Image(depth_image)
92
  image_o3d = o3d.geometry.Image(rgb_image)
93
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
94
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
95
  )
96
- w = int(depth_image.shape[1])
97
- h = int(depth_image.shape[0])
98
 
99
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
100
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
101
 
102
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
103
- pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3))) # Invalidate existing normals
104
- pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30))
 
 
 
 
105
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
106
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
107
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
108
 
109
- # Poisson surface reconstruction
110
- mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
111
- pcd, depth=depth, width=0, scale=1.1, linear_fit=True
112
- )
 
113
 
114
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
115
- mesh = mesh_raw.simplify_vertex_clustering(voxel_size=voxel_size, contraction=o3d.geometry.SimplificationContraction.Average)
 
 
 
 
 
116
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
117
 
118
- # Crop mesh to a flat backside
119
  bbox = pcd.get_axis_aligned_bounding_box()
120
  mesh_crop = mesh.crop(bbox)
121
  gltf_path = f"./{image_path.stem}.gltf"
122
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
123
  return gltf_path
124
 
125
- # Gradio interface setup
126
- title = "Demo: Depth Estimation & 3D Reconstruction with DPT + Point Cloud"
127
- 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."
128
- examples = [["examples/" + img] for img in os.listdir("examples/")]
 
129
 
130
  iface = gr.Interface(
131
  fn=process_image,
132
  inputs=[
133
  gr.Image(type="filepath", label="Input Image"),
134
- gr.File(label="Input Depth Map (optional)"), # Changed from gr.Image to gr.File
135
  ],
136
  outputs=[
137
  gr.Image(label="Predicted Depth", type="pil"),
@@ -140,9 +129,9 @@ iface = gr.Interface(
140
  ],
141
  title=title,
142
  description=description,
143
- examples=examples,
144
  allow_flagging="never",
145
  cache_examples=False,
146
  )
147
 
 
148
  iface.launch(debug=True, show_api=True, share=True)
 
6
  import open3d as o3d
7
  from pathlib import Path
8
  import os
9
+ import cv2
 
10
 
 
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
+ # Determine if depth map is npy or image format
24
+ if depth_map_path.endswith(".npy"):
25
+ depth_image = np.load(depth_map_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  else:
27
+ depth_image_raw = Image.open(depth_map_path)
28
+ depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
29
+ depth_image = np.array(depth_image)
30
+
31
+ # Normalize depth if needed
32
+ depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
33
+ depth_image = (depth_image * 255).astype('uint8')
34
+ else:
35
+ # Generate depth using DPT if not 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
+ prediction = torch.nn.functional.interpolate(
42
+ predicted_depth.unsqueeze(1),
43
+ size=image.size[::-1],
44
+ mode="bicubic",
45
+ align_corners=False,
46
+ ).squeeze()
47
+ depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
48
+
49
+ # Create inpainted background with OpenCV
50
+ inpainted_bg = inpaint_background(image, np.array(image_raw))
51
+
52
+ try:
53
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path, inpainted_bg)
54
  img = Image.fromarray(depth_image)
 
55
  return [img, gltf_path, gltf_path]
56
  except Exception as e:
57
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path, inpainted_bg, depth=8)
58
+ img = Image.fromarray(depth_image)
59
+ return [img, gltf_path, gltf_path]
60
+ except:
61
+ print("Error reconstructing 3D model")
62
+ raise Exception("Error reconstructing 3D model")
63
+
64
+ def inpaint_background(image, original_image):
65
+ mask = np.array(image.convert("L").point(lambda x: 255 if x == 0 else 0, mode="1"))
66
+ inpainted_image = cv2.inpaint(original_image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
67
+ return inpainted_image
68
 
69
+ def create_3d_obj(rgb_image, depth_image, image_path, inpainted_bg, depth=12):
 
70
  depth_o3d = o3d.geometry.Image(depth_image)
71
  image_o3d = o3d.geometry.Image(rgb_image)
72
  rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
73
  image_o3d, depth_o3d, convert_rgb_to_intensity=False
74
  )
75
+ w, h = depth_image.shape[1], depth_image.shape[0]
 
76
 
77
  camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
78
  camera_intrinsic.set_intrinsics(w, h, 1000, 1000, w / 2, h / 2)
79
 
80
  pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, camera_intrinsic)
81
+
82
+ # Estimate and orient normals
83
+ pcd.normals = o3d.utility.Vector3dVector(np.zeros((1, 3)))
84
+ pcd.estimate_normals(
85
+ search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=30)
86
+ )
87
  pcd.orient_normals_towards_camera_location(camera_location=np.array([0.0, 0.0, 1000.0]))
88
  pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
89
  pcd.transform([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
90
 
91
+ # Poisson reconstruction
92
+ with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug):
93
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
94
+ pcd, depth=depth, width=0, scale=1.1, linear_fit=True
95
+ )
96
 
97
  voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 512
98
+ mesh = mesh_raw.simplify_vertex_clustering(
99
+ voxel_size=voxel_size,
100
+ contraction=o3d.geometry.SimplificationContraction.Average,
101
+ )
102
+
103
+ # Smooth mesh
104
  mesh = mesh.filter_smooth_simple(number_of_iterations=3)
105
 
106
+ # Apply bounding box crop and save mesh
107
  bbox = pcd.get_axis_aligned_bounding_box()
108
  mesh_crop = mesh.crop(bbox)
109
  gltf_path = f"./{image_path.stem}.gltf"
110
  o3d.io.write_triangle_mesh(gltf_path, mesh_crop, write_triangle_uvs=True)
111
  return gltf_path
112
 
113
+ title = "Enhanced Depth Estimation & 3D Reconstruction with Panorama Background"
114
+ description = (
115
+ "Upload an RGB image and optionally a depth map (image or npy) to create a 3D model. "
116
+ "Background remains unchanged and un-cropped, with a panoramic effect for a more immersive experience."
117
+ )
118
 
119
  iface = gr.Interface(
120
  fn=process_image,
121
  inputs=[
122
  gr.Image(type="filepath", label="Input Image"),
123
+ gr.File(type="filepath", label="Input Depth Map (optional)"), # Changed to File
124
  ],
125
  outputs=[
126
  gr.Image(label="Predicted Depth", type="pil"),
 
129
  ],
130
  title=title,
131
  description=description,
 
132
  allow_flagging="never",
133
  cache_examples=False,
134
  )
135
 
136
+
137
  iface.launch(debug=True, show_api=True, share=True)