-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoint_mapping.py
More file actions
214 lines (166 loc) · 7.9 KB
/
point_mapping.py
File metadata and controls
214 lines (166 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python
from sklearn.neighbors import NearestNeighbors
import numpy as np
from trimesh import TriMesh
from geometry import (dist, estimate_max_diagonal, transform_trimesh,
center_of_mass, nearest_neighbor_distance,
get_mesh_of_high_curvature)
def clamp(val, low, high):
"""Clamps val to the range [low, high]."""
return max(min(val, high), low)
class RegistrationAlgorithm(object):
def __init__(self, source_mesh, destination_mesh, verbose = False):
assert(isinstance(source_mesh, TriMesh) and
isinstance(destination_mesh, TriMesh))
self.source_mesh = source_mesh
self.destination_mesh = destination_mesh
self.global_confidence = 1.0
self.destination_nearest_neighbors = (
NearestNeighbors(n_neighbors=1,
algorithm="kd_tree").fit(destination_mesh.vs))
self.destination_longest_diagonal = None
self.verbose = verbose
def run(self):
pass
def transform(self, source_point):
"""In classes which inherit from RegistrationAlgorithm, this
function will perform the mapping on source_point, and return
the tuple (predicted_point, confidence)."""
pass
def register(self, mapping):
"""Finds a registration for mapping.source on the destination_mesh,
and also stores in mapping.confidence the confidence in that mapping."""
assert(isinstance(mapping, PointMapping))
mapping.destination, mapping.confidence = self.transform(mapping.source)
mapping.destination, distance = self.project(mapping.destination)
mapping.confidence *= self.get_confidence_of_projection(distance)
mapping.confidence *= self.global_confidence
def project(self, source_point):
"""Finds the closest point on the destination mesh for the given
source_point, and returns the projected point as well as the distance
to that point."""
projected_point_index = self.destination_nearest_neighbors.kneighbors(
source_point
)[1][0][0]
projected_point = self.destination_mesh.vs[projected_point_index]
return projected_point, dist(projected_point, source_point)
def get_confidence_of_projection(self, distance, tolerance = 0.5):
"""Returns a confidence metric 0.0 < c < 1.0 corresponding to a
projection in which a point P was moved to a point Q that is dist
away."""
if self.destination_longest_diagonal is None:
self.destination_longest_diagonal = (
estimate_max_diagonal(destination_mesh.vs))
raw = 1.0 - (distance / self.destination_longest_diagonal)**(tolerance)
return clamp(raw, 0.0, 1.0)
def transformed_mesh(self):
"""Transforms a copy of the source_mesh by the transformation."""
result = self.source_mesh.copy()
# but transform returns a tuple, so...
def one_return_transform(x):
return self.transform(x)[0]
transform_trimesh(result, one_return_transform)
return result
def projected_mesh(self):
"""Returns a copy of the source mesh transformed by the registration,
then projected down onto the destination mesh."""
result = self.transformed_mesh()
for i in range(len(result.vs)):
result.vs[i], _ = self.project(result.vs[i])
return result
def point_error(self, pt, nn = None):
if nn is None:
nn = self.destination_nearest_neighbors
return nearest_neighbor_distance(pt, nn)**2
def fit_error(self):
mesh = self.transformed_mesh()
return sum(map(self.point_error, mesh.vs))
def curvature_error(self):
mesh = self.transformed_mesh()
high_curvature_source = get_mesh_of_high_curvature(mesh)
high_curvature_destination = get_mesh_of_high_curvature(self.destination_mesh)
nn = (NearestNeighbors(n_neighbors=1,
algorithm="kd_tree").fit(high_curvature_destination.vs))
return sum(map(lambda pt: self.point_error(pt, nn), mesh.vs))
class FixedPairRegistrationAlgorithm(RegistrationAlgorithm):
def __init__(self, source_mesh, destination_mesh,
source_fixed_point = None, destination_fixed_point = None, verbose = False):
super(FixedPairRegistrationAlgorithm, self).__init__(source_mesh,
destination_mesh)
self.source_fixed = source_fixed_point
self.destination_fixed = destination_fixed_point
self.verbose = verbose
class PointMapping:
"""Encapsulates the mapping of a point of interest to another point of
interest, for use in recording the output of registration algorithms."""
def __init__(self, label, source, destination = None, confidence = None):
self.label = label
self.source = source
self.destination = destination
self.confidence = confidence
def __str__(self):
"""Returns the string representation of this PointMapping in the
format 'lbl x-src y-src z-src x-dst y-dst z-dst conf'."""
return "{0} {1:8f} {2:8f} {3:8f} {4:8f} {5:8f} {6:8f} {7:8f}".format(
self.label,
self.source[0],
self.source[1],
self.source[2],
self.destination[0],
self.destination[1],
self.destination[2],
self.confidence
)
def to_file(path, mappings):
"""Saves an array of PointMappings to a point mapping file specified
in path."""
try:
with open(path, "w") as f:
for i, point in enumerate(mappings):
if i != 0:
f.write("\n")
f.write(str(point))
except Exception as e:
print e
return None
to_file = staticmethod(to_file)
def from_file(path, source_mesh = None):
"""Parses an array of PointMappings from a point mapping file, and
returns that array and parsed grasp points as a tuple. If errors occur
in parsing, whatever points were successfully parsed will be
returned."""
try:
with open(path, "r") as f:
return PointMapping.from_string(f.readlines(), source_mesh)
except Exception as err:
print err
from_file = staticmethod(from_file)
def from_string(lines, source_mesh = None):
"""Parses an array of PointMappings from a string, and returns that
array. If errors occur in parsing, whatever points were successfully
parsed will be returned."""
points = []
grasp_points = (None, None)
for i, line in enumerate(lines):
splits = line.split()
try:
label = splits[0]
if label == "grasp-points":
grasp_points = (np.array([float(splits[1]),
float(splits[2]),
float(splits[3])]),
np.array([float(splits[4]),
float(splits[5]),
float(splits[6])]))
else:
if len(splits) == 2:
source = source_mesh.vs[int(splits[1])]
else:
source = np.array([float(splits[1]),
float(splits[2]),
float(splits[3])])
points.append(PointMapping(label, source))
except Exception as err:
print "Failed to parse line {0}: '{1}'".format(i, line)
return points, grasp_points
from_string = staticmethod(from_string)