dylanebert HF staff commited on
Commit
58c54d7
1 Parent(s): 657a1f5
.gitattributes CHANGED
@@ -56,3 +56,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
56
  # Video files - compressed
57
  *.mp4 filter=lfs diff=lfs merge=lfs -text
58
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
56
  # Video files - compressed
57
  *.mp4 filter=lfs diff=lfs merge=lfs -text
58
  *.webm filter=lfs diff=lfs merge=lfs -text
59
+ *.ply filter=lfs diff=lfs merge=lfs -text
LICENSE.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gaussian-Splatting License
2
+ ===========================
3
+
4
+ **Inria** and **the Max Planck Institut for Informatik (MPII)** hold all the ownership rights on the *Software* named **gaussian-splatting**.
5
+ The *Software* is in the process of being registered with the Agence pour la Protection des
6
+ Programmes (APP).
7
+
8
+ The *Software* is still being developed by the *Licensor*.
9
+
10
+ *Licensor*'s goal is to allow the research community to use, test and evaluate
11
+ the *Software*.
12
+
13
+ ## 1. Definitions
14
+
15
+ *Licensee* means any person or entity that uses the *Software* and distributes
16
+ its *Work*.
17
+
18
+ *Licensor* means the owners of the *Software*, i.e Inria and MPII
19
+
20
+ *Software* means the original work of authorship made available under this
21
+ License ie gaussian-splatting.
22
+
23
+ *Work* means the *Software* and any additions to or derivative works of the
24
+ *Software* that are made available under this License.
25
+
26
+
27
+ ## 2. Purpose
28
+ This license is intended to define the rights granted to the *Licensee* by
29
+ Licensors under the *Software*.
30
+
31
+ ## 3. Rights granted
32
+
33
+ For the above reasons Licensors have decided to distribute the *Software*.
34
+ Licensors grant non-exclusive rights to use the *Software* for research purposes
35
+ to research users (both academic and industrial), free of charge, without right
36
+ to sublicense.. The *Software* may be used "non-commercially", i.e., for research
37
+ and/or evaluation purposes only.
38
+
39
+ Subject to the terms and conditions of this License, you are granted a
40
+ non-exclusive, royalty-free, license to reproduce, prepare derivative works of,
41
+ publicly display, publicly perform and distribute its *Work* and any resulting
42
+ derivative works in any form.
43
+
44
+ ## 4. Limitations
45
+
46
+ **4.1 Redistribution.** You may reproduce or distribute the *Work* only if (a) you do
47
+ so under this License, (b) you include a complete copy of this License with
48
+ your distribution, and (c) you retain without modification any copyright,
49
+ patent, trademark, or attribution notices that are present in the *Work*.
50
+
51
+ **4.2 Derivative Works.** You may specify that additional or different terms apply
52
+ to the use, reproduction, and distribution of your derivative works of the *Work*
53
+ ("Your Terms") only if (a) Your Terms provide that the use limitation in
54
+ Section 2 applies to your derivative works, and (b) you identify the specific
55
+ derivative works that are subject to Your Terms. Notwithstanding Your Terms,
56
+ this License (including the redistribution requirements in Section 3.1) will
57
+ continue to apply to the *Work* itself.
58
+
59
+ **4.3** Any other use without of prior consent of Licensors is prohibited. Research
60
+ users explicitly acknowledge having received from Licensors all information
61
+ allowing to appreciate the adequacy between of the *Software* and their needs and
62
+ to undertake all necessary precautions for its execution and use.
63
+
64
+ **4.4** The *Software* is provided both as a compiled library file and as source
65
+ code. In case of using the *Software* for a publication or other results obtained
66
+ through the use of the *Software*, users are strongly encouraged to cite the
67
+ corresponding publications as explained in the documentation of the *Software*.
68
+
69
+ ## 5. Disclaimer
70
+
71
+ THE USER CANNOT USE, EXPLOIT OR DISTRIBUTE THE *SOFTWARE* FOR COMMERCIAL PURPOSES
72
+ WITHOUT PRIOR AND EXPLICIT CONSENT OF LICENSORS. YOU MUST CONTACT INRIA FOR ANY
73
+ UNAUTHORIZED USE: stip-sophia.transfert@inria.fr . ANY SUCH ACTION WILL
74
+ CONSTITUTE A FORGERY. THIS *SOFTWARE* IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES
75
+ OF ANY NATURE AND ANY EXPRESS OR IMPLIED WARRANTIES, WITH REGARDS TO COMMERCIAL
76
+ USE, PROFESSIONNAL USE, LEGAL OR NOT, OR OTHER, OR COMMERCIALISATION OR
77
+ ADAPTATION. UNLESS EXPLICITLY PROVIDED BY LAW, IN NO EVENT, SHALL INRIA OR THE
78
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
80
+ GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
81
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
82
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING FROM, OUT OF OR
83
+ IN CONNECTION WITH THE *SOFTWARE* OR THE USE OR OTHER DEALINGS IN THE *SOFTWARE*.
dtu.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4caf0a4523494dea748c514f718cd3d187956e3ccb511703829e25caa9846da7
3
+ size 3561809006
dtu_results/.DS_Store ADDED
Binary file (6.15 kB). View file
 
