Skip to content

Commit e0c07ee

Browse files
Tutorial: Non-Rigid Structure-from-Motion
1 parent 2aa9fe5 commit e0c07ee

File tree

2 files changed

+326
-1
lines changed

2 files changed

+326
-1
lines changed

docs/source/conf.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,9 @@
6666
# Modules for which function level galleries are created.
6767
'doc_module': 'pyproximal',
6868
# Insert links to documentation of objects in the examples
69-
'reference_url': {'pyproximal': None}
69+
'reference_url': {'pyproximal': None},
70+
# Allow animations
71+
'matplotlib_animations': True,
7072
}
7173

7274
# Always show the source code that generates a plot

tutorials/nrsfm.py

Lines changed: 323 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,323 @@
1+
r"""
2+
Non-rigid structure-from-motion (NRSfM)
3+
=======================================
4+
In computer vision, structure-from-motion (SfM) is an imaging technique for
5+
estimating three-dimensional structures from two-dimensional images. Theoretically,
6+
the problem is generally well-posed when considering rigid objects, meaning
7+
that the objects do not move or deform in the scene. However, non-static scenes
8+
are still relevant and have gained increased popularity among researchers in
9+
recent years. This is known as *non-rigid structure-from-motion*.
10+
11+
In this tutorial, we will consider motion capture (MOCAP). This is a special
12+
case, where we use images from multiple camera views to compute the 3D positions
13+
of specifically designed markers that track the motion of a person (or object)
14+
performing various tasks.
15+
16+
Non-rigid shapes
17+
****************
18+
To make the problem well-posed, one has to control the complexity of
19+
the deformations using some minor assumptions on the possible space of object
20+
shapes. This is not a weird thing to do: consider e.g. the human body,
21+
we have different joints that bend and turn in a finite amount of ways; the
22+
skeleton itself is rigid and not capable of such deformations. For this reason,
23+
Bregler et al. [1]_ suggested that all movements (or shapes) can be represented
24+
by a low-dimensional basis. In the context of motion capture, this means that
25+
every movement a person does can be considered a combination of core movements
26+
(or basis shapes).
27+
28+
Mathematically speaking, this translates to any motion being a linear combination
29+
of the basis shapes, i.e. assuming there are :math:`K` basis shapes, any non-rigid
30+
shape :math:`X_i` can be written as
31+
32+
.. math::
33+
X_i = \sum_{i=1}^K c_{ik}B_k
34+
35+
where :math:`c_{ik}` are the basis coefficients and :math:`B_k` are the basis shapes.
36+
Here, :math:`X_i` is a :math:`3\times N` matrix where each column is a point in
37+
3D space.
38+
39+
The CMU MOCAP dataset
40+
*********************
41+
Let us first try to understand the data we are given. We will use the *Pickup*
42+
instance from the CMU MOCAP dataset, which depicts a person picking something
43+
up from the floor.
44+
"""
45+
46+
import matplotlib.pyplot as plt
47+
import matplotlib.animation as animation
48+
import numpy as np
49+
import scipy as sp
50+
51+
52+
plt.close('all')
53+
np.random.seed(0)
54+
data = np.load('../testdata/mocap.npz', allow_pickle=True)
55+
X_gt = data['X_gt']
56+
markers = data['markers'].item()
57+
58+
###############################################################################
59+
# First we view the first 3D poses. In order to easily visualize the person, we
60+
# draw a skeleton between the markers corresponding to certain body parts. Note
61+
# that these are not used in any other way.
62+
63+
64+
def plot_first_3d_pose(ax, X, color='b', marker='o', linecolor='k'):
65+
ax.scatter(X[0, :], X[1, :], X[2, :], color, marker=marker)
66+
for j, ind in enumerate(markers.values()):
67+
ax.plot(X[0, ind], X[1, ind], X[2, ind], '-', color=linecolor)
68+
ax.set_box_aspect(np.ptp(X[:3, :], axis=1))
69+
ax.view_init(20, 25)
70+
71+
72+
fig = plt.figure()
73+
ax = fig.add_subplot(projection='3d')
74+
plot_first_3d_pose(ax, X_gt)
75+
plt.tight_layout()
76+
77+
###############################################################################
78+
# Now, we turn the attention to the data the algorithm is given, which is a
79+
# sequence of 2D images from varying views. The goal is to recreate the 3D
80+
# points, such as in the example above, from all timestamps.
81+
82+
M = data['M']
83+
F = int(X_gt.shape[0] / 3)
84+
85+
86+
def _update(f: int):
87+
X = M[2 * f:2 * f + 2, :]
88+
lines[0].set_data(X[0, :], X[1, :])
89+
for j, ind in enumerate(markers.values()):
90+
lines[j + 1].set_data(X[0, ind], X[1, ind])
91+
return lines
92+
93+
94+
fig, ax = plt.subplots()
95+
lines = ax.plot([], [], 'r.')
96+
for _ in range(len(markers)):
97+
lines.append(ax.plot([], [], 'k-')[0])
98+
ax.set(xlim=(-2.5, 2.5), ylim=(-3.5, 3.5))
99+
ax.set_aspect('equal')
100+
101+
ani = animation.FuncAnimation(fig, _update, F, interval=25, blit=True)
102+
103+
104+
###############################################################################
105+
# Note that these are the 2D image correspondences and that the image view is
106+
# constantly changing as it is spinning around. Such motion can be modeled
107+
# with orthographic cameras, which we will discuss next.
108+
#
109+
# Orthographic projections
110+
# ************************
111+
# Assuming that we know the pose of the camera from which the image was taken
112+
# the corresponding 2D image point can be obtained. In the case of rotations,
113+
# we assume the cameras are orthographic, meaning that the image points :math:`x_i`
114+
# are obtained from the relation
115+
#
116+
# .. math::
117+
# x_i = R_iX_i
118+
#
119+
# where :math:`R_i` is a :math:`2\times 3` matrix fulfilling :math:`R_iR_i^T=I`.
120+
# Essentially, the :math:`R_i` matrices consists of the top two rows of the
121+
# corresponding rotation matrix.
122+
#
123+
# Now, the task at hand is essentially the inverse problem: to reconstruct the
124+
# 3D points for each point in time from these 2D images.
125+
#
126+
# Treating NRSfM as a low-rank factorization problem
127+
# **************************************************
128+
# One of the main novelties of the paper by Dai et al. [2]_ is to reshape and
129+
# stack the non-rigid shapes :math:`X_i` in a way that allows us to treat the
130+
# problem using methods from low-rank factorization. This is done in the following
131+
# way: first concatenate all rows of :math:`X_i` creating a vector
132+
# :math:`X^\sharp_i` of size :math:`1\times 3N`. Secondly, assuming there are in
133+
# total :math:`F` non-rigid shapes we create the matrix :math:`X^\sharp` of size
134+
# :math:`F\times 3N` by stacking all :math:`X^\sharp_i`. This enables us to decompose
135+
# the newly created matrix :math:`X^\sharp=CB^\sharp` in the low-rank factors
136+
# consisting of the shape coefficients :math:`C` and the basis shapes :math:`B^\sharp`
137+
# (constructed in the same way as :math:`X^\sharp`).
138+
#
139+
# Now, let us implement and visualize this approach.
140+
141+
142+
def stack(X: np.ndarray):
143+
return np.hstack((X[::3, :], X[1::3, :], X[2::3, :]))
144+
145+
146+
Xi = np.arange(15).reshape((3, 5))
147+
fig, ax = plt.subplots(1, 2)
148+
ax[0].matshow(Xi)
149+
ax[0].set_title(r'$X_i$')
150+
ax[0].axis('off')
151+
ax[1].matshow(stack(Xi))
152+
ax[1].set_title(r'$X_i^\sharp$')
153+
ax[1].axis('off')
154+
plt.tight_layout()
155+
156+
###############################################################################
157+
# Furthermore, we introduce the inverse
158+
# operation, such that :math:`X=\mathcal{U}(X^\sharp)`, where
159+
# :math:`\mathcal{U}` is the "unstacking" operator.
160+
161+
162+
def unstack(Xs: np.ndarray):
163+
"""Inverse operation of stack."""
164+
m, n = Xs.shape
165+
m *= 3
166+
n //= 3
167+
X = np.zeros((m, n), dtype=Xs.dtype)
168+
X[::3] = Xs[:, :n]
169+
X[1::3] = Xs[:, n:2*n]
170+
X[2::3] = Xs[:, 2*n:3*n]
171+
return X
172+
173+
###############################################################################
174+
# In many cases, the necessary amount of basis shapes is not known
175+
# *a priori*. Therefore, a suitable objective to try to minimize is
176+
#
177+
# .. math::
178+
# \argmin_X \mu \rank(X^\sharp) + \frac{1}{2}\sum_{i=1}^F\|R_iX_i - x_i\|_2^2
179+
#
180+
# or, equivalently,
181+
#
182+
# .. math::
183+
# \argmin_X \mu \rank(X^\sharp) + \frac{1}{2}\|RX - M\|_F^2
184+
#
185+
# where :math:`R` is a block-diagonal matrix with :math:`R_i` on the main diagonal,
186+
# whereas :math:`X` and :math:`M` are the concatenations of :math:`X_i` and
187+
# :math:`x_i`, respectively.
188+
#
189+
# Since the rank function is non-convex and discontinuous, it is often replaced
190+
# by a relaxation. In [2]_ the *nuclear norm* :math:`\|\cdot\|_{*}` was used, i.e.
191+
# we seek to minimize
192+
#
193+
# .. math::
194+
# \argmin_X \mu \|X^\sharp\|_{*} + \frac{1}{2}\|RX - M\|_F^2 \; .
195+
#
196+
# There are some theoretical justifications for this specific choice of relaxation,
197+
# e.g. the nuclear norm is the convex envelope of the rank function under
198+
# curtain assumptions [3]_.
199+
#
200+
# Solving the relaxed problem
201+
# ***************************
202+
# We will now show how to solve this problem using splitting schemes. Specifically,
203+
# we will use :class:`pyproximal.ADMM` and re-write the objective as
204+
#
205+
# .. math::
206+
# \argmin_{X, Z} \mu \|Z^\sharp\|_{*} + \frac{1}{2}\|RX - M\|_F^2,
207+
#
208+
# and add the constraint :math:`X=Z`. This way, the proximal operators
209+
# are simply those of the (stacked) nuclear norm and the Frobenius norm.
210+
# We implement these next:
211+
212+
from pyproximal.ProxOperator import _check_tau
213+
from pyproximal import Nuclear, ProxOperator
214+
215+
216+
class BlockDiagFrobenius(ProxOperator):
217+
r"""Proximal operator for 1/2 * ||RX - M||_F^2 where R is block-diagonal.
218+
Note: You could also wrap pyproximal.L2, but this class is used here in
219+
this tutorial to increase legibility.
220+
"""
221+
def __init__(self, dim, R, M):
222+
super().__init__(None, False)
223+
self.dim = dim
224+
self.R = R
225+
self.M = M
226+
227+
def __call__(self, x):
228+
X = x.reshape(self.dim)
229+
return 0.5 * np.linalg.norm(self.R @ X - self.M, 'fro') ** 2
230+
231+
@_check_tau
232+
def prox(self, x, tau):
233+
X = x.reshape(self.dim)
234+
Y = np.zeros_like(X)
235+
for f, Rf in enumerate(self.R):
236+
Y[3 * f: 3 * f + 3, :] = np.linalg.solve(
237+
tau * Rf.T @ Rf + np.eye(3),
238+
tau * Rf.T @ self.M[2 * f:2 * f + 2, :] + X[3 * f: 3 * f + 3, :]
239+
)
240+
return Y.flatten()
241+
242+
243+
class StackedNuclear(Nuclear):
244+
r"""Proximal operator for the stacked nuclear norm."""
245+
def __init__(self, dim, sigma=1.):
246+
super().__init__(dim, sigma)
247+
self.unstacked_dim = (dim[0] * 3, dim[1] // 3)
248+
249+
def __call__(self, x):
250+
X = stack(x.reshape(self.unstacked_dim))
251+
return super().__call__(X.ravel())
252+
253+
def prox(self, x, tau):
254+
X = stack(x.reshape(self.unstacked_dim))
255+
x = super().prox(X.ravel(), tau)
256+
X = unstack(x.reshape(self.dim))
257+
return X.ravel()
258+
259+
260+
###############################################################################
261+
# Now we are ready to solve the problem using ADMM.
262+
263+
from pyproximal.optimization.primal import ADMM
264+
265+
266+
mu = 1
267+
R = data['R']
268+
Rblk = sp.linalg.block_diag(*R)
269+
M = Rblk @ X_gt
270+
N = M.shape[1]
271+
normal_size = (3*F, N)
272+
stacked_size = (F, 3*N)
273+
X0 = np.zeros(normal_size)
274+
proxf = BlockDiagFrobenius(normal_size, R, M)
275+
proxg = StackedNuclear(stacked_size, mu)
276+
X_rec = ADMM(proxf, proxg, x0=X0.flatten(), tau=0.9, niter=200)[0]
277+
X_rec = X_rec.reshape(normal_size)
278+
279+
###############################################################################
280+
# Let us compare the results with the ground truth data.
281+
fig = plt.figure()
282+
ax = fig.add_subplot(projection='3d')
283+
plot_first_3d_pose(ax, X_gt)
284+
plot_first_3d_pose(ax, X_rec, color='r', marker='v', linecolor='r')
285+
plt.tight_layout()
286+
287+
###############################################################################
288+
# Furthermore, we compute some statistics on the reconstruction performance. You
289+
# can vary the regulation strength :math:`\mu` to see if you can achieve better
290+
# performance yourself!
291+
print(f'Datafit: {np.linalg.norm(Rblk @ X_rec - M, "fro")}')
292+
print(f'Distance to GT: {np.linalg.norm(X_rec - X_gt, "fro")}')
293+
294+
###############################################################################
295+
# One issue with the nuclear norm is that you have the hyperparameter
296+
# :math:`\mu` that regulates the impact of the datafit vs. model assumption.
297+
# When :math:`\mu=0` the datafit is perfect, but there would be no enforcement
298+
# of the basis shapes, leading to severe over-fitting. On the other end, as
299+
# :math:`\mu\to\infty` the reconstruction turns towards the zero matrix, thus
300+
# completely ignoring the given data.
301+
#
302+
# Later publications have tried to mitigate this issue, and have shown that
303+
# the weighted nuclear norm performs even better when the weights are selected
304+
# with care [4]_. Other non-convex relaxations show similar results [5]_.
305+
#
306+
# **References**
307+
#
308+
# .. [1] C. Bregler, A. Hertzmann, and H. Biermann. Recovering non-rigid 3d shape
309+
# from image streams. In The IEEE Conference on Computer Vision and Pattern
310+
# Recognition (CVPR), 2000.
311+
# .. [2] Y. Dai, H. Li, and M. He. A simple prior-free method for non-rigid
312+
# structure-from-motion factorization. International Journal of Computer Vision,
313+
# 107(2):101–122, 2014.
314+
# .. [3] M. Fazel, H. Hindi, and S. P. Boyd. A rank minimization heuristic with
315+
# application to minimum order system approximation. In the Proceedings of the
316+
# American Control Conference (ACC), 2001.
317+
# .. [4] S. Kumar. Non-rigid structure from motion: Prior-free factorization method
318+
# revisited. In The IEEE Winter Conference on Applications of Computer Vision
319+
# (WACV), 2020.
320+
# .. [5] M. Valtonen Örnhag and C. Olsson. A unified optimization framework for
321+
# low-rank inducing penalties. In the Proceedings of the IEEE/CVF conference
322+
# on computer vision and pattern recognition (CVPR), 2020.
323+

0 commit comments

Comments
 (0)