aliabd HF staff commited on
Commit
9fbe6b8
1 Parent(s): a2fd4e2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -0
app.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # URL: https://huggingface.co/spaces/radames/dpt-depth-estimation-3d-obj
2
+ # imports
3
+ import gradio as gr
4
+ from transformers import DPTFeatureExtractor, DPTForDepthEstimation
5
+ import torch
6
+ import numpy as np
7
+ from PIL import Image
8
+ import open3d as o3d
9
+ from pathlib import Path
10
+ import os
11
+
12
+ # load the model
13
+ feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
14
+ model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
15
+
16
+ # define the core and helper functions
17
+ def process_image(image_path):
18
+ image_path = Path(image_path)
19
+ image_raw = Image.open(image_path)
20
+ image = image_raw.resize(
21
+ (800, int(800 * image_raw.size[1] / image_raw.size[0])),
22
+ Image.Resampling.LANCZOS)
23
+
24
+ # prepare image for the model
25
+ encoding = feature_extractor(image, return_tensors="pt")
26
+
27
+ # forward pass
28
+ with torch.no_grad():
29
+ outputs = model(**encoding)
30
+ predicted_depth = outputs.predicted_depth
31
+
32
+ # interpolate to original size
33
+ prediction = torch.nn.functional.interpolate(
34
+ predicted_depth.unsqueeze(1),
35
+ size=image.size[::-1],
36
+ mode="bicubic",
37
+ align_corners=False,
38
+ ).squeeze()
39
+ output = prediction.cpu().numpy()
40
+ depth_image = (output * 255 / np.max(output)).astype('uint8')
41
+ try:
42
+ gltf_path = create_3d_obj(np.array(image), depth_image, image_path)
43
+ img = Image.fromarray(depth_image)
44
+ return [img, gltf_path, gltf_path]
45
+ except Exception as e:
46
+ gltf_path = create_3d_obj(
47
+ np.array(image), depth_image, image_path, depth=8)
48
+ img = Image.fromarray(depth_image)
49
+ return [img, gltf_path, gltf_path]
50
+ except:
51
+ print("Error reconstructing 3D model")
52
+ raise Exception("Error reconstructing 3D model")
53
+
54
+
55
+ def create_3d_obj(rgb_image, depth_image, image_path, depth=10):
56
+ depth_o3d = o3d.geometry.Image(depth_image)
57
+ image_o3d = o3d.geometry.Image(rgb_image)
58
+ rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
59
+ image_o3d, depth_o3d, convert_rgb_to_intensity=False)
60
+ w = int(depth_image.shape[1])
61
+ h = int(depth_image.shape[0])
62
+
63
+ camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
64
+ camera_intrinsic.set_intrinsics(w, h, 500, 500, w/2, h/2)
65
+
66
+ pcd = o3d.geometry.PointCloud.create_from_rgbd_image(
67
+ rgbd_image, camera_intrinsic)
68
+
69
+ print('normals')
70
+ pcd.normals = o3d.utility.Vector3dVector(
71
+ np.zeros((1, 3))) # invalidate existing normals
72
+ pcd.estimate_normals(
73
+ search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=30))
74
+ pcd.orient_normals_towards_camera_location(
75
+ camera_location=np.array([0., 0., 1000.]))
76
+ pcd.transform([[1, 0, 0, 0],
77
+ [0, -1, 0, 0],
78
+ [0, 0, -1, 0],
79
+ [0, 0, 0, 1]])
80
+ pcd.transform([[-1, 0, 0, 0],
81
+ [0, 1, 0, 0],
82
+ [0, 0, 1, 0],
83
+ [0, 0, 0, 1]])
84
+
85
+ print('run Poisson surface reconstruction')
86
+ with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
87
+ mesh_raw, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(
88
+ pcd, depth=depth, width=0, scale=1.1, linear_fit=True)
89
+
90
+ voxel_size = max(mesh_raw.get_max_bound() - mesh_raw.get_min_bound()) / 256
91
+ print(f'voxel_size = {voxel_size:e}')
92
+ mesh = mesh_raw.simplify_vertex_clustering(
93
+ voxel_size=voxel_size,
94
+ contraction=o3d.geometry.SimplificationContraction.Average)
95
+
96
+ # vertices_to_remove = densities < np.quantile(densities, 0.001)
97
+ # mesh.remove_vertices_by_mask(vertices_to_remove)
98
+ bbox = pcd.get_axis_aligned_bounding_box()
99
+ mesh_crop = mesh.crop(bbox)
100
+ gltf_path = f'./{image_path.stem}.gltf'
101
+ o3d.io.write_triangle_mesh(
102
+ gltf_path, mesh_crop, write_triangle_uvs=True)
103
+ return gltf_path
104
+
105
+ # define the title, description and examples
106
+ title = "Demo: zero-shot depth estimation with DPT + 3D Point Cloud"
107
+ description = "This demo is a variation from the original <a href='https://huggingface.co/spaces/nielsr/dpt-depth-estimation' target='_blank'>DPT Demo</a>. It uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object."
108
+ examples = [["examples/" + img] for img in os.listdir("examples/")]
109
+
110
+ # define an interface with one Image input and 3 outputs: Image, Model3D and File
111
+ iface = gr.Interface(fn=process_image,
112
+ inputs=[gr.Image(
113
+ type="filepath", label="Input Image")],
114
+ outputs=[gr.Image(label="predicted depth", type="pil"),
115
+ gr.Model3D(label="3d mesh reconstruction", clear_color=[
116
+ 1.0, 1.0, 1.0, 1.0]),
117
+ gr.File(label="3d gLTF")],
118
+ title=title,
119
+ description=description,
120
+ examples=examples,
121
+ allow_flagging="never",
122
+ cache_examples=False)
123
+
124
+ # launch
125
+ iface.launch(debug=True, enable_queue=False)