dtu_results/mesh/scan105.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b75c868c3b0d41f039855e7d67768f5e7edd184942db3e1a54d9a1de09eeb804
3
+ size 5945211
dtu_results/mesh/scan106.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c4ac08899eeedae1da6c25141d04a1594c8cef37df33446336bcf0311462e32
3
+ size 6466761
dtu_results/mesh/scan110.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4f70861339f38b7d1e59d717e022c6d6fc6f803e22515485ad258bafc6e8b40
3
+ size 4840368
dtu_results/mesh/scan114.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dac7f6ff3f799534d9a1d929d9af06a22726a0535bdaeebc0eb4650508cea2a4
3
+ size 3780667
dtu_results/mesh/scan118.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ed9e578ac04d8b5adca51b62a8074fa2c2840cf7d2c588e785a97f95bba8f1e
3
+ size 5759764
dtu_results/mesh/scan122.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3254a5c678e16154cc6f931a3e8e207823aac55c68404e34ffc650a7afb1802a
3
+ size 5703021
dtu_results/mesh/scan24.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7269dac27860efc610d33cfd23b27f0eff3a3c441c54fceff63f8c5e831a791f
3
+ size 10548798
dtu_results/mesh/scan37.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:deca83c23fcb3f8885138e6d7189690f3f3f4d5965649727e86a411abc5b7246
3
+ size 13370975
dtu_results/mesh/scan40.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d70f35437d16054f4be4a5147c08d356a541bce9716a09941200ecda631819c
3
+ size 9288623
dtu_results/mesh/scan55.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:505c626094e3ac5217a233a7caca44f427d1133b25ddb670c6f1bb957577bc1a
3
+ size 7592924
dtu_results/mesh/scan63.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d07d00caa8eab3aadbdba0abb92f288e1f00669c1df02e6cded797e69501361
3
+ size 7510769
dtu_results/mesh/scan65.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c0815d074fb98f7b9b922775a8d5dcca0cebd8b4e9b4fdea88586fb1cd93386
3
+ size 10142310
dtu_results/mesh/scan69.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecf0eceb175285a5aa6eeaa0d39b25ad08d993a65312e0c18398f5b95a669812
3
+ size 8369756
dtu_results/mesh/scan83.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3da9869c2e36b48b48ce65bd21824abfbf15fab3ff99d59b42741e681abaab46
3
+ size 5809035
dtu_results/mesh/scan97.ply ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7e703cfc1ef8fc9bd454942285af547673d0e9be98868ad680dfbeeec21b8a4
3
+ size 5216954
eval_dtu/eval.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adapted from https://github.com/jzhangbs/DTUeval-python
2
+ import numpy as np
3
+ import open3d as o3d
4
+ import sklearn.neighbors as skln
5
+ from tqdm import tqdm
6
+ from scipy.io import loadmat
7
+ import multiprocessing as mp
8
+ import argparse
9
+
10
+ def sample_single_tri(input_):
11
+ n1, n2, v1, v2, tri_vert = input_
12
+ c = np.mgrid[:n1+1, :n2+1]
13
+ c += 0.5
14
+ c[0] /= max(n1, 1e-7)
15
+ c[1] /= max(n2, 1e-7)
16
+ c = np.transpose(c, (1,2,0))
17
+ k = c[c.sum(axis=-1) < 1] # m2
18
+ q = v1 * k[:,:1] + v2 * k[:,1:] + tri_vert
19
+ return q
20
+
21
+ def write_vis_pcd(file, points, colors):
22
+ pcd = o3d.geometry.PointCloud()
23
+ pcd.points = o3d.utility.Vector3dVector(points)
24
+ pcd.colors = o3d.utility.Vector3dVector(colors)
25
+ o3d.io.write_point_cloud(file, pcd)
26
+
27
+ if __name__ == '__main__':
28
+ mp.freeze_support()
29
+
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument('--data', type=str, default='data_in.ply')
32
+ parser.add_argument('--scan', type=int, default=1)
33
+ parser.add_argument('--mode', type=str, default='mesh', choices=['mesh', 'pcd'])
34
+ parser.add_argument('--dataset_dir', type=str, default='.')
35
+ parser.add_argument('--vis_out_dir', type=str, default='.')
36
+ parser.add_argument('--downsample_density', type=float, default=0.2)
37
+ parser.add_argument('--patch_size', type=float, default=60)
38
+ parser.add_argument('--max_dist', type=float, default=20)
39
+ parser.add_argument('--visualize_threshold', type=float, default=10)
40
+ args = parser.parse_args()
41
+
42
+ thresh = args.downsample_density
43
+ if args.mode == 'mesh':
44
+ pbar = tqdm(total=9)
45
+ pbar.set_description('read data mesh')
46
+ data_mesh = o3d.io.read_triangle_mesh(args.data)
47
+
48
+ vertices = np.asarray(data_mesh.vertices)
49
+ triangles = np.asarray(data_mesh.triangles)
50
+ tri_vert = vertices[triangles]
51
+
52
+ pbar.update(1)
53
+ pbar.set_description('sample pcd from mesh')
54
+ v1 = tri_vert[:,1] - tri_vert[:,0]
55
+ v2 = tri_vert[:,2] - tri_vert[:,0]
56
+ l1 = np.linalg.norm(v1, axis=-1, keepdims=True)
57
+ l2 = np.linalg.norm(v2, axis=-1, keepdims=True)
58
+ area2 = np.linalg.norm(np.cross(v1, v2), axis=-1, keepdims=True)
59
+ non_zero_area = (area2 > 0)[:,0]
60
+ l1, l2, area2, v1, v2, tri_vert = [
61
+ arr[non_zero_area] for arr in [l1, l2, area2, v1, v2, tri_vert]
62
+ ]
63
+ thr = thresh * np.sqrt(l1 * l2 / area2)
64
+ n1 = np.floor(l1 / thr)
65
+ n2 = np.floor(l2 / thr)
66
+
67
+ with mp.Pool() as mp_pool:
68
+ new_pts = mp_pool.map(sample_single_tri, ((n1[i,0], n2[i,0], v1[i:i+1], v2[i:i+1], tri_vert[i:i+1,0]) for i in range(len(n1))), chunksize=1024)
69
+
70
+ new_pts = np.concatenate(new_pts, axis=0)
71
+ data_pcd = np.concatenate([vertices, new_pts], axis=0)
72
+
73
+ elif args.mode == 'pcd':
74
+ pbar = tqdm(total=8)
75
+ pbar.set_description('read data pcd')
76
+ data_pcd_o3d = o3d.io.read_point_cloud(args.data)
77
+ data_pcd = np.asarray(data_pcd_o3d.points)
78
+
79
+ pbar.update(1)
80
+ pbar.set_description('random shuffle pcd index')
81
+ shuffle_rng = np.random.default_rng()
82
+ shuffle_rng.shuffle(data_pcd, axis=0)
83
+
84
+ pbar.update(1)
85
+ pbar.set_description('downsample pcd')
86
+ nn_engine = skln.NearestNeighbors(n_neighbors=1, radius=thresh, algorithm='kd_tree', n_jobs=-1)
87
+ nn_engine.fit(data_pcd)
88
+ rnn_idxs = nn_engine.radius_neighbors(data_pcd, radius=thresh, return_distance=False)
89
+ mask = np.ones(data_pcd.shape[0], dtype=np.bool_)
90
+ for curr, idxs in enumerate(rnn_idxs):
91
+ if mask[curr]:
92
+ mask[idxs] = 0
93
+ mask[curr] = 1
94
+ data_down = data_pcd[mask]
95
+
96
+ pbar.update(1)
97
+ pbar.set_description('masking data pcd')
98
+ obs_mask_file = loadmat(f'{args.dataset_dir}/ObsMask/ObsMask{args.scan}_10.mat')
99
+ ObsMask, BB, Res = [obs_mask_file[attr] for attr in ['ObsMask', 'BB', 'Res']]
100
+ BB = BB.astype(np.float32)
101
+
102
+ patch = args.patch_size
103
+ inbound = ((data_down >= BB[:1]-patch) & (data_down < BB[1:]+patch*2)).sum(axis=-1) ==3
104
+ data_in = data_down[inbound]
105
+
106
+ data_grid = np.around((data_in - BB[:1]) / Res).astype(np.int32)
107
+ grid_inbound = ((data_grid >= 0) & (data_grid < np.expand_dims(ObsMask.shape, 0))).sum(axis=-1) ==3
108
+ data_grid_in = data_grid[grid_inbound]
109
+ in_obs = ObsMask[data_grid_in[:,0], data_grid_in[:,1], data_grid_in[:,2]].astype(np.bool_)
110
+ data_in_obs = data_in[grid_inbound][in_obs]
111
+
112
+ pbar.update(1)
113
+ pbar.set_description('read STL pcd')
114
+ stl_pcd = o3d.io.read_point_cloud(f'{args.dataset_dir}/Points/stl/stl{args.scan:03}_total.ply')
115
+ stl = np.asarray(stl_pcd.points)
116
+
117
+ pbar.update(1)
118
+ pbar.set_description('compute data2stl')
119
+ nn_engine.fit(stl)
120
+ dist_d2s, idx_d2s = nn_engine.kneighbors(data_in_obs, n_neighbors=1, return_distance=True)
121
+ max_dist = args.max_dist
122
+ mean_d2s = dist_d2s[dist_d2s < max_dist].mean()
123
+
124
+ pbar.update(1)
125
+ pbar.set_description('compute stl2data')
126
+ ground_plane = loadmat(f'{args.dataset_dir}/ObsMask/Plane{args.scan}.mat')['P']
127
+
128
+ stl_hom = np.concatenate([stl, np.ones_like(stl[:,:1])], -1)
129
+ above = (ground_plane.reshape((1,4)) * stl_hom).sum(-1) > 0
130
+ stl_above = stl[above]
131
+
132
+ nn_engine.fit(data_in)
133
+ dist_s2d, idx_s2d = nn_engine.kneighbors(stl_above, n_neighbors=1, return_distance=True)
134
+ mean_s2d = dist_s2d[dist_s2d < max_dist].mean()
135
+
136
+ pbar.update(1)
137
+ pbar.set_description('visualize error')
138
+ vis_dist = args.visualize_threshold
139
+ R = np.array([[1,0,0]], dtype=np.float64)
140
+ G = np.array([[0,1,0]], dtype=np.float64)
141
+ B = np.array([[0,0,1]], dtype=np.float64)
142
+ W = np.array([[1,1,1]], dtype=np.float64)
143
+ data_color = np.tile(B, (data_down.shape[0], 1))
144
+ data_alpha = dist_d2s.clip(max=vis_dist) / vis_dist
145
+ data_color[ np.where(inbound)[0][grid_inbound][in_obs] ] = R * data_alpha + W * (1-data_alpha)
146
+ data_color[ np.where(inbound)[0][grid_inbound][in_obs][dist_d2s[:,0] >= max_dist] ] = G
147
+ write_vis_pcd(f'{args.vis_out_dir}/vis_{args.scan:03}_d2s.ply', data_down, data_color)
148
+ stl_color = np.tile(B, (stl.shape[0], 1))
149
+ stl_alpha = dist_s2d.clip(max=vis_dist) / vis_dist
150
+ stl_color[ np.where(above)[0] ] = R * stl_alpha + W * (1-stl_alpha)
151
+ stl_color[ np.where(above)[0][dist_s2d[:,0] >= max_dist] ] = G
152
+ write_vis_pcd(f'{args.vis_out_dir}/vis_{args.scan:03}_s2d.ply', stl, stl_color)
153
+
154
+ pbar.update(1)
155
+ pbar.set_description('done')
156
+ pbar.close()
157
+ over_all = (mean_d2s + mean_s2d) / 2
158
+ print(mean_d2s, mean_s2d, over_all)
159
+
160
+ import json
161
+ with open(f'{args.vis_out_dir}/results.json', 'w') as fp:
162
+ json.dump({
163
+ 'mean_d2s': mean_d2s,
164
+ 'mean_s2d': mean_s2d,
165
+ 'overall': over_all,
166
+ }, fp, indent=True)
eval_dtu/evaluate.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import root
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import cv2
6
+ import numpy as np
7
+ import os
8
+ import glob
9
+ from skimage.morphology import binary_dilation, disk
10
+ import argparse
11
+ import trimesh
12
+ from pathlib import Path
13
+ import subprocess
14
+
15
+ from evaluate_single_scene import cull_scan
16
+
17
+
18
+ # Ground truth DTU point cloud path
19
+ Offical_DTU_Dataset = "./Offical_DTU_Dataset"
20
+ scans = [24, 37, 40, 55, 63, 65, 69, 83, 97, 105, 106, 110, 114, 118, 122]
21
+
22
+ out_dir_prefix = "evaluation/"
23
+ Path(out_dir_prefix).mkdir(parents=True, exist_ok=True)
24
+
25
+ # output file to save quantitative results
26
+ evaluation_txt_file = "evaluation/DTU.csv"
27
+ evaluation_txt_file = open(evaluation_txt_file, 'w')
28
+
29
+ root_dir = '../exps/'
30
+ exp_names =["dtu_3views"]
31
+
32
+ for exp in exp_names:
33
+ for scan in scans:
34
+ out_dir = os.path.join(out_dir_prefix, str(scan))
35
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
36
+ vis_out_dir = os.path.join(out_dir_prefix, exp)
37
+ Path(vis_out_dir).mkdir(parents=True, exist_ok=True)
38
+
39
+ cur_root = os.path.join(root_dir, f"{exp}_{scan}")
40
+
41
+ files = list(filter(os.path.isfile, glob.glob(os.path.join(cur_root, "*/plots/*.ply"))))
42
+ files.sort(key=lambda x:os.path.getmtime(x))
43
+
44
+ for ply_file in files[-1:]:
45
+ iter_num = Path(ply_file).stem
46
+ cur_vis_out_dir = os.path.join(out_dir_prefix, exp)
47
+ Path(cur_vis_out_dir).mkdir(parents=True, exist_ok=True)
48
+
49
+ print(ply_file)
50
+
51
+ # delete mesh by mask
52
+ result_mesh_file = os.path.join(out_dir, f"{exp}_{iter_num}.ply")
53
+ cull_scan(scan, ply_file, result_mesh_file)
54
+
55
+ cmd = f"python eval.py --data {result_mesh_file} --scan {scan} --mode mesh --dataset_dir {Offical_DTU_Dataset} --vis_out_dir {cur_vis_out_dir}"
56
+ print(cmd)
57
+ #acc, comp, overall
58
+ output = subprocess.check_output(cmd, shell=True).decode("utf-8")
59
+ output = output.replace(" ", ",")
60
+
61
+ evaluation_txt_file.write(f"{exp},{scan},{iter_num},{output}")
62
+ evaluation_txt_file.flush()
eval_dtu/evaluate_single_scene.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import cv2
5
+ import numpy as np
6
+ import os
7
+ import glob
8
+ from skimage.morphology import binary_dilation, disk
9
+ import argparse
10
+
11
+ import trimesh
12
+ from pathlib import Path
13
+ import subprocess
14
+
15
+ import sys
16
+ sys.path.append("../code")
17
+ import render_utils as rend_util
18
+
19
+
20
+ def cull_scan(scan, mesh_path, result_mesh_file):
21
+
22
+ # load poses
23
+ instance_dir = os.path.join('/p300/wangchy/huangbb/anti-alising-gaussian-splatting/data/DTU_dense', 'scan{0}'.format(scan))
24
+ image_dir = '{0}/images'.format(instance_dir)
25
+ image_paths = sorted(glob.glob(os.path.join(image_dir, "*.png")))
26
+ n_images = len(image_paths)
27
+ cam_file = '{0}/cameras.npz'.format(instance_dir)
28
+ camera_dict = np.load(cam_file)
29
+ scale_mats = [camera_dict['scale_mat_%d' % idx].astype(np.float32) for idx in range(n_images)]
30
+ world_mats = [camera_dict['world_mat_%d' % idx].astype(np.float32) for idx in range(n_images)]
31
+
32
+ intrinsics_all = []
33
+ pose_all = []
34
+ for scale_mat, world_mat in zip(scale_mats, world_mats):
35
+ P = world_mat @ scale_mat
36
+ P = P[:3, :4]
37
+ intrinsics, pose = rend_util.load_K_Rt_from_P(None, P)
38
+ intrinsics_all.append(torch.from_numpy(intrinsics).float())
39
+ pose_all.append(torch.from_numpy(pose).float())
40
+
41
+ # load mask
42
+ mask_dir = '{0}/mask'.format(instance_dir)
43
+ mask_paths = sorted(glob.glob(os.path.join(mask_dir, "*.png")))
44
+ masks = []
45
+ for p in mask_paths:
46
+ mask = cv2.imread(p)
47
+ masks.append(mask)
48
+
49
+ # hard-coded image shape
50
+ W, H = 1600, 1200
51
+
52
+ # load mesh
53
+ mesh = trimesh.load(mesh_path)
54
+
55
+ # load transformation matrix
56
+
57
+ vertices = mesh.vertices
58
+
59
+ # project and filter
60
+ vertices = torch.from_numpy(vertices).cuda()
61
+ vertices = torch.cat((vertices, torch.ones_like(vertices[:, :1])), dim=-1)
62
+ vertices = vertices.permute(1, 0)
63
+ vertices = vertices.float()
64
+
65
+ sampled_masks = []
66
+ for i in range(n_images):
67
+ pose = pose_all[i]
68
+ w2c = torch.inverse(pose).cuda()
69
+ intrinsic = intrinsics_all[i].cuda()
70
+
71
+ with torch.no_grad():
72
+ # transform and project
73
+ cam_points = intrinsic @ w2c @ vertices
74
+ pix_coords = cam_points[:2, :] / (cam_points[2, :].unsqueeze(0) + 1e-6)
75
+ pix_coords = pix_coords.permute(1, 0)
76
+ pix_coords[..., 0] /= W - 1
77
+ pix_coords[..., 1] /= H - 1
78
+ pix_coords = (pix_coords - 0.5) * 2
79
+ valid = ((pix_coords > -1. ) & (pix_coords < 1.)).all(dim=-1).float()
80
+
81
+ # dialate mask similar to unisurf
82
+ maski = masks[i][:, :, 0].astype(np.float32) / 256.
83
+ maski = torch.from_numpy(binary_dilation(maski, disk(24))).float()[None, None].cuda()
84
+
85
+ # # if scan == '83':
86
+ # import matplotlib.pyplot as plt
87
+ # plt.imshow(maski.cpu().numpy()[0,0])
88
+ # points = (cam_points[:2, :] / (cam_points[2, :].unsqueeze(0) + 1e-6)).permute(1,0)[valid==1].cpu().numpy()
89
+ # scatters = points[np.random.permutation(len(points))[:10000]]
90
+ # plt.scatter(scatters[:,0], scatters[:,1], color='r')
91
+ # plt.savefig(f'test{i}')
92
+ # plt.clf()
93
+ # plt.close()
94
+
95
+ sampled_mask = F.grid_sample(maski, pix_coords[None, None], mode='nearest', padding_mode='zeros', align_corners=True)[0, -1, 0]
96
+ # print(f'culling {i}')
97
+ sampled_mask = sampled_mask + (1. - valid)
98
+ sampled_masks.append(sampled_mask)
99
+
100
+ sampled_masks = torch.stack(sampled_masks, -1)
101
+ # filter
102
+
103
+ mask = (sampled_masks > 0.).all(dim=-1).cpu().numpy()
104
+ face_mask = mask[mesh.faces].all(axis=1)
105
+
106
+ mesh.update_vertices(mask)
107
+ mesh.update_faces(face_mask)
108
+
109
+ # with o3d.utility.VerbosityContextManager(o3d.utility.VerbosityLevel.Debug) as cm:
110
+ # triangle_clusters, cluster_n_triangles, cluster_area = (mesh.cluster_connected_triangles())
111
+ # triangle_clusters = np.asarray(triangle_clusters)
112
+ # cluster_n_triangles = np.asarray(cluster_n_triangles)
113
+ # cluster_area = np.asarray(cluster_area)
114
+ # largest_cluster_idx = cluster_n_triangles.argmax()
115
+ # triangles_to_remove = (triangle_clusters != largest_cluster_idx)
116
+
117
+ # transform vertices to world
118
+ scale_mat = scale_mats[0]
119
+ mesh.vertices = mesh.vertices * scale_mat[0, 0] + scale_mat[:3, 3][None]
120
+ mesh.export(result_mesh_file)
121
+ del mesh
122
+
123
+
124
+ if __name__ == "__main__":
125
+
126
+ parser = argparse.ArgumentParser(
127
+ description='Arguments to evaluate the mesh.'
128
+ )
129
+
130
+ parser.add_argument('--input_mesh', type=str, help='path to the mesh to be evaluated')
131
+ parser.add_argument('--scan_id', type=str, help='scan id of the input mesh')
132
+ parser.add_argument('--output_dir', type=str, default='evaluation_results_single', help='path to the output folder')
133
+ parser.add_argument('--DTU', type=str, default='Offical_DTU_Dataset', help='path to the GT DTU point clouds')
134
+ args = parser.parse_args()
135
+
136
+
137
+ Offical_DTU_Dataset = args.DTU
138
+ out_dir = args.output_dir
139
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
140
+
141
+ scan = args.scan_id
142
+ ply_file = args.input_mesh
143
+
144
+ result_mesh_file = os.path.join(out_dir, "culled_mesh.ply")
145
+ cull_scan(scan, ply_file, result_mesh_file)
146
+
147
+ cmd = f"python eval.py --data {result_mesh_file} --scan {scan} --mode mesh --dataset_dir {Offical_DTU_Dataset} --vis_out_dir {out_dir}"
148
+ os.system(cmd)
eval_dtu/render_utils.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import imageio
3
+ import skimage
4
+ import cv2
5
+ import torch
6
+ from torch.nn import functional as F
7
+
8
+
9
+ def get_psnr(img1, img2, normalize_rgb=False):
10
+ if normalize_rgb: # [-1,1] --> [0,1]
11
+ img1 = (img1 + 1.) / 2.
12
+ img2 = (img2 + 1. ) / 2.
13
+
14
+ mse = torch.mean((img1 - img2) ** 2)
15
+ psnr = -10. * torch.log(mse) / torch.log(torch.Tensor([10.]).cuda())
16
+
17
+ return psnr
18
+
19
+
20
+ def load_rgb(path, normalize_rgb = False):
21
+ img = imageio.imread(path)
22
+ img = skimage.img_as_float32(img)
23
+
24
+ if normalize_rgb: # [-1,1] --> [0,1]
25
+ img -= 0.5
26
+ img *= 2.
27
+ img = img.transpose(2, 0, 1)
28
+ return img
29
+
30
+
31
+ def load_K_Rt_from_P(filename, P=None):
32
+ if P is None:
33
+ lines = open(filename).read().splitlines()
34
+ if len(lines) == 4:
35
+ lines = lines[1:]
36
+ lines = [[x[0], x[1], x[2], x[3]] for x in (x.split(" ") for x in lines)]
37
+ P = np.asarray(lines).astype(np.float32).squeeze()
38
+
39
+ out = cv2.decomposeProjectionMatrix(P)
40
+ K = out[0]
41
+ R = out[1]
42
+ t = out[2]
43
+
44
+ K = K/K[2,2]
45
+ intrinsics = np.eye(4)
46
+ intrinsics[:3, :3] = K
47
+
48
+ pose = np.eye(4, dtype=np.float32)
49
+ pose[:3, :3] = R.transpose()
50
+ pose[:3,3] = (t[:3] / t[3])[:,0]
51
+
52
+ return intrinsics, pose
53
+
54
+
55
+ def get_camera_params(uv, pose, intrinsics):
56
+ if pose.shape[1] == 7: #In case of quaternion vector representation
57
+ cam_loc = pose[:, 4:]
58
+ R = quat_to_rot(pose[:,:4])
59
+ p = torch.eye(4).repeat(pose.shape[0],1,1).cuda().float()
60
+ p[:, :3, :3] = R
61
+ p[:, :3, 3] = cam_loc
62
+ else: # In case of pose matrix representation
63
+ cam_loc = pose[:, :3, 3]
64
+ p = pose
65
+
66
+ batch_size, num_samples, _ = uv.shape
67
+
68
+ depth = torch.ones((batch_size, num_samples)).cuda()
69
+ x_cam = uv[:, :, 0].view(batch_size, -1)
70
+ y_cam = uv[:, :, 1].view(batch_size, -1)
71
+ z_cam = depth.view(batch_size, -1)
72
+
73
+ pixel_points_cam = lift(x_cam, y_cam, z_cam, intrinsics=intrinsics)
74
+
75
+ # permute for batch matrix product
76
+ pixel_points_cam = pixel_points_cam.permute(0, 2, 1)
77
+
78
+ world_coords = torch.bmm(p, pixel_points_cam).permute(0, 2, 1)[:, :, :3]
79
+ ray_dirs = world_coords - cam_loc[:, None, :]
80
+ ray_dirs = F.normalize(ray_dirs, dim=2)
81
+
82
+ return ray_dirs, cam_loc
83
+
84
+
85
+ def get_camera_for_plot(pose):
86
+ if pose.shape[1] == 7: #In case of quaternion vector representation
87
+ cam_loc = pose[:, 4:].detach()
88
+ R = quat_to_rot(pose[:,:4].detach())
89
+ else: # In case of pose matrix representation
90
+ cam_loc = pose[:, :3, 3]
91
+ R = pose[:, :3, :3]
92
+ cam_dir = R[:, :3, 2]
93
+ return cam_loc, cam_dir
94
+
95
+
96
+ def lift(x, y, z, intrinsics):
97
+ # parse intrinsics
98
+ intrinsics = intrinsics.cuda()
99
+ fx = intrinsics[:, 0, 0]
100
+ fy = intrinsics[:, 1, 1]
101
+ cx = intrinsics[:, 0, 2]
102
+ cy = intrinsics[:, 1, 2]
103
+ sk = intrinsics[:, 0, 1]
104
+
105
+ x_lift = (x - cx.unsqueeze(-1) + cy.unsqueeze(-1)*sk.unsqueeze(-1)/fy.unsqueeze(-1) - sk.unsqueeze(-1)*y/fy.unsqueeze(-1)) / fx.unsqueeze(-1) * z
106
+ y_lift = (y - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z
107
+
108
+ # homogeneous
109
+ return torch.stack((x_lift, y_lift, z, torch.ones_like(z).cuda()), dim=-1)
110
+
111
+
112
+ def quat_to_rot(q):
113
+ batch_size, _ = q.shape
114
+ q = F.normalize(q, dim=1)
115
+ R = torch.ones((batch_size, 3,3)).cuda()
116
+ qr=q[:,0]
117
+ qi = q[:, 1]
118
+ qj = q[:, 2]
119
+ qk = q[:, 3]
120
+ R[:, 0, 0]=1-2 * (qj**2 + qk**2)
121
+ R[:, 0, 1] = 2 * (qj *qi -qk*qr)
122
+ R[:, 0, 2] = 2 * (qi * qk + qr * qj)
123
+ R[:, 1, 0] = 2 * (qj * qi + qk * qr)
124
+ R[:, 1, 1] = 1-2 * (qi**2 + qk**2)
125
+ R[:, 1, 2] = 2*(qj*qk - qi*qr)
126
+ R[:, 2, 0] = 2 * (qk * qi-qj * qr)
127
+ R[:, 2, 1] = 2 * (qj*qk + qi*qr)
128
+ R[:, 2, 2] = 1-2 * (qi**2 + qj**2)
129
+ return R
130
+
131
+
132
+ def rot_to_quat(R):
133
+ batch_size, _,_ = R.shape
134
+ q = torch.ones((batch_size, 4)).cuda()
135
+
136
+ R00 = R[:, 0,0]
137
+ R01 = R[:, 0, 1]
138
+ R02 = R[:, 0, 2]
139
+ R10 = R[:, 1, 0]
140
+ R11 = R[:, 1, 1]
141
+ R12 = R[:, 1, 2]
142
+ R20 = R[:, 2, 0]
143
+ R21 = R[:, 2, 1]
144
+ R22 = R[:, 2, 2]
145
+
146
+ q[:,0]=torch.sqrt(1.0+R00+R11+R22)/2
147
+ q[:, 1]=(R21-R12)/(4*q[:,0])
148
+ q[:, 2] = (R02 - R20) / (4 * q[:, 0])
149
+ q[:, 3] = (R10 - R01) / (4 * q[:, 0])
150
+ return q
151
+
152
+
153
+ def get_sphere_intersections(cam_loc, ray_directions, r = 1.0):
154
+ # Input: n_rays x 3 ; n_rays x 3
155
+ # Output: n_rays x 1, n_rays x 1 (close and far)
156
+
157
+ ray_cam_dot = torch.bmm(ray_directions.view(-1, 1, 3),
158
+ cam_loc.view(-1, 3, 1)).squeeze(-1)
159
+ under_sqrt = ray_cam_dot ** 2 - (cam_loc.norm(2, 1, keepdim=True) ** 2 - r ** 2)
160
+
161
+ # sanity check
162
+ if (under_sqrt <= 0).sum() > 0:
163
+ print('BOUNDING SPHERE PROBLEM!')
164
+ exit()
165
+
166
+ sphere_intersections = torch.sqrt(under_sqrt) * torch.Tensor([-1, 1]).cuda().float() - ray_cam_dot
167
+ sphere_intersections = sphere_intersections.clamp_min(0.0)
168
+
169
+ return sphere_intersections