forked from stephen-w-bailey/fast-n-deep-faces
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SSD.py
310 lines (261 loc) · 11 KB
/
SSD.py
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
from scipy.optimize import lsq_linear
import tqdm
limit = 1000
def rigidRegister(source, target):
# Normalize the data
v = target
p = source
pMean = np.mean(p,0)
vMean = np.mean(v,0)
pp = p - pMean
vp = v - vMean
# Compute the rotation
M = vp.T.dot(pp)
u,sig,v = np.linalg.svd(M)
sig = 1 / sig
Qsqrt = u.dot(np.diag(sig).dot(u.T))
R = Qsqrt.dot(M).T
if np.linalg.det(R) < 0:
print('det(R): '+str(np.linalg.det(R)))
print('rigidRegister: Error, not a rotation')
# Compute the translation
t = (vMean - pMean.dot(R)).astype('float32')
return R,t
# Implementation of the paper "Smooth Skinning Decomposition with Rigid Bones"
class SSD:
def __init__(self):
pass
def initialize(self, rest, meshes, k, iterations=20, faces=None):
# Create initial segments through k-means
whitened = whiten(rest)
codebook,distortion = kmeans(whitened,k)
assignment,dist = vq(whitened,codebook)
# Create initial bone configurations
m = len(meshes)
v = len(rest)
restBones = np.zeros((k,4,3))
for i in range(k):
restBones[i,:3] = np.eye(3)
restBones[i,3] = np.mean(rest[assignment==i],0)
bones = np.zeros((m,k,4,3))
restParts = [rest[assignment==i] - np.mean(rest[assignment==i],0) for i in range(k)]
def computeRigidBones(assignment):
for i in range(m):
for j in range(k):
if np.sum(assignment==j) < 3:
raise RuntimeError('Encountered bone with less than 3 vertices assigned')
part = meshes[i,assignment==j]
r,t = rigidRegister(restParts[j],part)
bones[i,j,:3] = r
bones[i,j,3] = t
return bones
bones = computeRigidBones(assignment)
# Loop a few times
for _ in tqdm.trange(iterations):
# Approximate all vertices with all bones
approx = np.zeros((k,m,v,3))
for i in range(k):
R = bones[:,i,:3] # m x 3 x 3
t = bones[:,[i],3] # m x 1 x 3
tRest = restBones[i,3] # 3
approx[i] = np.transpose(np.dot(np.transpose(R,(0,2,1)),(rest-tRest).T),(0,2,1))+t
# Assign each vertex to the bone that best approximates it
diff = np.mean(np.square(approx-meshes),(1,3)) # k x v
assignment = np.argmin(diff,0)
if faces is not None:
sums = np.asarray([np.sum(assignment==i) for i in range(k)])
while any(sums<3):
idx = list(sums<3).index(True)
f = np.random.choice(len(faces))
assignment[faces[f]] = idx
sums = np.asarray([np.sum(assignment==i) for i in range(k)])
# Update the bones
for i in range(k):
restBones[i,3] = np.mean(rest[assignment==i],0)
restParts = [rest[assignment==i] - np.mean(rest[assignment==i],0) for i in range(k)]
bones = computeRigidBones(assignment)
# Save the results
self.weights = np.zeros((v,k))
self.weights[range(v),assignment] = 1
self.restBones = restBones
self.rest = rest
self.bones = bones
self.meshes = meshes
# Fix the bones and compute the vertex weights with affinity k
def computeWeights(self,k=4):
numV = len(self.rest)
numB = len(self.restBones)
k = min(k,numB)
T = len(self.meshes)
for i in range(numV):
# Build the least squares problem
A = np.zeros((3*T,numB))
b = self.meshes[:,i].reshape(-1) # T*3
R = self.bones[:,:,:3] # T x numB x 3 x 3
t = self.bones[:,:,3] # T x numB x 3
v = self.rest[i]-self.restBones[:,3] # numB x 3
for j in range(numB):
Rv = np.sum(R[:,j].reshape((-1,3,3,1))*v[j].reshape((-1,3,1,1)),-3) # T x 3 x 1
Rvt = Rv.reshape((-1,3)) + t[:,j] # T x 3
A[:,j] = Rvt.reshape(-1)
# Solve the least squares problem
bounds = (0,1)
res = lsq_linear(A,b,bounds,method='bvls')
w = res.x
w = w / np.sum(w) # Fix any small numerical inaccuracies
# Find the k best weights
effect = np.sum(np.square(A),0)*np.square(w)
indices = np.argpartition(effect,numB-k)[numB-k:]
A = A[:,indices]
res = lsq_linear(A,b,bounds,method='bvls')
newW = res.x
newW = newW / np.sum(newW)
self.weights[i] = 0
self.weights[i][indices] = newW
def computeBones(self,meshes=None,bones=None):
if meshes is None:
meshes = self.meshes
bones = self.bones
elif bones is None:
raise ValueError('SSD::computeBones: New mesh provided without bones')
bones = bones.copy()
# Divide dataset to avoid memory errors
if len(bones) > limit:
count = len(bones)
bones1 = self.computeBones(meshes[:count//2],bones[:count//2])
bones2 = self.computeBones(meshes[count//2:],bones[count//2:])
bones = np.concatenate((bones1,bones2),0)
return bones
# Update the bones one at a time
numB = len(self.restBones)
T = len(meshes)
B = range(numB)
p = self.rest-self.restBones[:,3].reshape((-1,1,3)) # numB x v x 3
for b in range(numB):
# Remove the residual (Equation 6)
others = list(B)
del others[others.index(b)]
R = bones[:,others][:,:,:3] # T x numB-1 x 3 x 3
t = bones[:,others][:,:,3] # T x numB-1 x 3
v = p[others].transpose((0,2,1)) # numB-1 x 3 x v
q = meshes.copy() # T x v x 3
for j in range(len(others)):
Rv = np.sum(R[:,j].reshape((-1,3,3,1))*v[j].reshape((1,3,1,-1)),-3) # T x 3 x v
Rv = Rv.transpose((0,2,1)) # T x v x 3
Rvt = Rv + t[:,j][:,np.newaxis] # T x v x 3
q -= self.weights[:,others[j]].reshape((1,-1,1)) * Rvt
# Compute the remaining deformation
rest = p[b]
pStar = np.sum(np.square(self.weights[:,b])[...,np.newaxis]*rest,0) # v x 3 (Equation 8)
pStar = pStar/np.sum(np.square(self.weights[:,b]))
pBar = rest - pStar
qStar = np.sum(self.weights[:,b][...,np.newaxis]*q,1)/np.sum(np.square(self.weights[:,b])) # T x 3
qBar = q - self.weights[:,b][...,np.newaxis]*qStar.reshape((-1,1,3))
P = self.weights[:,b][...,np.newaxis]*pBar # v x 3
P = P.T # 3 x v
QT = qBar # T x v x 3
PQT = np.transpose(np.dot(np.transpose(QT,(0,2,1)),P.T),(0,2,1)) # T x 3 x 3
try:
u,_,v = np.linalg.svd(PQT)
except np.linalg.linalg.LinAlgError:
print('SVD error on the following matrix: '+str(PQT))
print('QT[0]: '+str(QT[0]))
print('P[0]: '+str(P[0]))
raise
u = u.transpose((0,2,1))
R = np.sum(v.reshape((-1,3,3,1))*u.reshape((-1,3,1,3)),-3)
t = qStar-R.transpose((0,1,2)).dot(pStar)
bones[:,b,:3] = R.transpose((0,2,1))
bones[:,b,3] = t
return bones
def runSSD(self,rest,meshes,numBones,k=4,faces=None):
print('Initializing:')
self.initialize(rest,meshes,numBones,faces=faces)
maxIter = 20
error = self.getFitError()
eps = 1e-8
print('Initial error: '+str(error))
for _ in range(maxIter):
self.computeWeights(k=k)
self.bones = self.computeBones()
newError = self.getFitError()
print('New error: '+str(newError))
if newError > error-eps:
break
error = newError
def fitBonesToMesh(self,meshes):
# Fit the bones first for rigid skinning
m = len(meshes)
k = self.bones.shape[1]
bones = np.zeros((m,k,4,3))
bones[:,:,:3] = np.eye(3)
assignment = np.argmax(self.weights,1)
restParts = [self.rest[assignment==i] - np.mean(self.rest[assignment==i],0) for i in range(k)]
for i in range(m):
for j in range(k):
part = meshes[i,assignment==j]
r,t = rigidRegister(restParts[j],part)
bones[i,j,:3] = r
bones[i,j,3] = t
initialError = self.getFitError(meshes,bones)
print('Rigid fit error: '+str(initialError))
maxItr = 10
eps = 1e-4
for i in range(maxItr):
bones = self.computeBones(meshes,bones)
error = self.getFitError(meshes,bones)
print('Fit error: '+str(error))
if error > initialError-eps:
break
initialError = error
return bones
def getFitError(self,meshes=None,bones=None,returnMean=True):
if meshes is None:
meshes = self.meshes
bones = self.bones
elif bones is None:
raise ValueError('SSD::getFitError: New mesh provided without bones')
# Divide dataset to avoid memory errors
if len(bones) > limit:
count = len(bones)
diff1 = self.getFitError(meshes[:count//2],bones[:count//2],False)
diff2 = self.getFitError(meshes[count//2:],bones[count//2:],False)
diff = np.concatenate((diff1,diff2),0)
if returnMean:
return np.mean(diff)
else:
return diff
# Rigidly transform by every bone (not that efficient)
k = self.weights.shape[1]
v = self.rest.shape[0]
T = len(bones)
approx = np.zeros((T,k,v,3))
for i in range(k):
R = bones[:,i,:3] # T x 3 x 3
t = bones[:,[i],3] # T x 1 x 3
tRest = self.restBones[i,3] # 3
vR = R.transpose((0,2,1)).dot((self.rest-tRest).T).transpose((0,2,1))
approx[:,i] = vR+t
weights = self.weights.T[...,np.newaxis] # k x v x 1
approx = np.sum(weights*approx,1)
diff = np.sqrt(np.sum(np.square(approx-meshes),-1))
if returnMean:
return np.mean(diff)
else:
return diff
def computeMesh(self,bones):
# Rigidly transform by every bone (not that efficient)
k = self.weights.shape[1]
v = self.rest.shape[0]
approx = np.zeros((k,v,3))
for i in range(k):
R = bones[i,:3] # 3 x 3
t = bones[[i],3] # 1 x 3
tRest = self.restBones[i,3] # 3
approx[i] = (self.rest-tRest).dot(R)+t
# Apply blending
weights = self.weights.T[...,np.newaxis] # k x v x 1
approx = np.sum(weights*approx,0) # v x 3
return approx