Algorithmcore
Image-based visual servoing
Also called IBVS.
Moves the camera with a velocity from the pseudoinverse of the interaction matrix times the image feature error.
- Time
- O(k) per_step
- Space
- O(k) extra
- Where
- k = the number of point features; the bounds are for one control step
- Model
- Real RAM
- Properties
- deterministicnot exactonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bernard Espiau, Francois Chaumette, Patrick Rives, 1992
Image-based visual servoing (IBVS) moves a camera so that features in its image, such as the image points of a few target corners, reach their positions in a reference image taken at the goal. The controller works directly on the image error . It computes the camera velocity , where is the interaction matrix that maps camera velocity to feature velocity and is its pseudoinverse. The method does not need a 3D model of the target or an estimate of its pose, and it is robust to errors in the camera calibration. It needs the depths of the points, or an estimate of them, and its camera path in 3D space is not controlled, so it can make large or useless motions.
In plain words
You hold a camera and look at a target. You also have a photo taken from the place where you want to be. You compare the two images: each corner of the target should move from where it is now to where it is in the photo. The interaction matrix tells you how the corners move in the image when you move the camera. So you choose the camera motion that moves the corners straight toward their places, at a speed proportional to how far they still have to go.
Because you only look at the image, the camera can take odd paths. If the target is turned half a turn, the straight image paths all pass through the center, and the only motion that does that is to back away from the target.
The problem
A calibrated camera is moved by a robot that accepts a camera twist , angular part first, in the camera frame. It sees points of a fixed target, with normalized image coordinates and depths . The desired features are those seen at the goal pose. Find at each step so that , which for enough points in general position means that the camera reaches the goal pose.
The algorithm
Each control step reads the features and the depths, and returns a twist.
IBVS-STEP(s, Z, s*, λ)- 1
e ← s - s* - 2
L ← stack over i of [[x_i y_i, -(1 + x_i²), y_i, -1/Z_i, 0, x_i/Z_i], [1 + y_i², -x_i y_i, -x_i, 0, -1/Z_i, y_i/Z_i]] - 3
L⁺ ← (Lᵀ L)⁻¹ Lᵀ - 4
V ← -λ L⁺ e - 5
return V
The robot applies for one sample time, the camera takes a new image, and the step repeats. Line L2 uses the current features and depths. Two other choices are common: the matrix at the goal, with the goal depths, which is constant and needs no depth estimate during the motion, and the mean . The columns are ordered as here; Chaumette and Hutchinson order them as . With exactly three points, is square and line L3 is the plain inverse.
Example
Four points form a square of side 0.2 m, centered on the optical axis at a depth of 1 m in the goal pose, so . The camera starts at the goal position, but rotated by about its optical axis. Each point now appears where its neighbor should be: the first point is seen at but should be at , so its error is . With , line L2 gives its two rows as and . With , lines L3 and L4 give
a rotation about the optical axis and a translation backward along it. As a check, the two rows times give , which is for this point.
Applying each twist for 10 ms gives:
| time (s) | angle left (rad) | distance moved back (m) | |
|---|---|---|---|
| 0 | 0.400 | 1.571 | 0 |
| 0.5 | 0.243 | 0.995 | 0.387 |
| 1 | 0.147 | 0.524 | 0.371 |
| 2 | 0.054 | 0.153 | 0.143 |
| 5 | 0.0026 | 0.0066 | 0.0066 |
The camera moves back up to 0.419 m at s and then returns. With the constant matrix instead, it first moves forward, up to 0.330 m toward the target, which is worse if the target is close. In both cases the error shrinks by about .
Correctness
Under the law, . The matrix is the orthogonal projection onto the range of , so : the image error never grows. With three points the projection is the identity and decays exactly like . With more points the error can stop at with , a local minimum. Near the goal, the linearized loop in pose coordinates is , so the goal is locally exponentially stable. For a rotation by about the optical axis with the target plane parallel to the image, the first twist is and . At the camera only moves back, and its depth becomes infinite in finite time. The proofs are in the proof file.
Proof: IBVS makes the image error decrease and converges locally at the rate lambdafull
The camera moves with the body twist , angular part first, expressed in the camera frame. A point fixed in the world has camera coordinates with and image coordinates , . The feature vector stacks the image coordinates of points, , and is the stacked interaction matrix. We assume that has full column rank 6 along the motion, so , and that the depths in are exact.
Lemma 1 (interaction matrix of a point). and .
Proof. A point fixed in the world moves in the camera frame as . So , and . Then . Putting in the three derivatives and , gives , which is the first formula. The second follows in the same way from .
So , and under the law the error obeys .
Theorem 1 (the image error does not grow). Along the closed loop, . It is zero exactly when .
Proof. is symmetric and , so it is the orthogonal projection onto the range of . Then . The projection is zero if and only if is orthogonal to the range of , that is .
With three points, is square and , so and while stays invertible. With four or more points, , and the set with contains the local minima of IBVS: the camera stops at a pose that is not the goal.
Theorem 2 (local exponential convergence of the pose). Let the goal pose be the identity, let be the features at the camera pose , and let , the interaction matrix at the goal, have rank 6. Write . Then the linearization of the closed loop at is , so the goal is locally exponentially stable with rate .
Proof. Near the identity, , because the right Jacobian of the exponential map is . By Lemma 1, . The matrices and depend smoothly on near 0, so , since for full column rank. So , and Lyapunov's indirect method gives local exponential stability.
Proposition 3 (rotation about the optical axis). Let all points have the same depth in both poses, with the target plane parallel to the image plane, and let the camera be rotated by an angle about its optical axis, so that every current feature is , with the plane rotation. With at the current features, the first twist is , , and all other components are zero.
Proof. Write for the rotation of the plane by . For one point, the column of Lemma 1 is and the column is . Since and , we get . The candidate twist gives for every point. So is in the range of , and since has full column rank, is the unique with , which is the candidate.
For , , so the camera first moves backward along its optical axis. With at the desired features, the same computation with in place of gives , a forward motion.
Corollary 4 (half turn). Let the target be at depth 1 in the goal pose, and let the camera start rotated by about its optical axis at depth . Then the law is a pure backward translation for all time, and the depth is , which is infinite at .
Proof. While the rotation is and the camera has only moved along its optical axis, the current features are . Then , and gives . By full column rank this is the twist of the law. It has and moves the camera only along its optical axis, so the form stays valid, and . Separating variables, , which solves to the formula. Its denominator vanishes at the stated time.
In this case the image error is exactly, as Theorem 1 with predicts, but the features reach the image center when the camera is infinitely far away. This is the classical failure of IBVS for a half turn about the optical axis.
Complexity
In the real-RAM model, with points, line L2 builds a matrix in time. Line L3 forms in operations and inverts a matrix in constant time, and line L4 is . So one step takes time and memory. In practice the image processing that finds and tracks the features costs far more than the control law.
Properties
- Image error decreases. With exact depths, is nonincreasing along the continuous-time loop, and the features move on nearly straight lines in the image, which helps to keep them in view.
- No pose estimate. The law uses the features directly. Calibration errors change and so the path, but if the reference image was taken with the same camera, the loop still stops where the image equals the reference image.
- Uncontrolled camera path. The path in 3D space can be far from a straight line, and large rotations about the optical axis cause a retreat or an advance.
- Local minima and singularities. With four or more points, the loop can stop at a pose where but . loses rank for three collinear points, and for three points there are configurations where it is singular.
- Local stability only. The convergence results hold near the goal; global convergence is not guaranteed.
Variants and improvements
- Constant matrix . Compute once at the goal. It needs no depth estimate, but its region of convergence is smaller and it can drive the camera toward the target.
- Mean matrix. Use , as proposed by Malis. For a rotation about the optical axis it gives a pure rotation, but it is singular at a half turn, and for the square of the example also at a quarter turn.
- Depth estimation. Estimate online from the known camera motion, or use a constant guess such as .
- Other features. Use lines, image moments or cylindrical coordinates of points instead of Cartesian points; image moments decouple the rotation about the optical axis.
- Hybrid and switching schemes. 2.5D visual servoing (Malis, Chaumette and Boudet) controls the rotation from a partial pose estimate and the rest from the image; other schemes switch between IBVS and PBVS.
- Eye-to-hand. The camera is fixed and watches the end effector; the same law applies with the robot Jacobian between the twist and the joints.
When to use it
Use it when the goal is given by a reference image rather than a pose, when the camera calibration or the target model is uncertain, and when the motion from the start to the goal is moderate: positioning a gripper above a part, docking, or tracking a moving target. For large rotations, or when the camera path in space must be controlled, use position-based visual servoing or a hybrid scheme.
Pitfalls
- Depths. The translation columns of scale with . A wrong depth changes the gain and the direction of the motion; a negative or zero depth estimate breaks the law.
- Half turn about the optical axis. The camera retreats to infinity. Plan a rotation first or use another feature set.
- Features leave the image. The law does not keep features in view. Add a constraint or a secondary task in the null space of .
- Too few or degenerate features. Three points in general position give a square but several poses with the same image; four points avoid this but bring local minima. Collinear points make singular.
- Gain and delay. The image is slow and delayed; a large with a slow camera makes the loop oscillate. Saturate the twist.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/image-based-visual-servoing/. The authors are listed in prov/A4GWRN.jsonl.
"""Image-based visual servoing (IBVS) with point features.
The camera frame has its z axis along the optical axis. A point with
camera coordinates (X, Y, Z) has the normalized image coordinates
x = X / Z and y = Y / Z (a calibrated camera with unit focal length).
The camera twist V = (omega, v) is expressed in the camera frame,
angular part first, and the camera pose T_wc moves by T_wc exp([V] dt).
The law is V = -lambda L^+ (s - s*), with L the stacked interaction
matrix of the points.
Matrices are lists of rows and vectors are lists. Only the standard library.
"""
from rbm import T_apply, T_inv, mul, norm, pinv_right, se3_exp, sub, transpose
def project(t_wc, p_w):
"""Return (x, y, Z) of the world point p_w seen from the camera pose t_wc."""
x, y, z = T_apply(T_inv(t_wc), p_w)
if z <= 0.0:
raise ValueError("point is behind the camera")
return x / z, y / z, z
def point_interaction(x, y, z):
"""Return the 2 by 6 interaction matrix of the image point (x, y) at depth z.
The columns are for (omega_x, omega_y, omega_z, v_x, v_y, v_z).
"""
return [
[x * y, -(1.0 + x * x), y, -1.0 / z, 0.0, x / z],
[1.0 + y * y, -x * y, -x, 0.0, -1.0 / z, y / z],
]
def interaction_matrix(s, depths):
"""Stack the point interaction matrices; s = (x1, y1, x2, y2, ...)."""
rows = []
for i, z in enumerate(depths):
rows.extend(point_interaction(s[2 * i], s[2 * i + 1], z))
return rows
def ibvs_step(s, s_star, depths, lam, choice="current", depths_star=None):
"""Return the camera twist V = -lam L^+ (s - s*).
choice selects the matrix: "current" uses s and the current depths,
"desired" uses s* and depths_star, and "mean" uses the mean of the two.
"""
e = sub(s, s_star) # @line L1
if choice == "current":
lmat = interaction_matrix(s, depths) # @line L2
elif choice == "desired":
lmat = interaction_matrix(s_star, depths_star)
elif choice == "mean":
a, b = interaction_matrix(s, depths), interaction_matrix(s_star, depths_star)
lmat = [[(p + q) / 2.0 for p, q in zip(ra, rb)] for ra, rb in zip(a, b)]
else:
raise ValueError("unknown choice of interaction matrix")
# L has full column rank 6 for three or more points in general position;
# then L^+ = (L^T L)^-1 L^T, the transpose of the right pseudoinverse of L^T.
lplus = transpose(pinv_right(transpose(lmat))) # @line L3
v = [-lam * sum(lplus[i][j] * e[j] for j in range(len(e))) for i in range(6)] # @line L4
return v # @line L5
def features(t_wc, points_w):
"""Return the feature vector s and the depths of the points."""
s, depths = [], []
for p in points_w:
x, y, z = project(t_wc, p)
s.extend([x, y])
depths.append(z)
return s, depths
def simulate(points_w, t_wc, s_star, lam, dt, steps, choice="current", depths_star=None):
"""Run IBVS with exact features and depths; the twist is held for dt.
Return a list of (t_wc, s, |e|) for the steps 0 to steps.
"""
out = []
for k in range(steps + 1):
s, depths = features(t_wc, points_w)
out.append((t_wc, s, norm(sub(s, s_star))))
if k < steps:
v = ibvs_step(s, s_star, depths, lam, choice, depths_star)
t_wc = mul(t_wc, se3_exp([dt * c for c in v]))
return out
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.
Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.
The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""
import math
# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2
# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2
# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12
# ---------------------------------------------------------------- matrices
def zeros(n, m):
"""Return the n by m zero matrix."""
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, s):
"""Return s * a for a vector or a matrix a and a number s."""
if _is_matrix(a):
return [[s * x for x in row] for row in a]
return [s * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def mul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x, y):
"""Return the dot product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(x):
"""Return the Euclidean norm of a vector."""
return math.sqrt(dot(x, x))
def cross(a, b):
"""Return the cross product a x b of two 3-vectors."""
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
def _max_abs(a):
return max((abs(x) for row in a for x in row), default=0.0)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a square matrix. b is a vector or a matrix with one column per
right-hand side; the result has the same shape as b. Raise ValueError
if a pivot is at most PIVOT_TOL times the largest entry of a.
"""
n = len(a)
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
k = len(rhs[0]) if rhs else 0
tol = PIVOT_TOL * _max_abs(a)
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
raise ValueError("matrix is singular to working precision")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0.0:
row_r, row_c = m[r], m[c]
for j in range(c, n + k):
row_r[j] -= f * row_c[j]
x = [[0.0] * k for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(k):
s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def inv(a):
"""Return the inverse of the square matrix a (see solve for errors)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a by elimination."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0.0:
return 0.0
if piv != c:
m[c], m[piv] = m[piv], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T.
a must be symmetric positive definite. Raise ValueError if a diagonal
entry of the factor is not positive.
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def pinv_right(j):
"""Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
jt = transpose(j)
return mul(jt, inv(mul(j, jt)))
# ---------------------------------------------------------------- hat and vee
def hat3(w):
"""Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
return [
[0.0, -w[2], w[1]],
[w[2], 0.0, -w[0]],
[-w[1], w[0], 0.0],
]
def vee3(m):
"""Return the 3-vector w of a skew-symmetric matrix m = [w]."""
return [m[2][1], m[0][2], m[1][0]]
def hat6(v):
"""Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
w = hat3(v[:3])
return [
[w[0][0], w[0][1], w[0][2], v[3]],
[w[1][0], w[1][1], w[1][2], v[4]],
[w[2][0], w[2][1], w[2][2], v[5]],
[0.0, 0.0, 0.0, 0.0],
]
def vee6(m):
"""Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]
# ---------------------------------------------------------------- rotations
def rot_x(a):
"""Return the rotation by a radians about the x axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a):
"""Return the rotation by a radians about the y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a):
"""Return the rotation by a radians about the z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def rpy(roll, pitch, yaw):
"""Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))
def so3_exp(w):
"""Return exp([w]) for exponential coordinates w = omega_hat * theta.
Rodrigues' formula in the form I + A [w] + B [w]^2 with
A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
"""
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
else:
a = math.sin(t) / t
b = (1.0 - math.cos(t)) / (t * t)
k = hat3(w)
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].
theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
above pi - NEAR_PI, the axis comes from the symmetric part
((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
from s. At theta = pi both signs are valid; the sign is then chosen so
that the largest component of the axis is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
c = max(-1.0, min(1.0, c))
s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
sn = norm(s)
t = math.atan2(sn, c)
if t < SERIES_THETA:
t2 = t * t
f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
return [f * x for x in s]
if t <= math.pi - NEAR_PI:
return [t / sn * x for x in s]
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
# b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
# diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
axis = [x / norm(col) for x in col]
if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
axis = [-x for x in axis]
return [t * x for x in axis]
# ---------------------------------------------------------------- poses
def make_T(r, p):
"""Return the 4x4 pose [[r, p], [0, 1]]."""
return [
[r[0][0], r[0][1], r[0][2], p[0]],
[r[1][0], r[1][1], r[1][2], p[1]],
[r[2][0], r[2][1], r[2][2], p[2]],
[0.0, 0.0, 0.0, 1.0],
]
def _rp(t):
return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]
def T_inv(t):
"""Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
r, p = _rp(t)
rt = transpose(r)
return make_T(rt, [-x for x in matvec(rt, p)])
def T_apply(t, x):
"""Return R x + p, the image of the point x under the pose t."""
r, p = _rp(t)
return add(matvec(r, x), p)
def se3_exp(xi):
"""Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.
The rotation is so3_exp(w). The translation is G v with
G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
translation by v.
"""
w, v = xi[:3], xi[3:]
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
else:
b = (1.0 - math.cos(t)) / (t * t)
c = (t - math.sin(t)) / (t * t * t)
k = hat3(w)
k2 = mul(k, k)
g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
return make_T(so3_exp(w), matvec(g, v))
def se3_log(t):
"""Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].
w = so3_log(R) and v = G^(-1) p with
G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
"""
r, p = _rp(t)
w = so3_log(r)
th = norm(w)
if th < SERIES_THETA:
t2 = th * th
d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
else:
half = th / 2.0
d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
k = hat3(w)
k2 = mul(k, k)
gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
return w + matvec(gi, p)
def adjoint(t):
"""Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
r, p = _rp(t)
pr = mul(hat3(p), r)
out = zeros(6, 6)
for i in range(3):
for j in range(3):
out[i][j] = r[i][j]
out[i + 3][j + 3] = r[i][j]
out[i + 3][j] = pr[i][j]
return out
# ---------------------------------------------------------------- quaternions
def quat_mul(q, r):
"""Return the Hamilton product q r of quaternions (w, x, y, z)."""
a1, b1, c1, d1 = q
a2, b2, c2, d2 = r
return [
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
]
def quat_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return [q[0], -q[1], -q[2], -q[3]]
def quat_to_rot(q):
"""Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.
q need not be of unit length; the result is the rotation of q / |q|.
"""
w, x, y, z = q
n = w * w + x * x + y * y + z * z
s = 2.0 / n
return [
[1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
[s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
[s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
]
def quat_from_axis_angle(axis, angle):
"""Return (cos(angle / 2), sin(angle / 2) axis / |axis|).
A zero axis is allowed only with angle 0 (the identity); otherwise
raise ValueError.
"""
n = norm(axis)
if n == 0.0:
if angle == 0.0:
return [1.0, 0.0, 0.0, 0.0]
raise ValueError("zero axis with a nonzero angle")
s = math.sin(angle / 2.0) / n
return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]
# ---------------------------------------------------------------- derivatives
def num_jacobian(f, x, h=1e-6):
"""Return the Jacobian of f at x by central differences with step h.
f maps a list of n numbers to a list of m numbers; the result is m by n.
"""
cols = []
for i in range(len(x)):
xp = list(x)
xm = list(x)
xp[i] += h
xm[i] -= h
fp, fm = f(xp), f(xm)
cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
return transpose(cols)
# ---------------------------------------------------------------- self-test
def self_test():
"""Check the area check values; return True or raise AssertionError."""
r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
w = so3_log(want)
assert abs(norm(w) - 2.0943951) < 1e-7
assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
return True
test_image_based_visual_servoing.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/image-based-visual-servoing/. The authors are listed in prov/A4GWRN.jsonl.
import math
import random
from image_based_visual_servoing import features, ibvs_step, interaction_matrix, simulate
from rbm import eye, make_T, mul, norm, rot_x, rot_z, se3_exp, so3_exp, so3_log
SQUARE = [[-0.1, -0.1, 1.0], [0.1, -0.1, 1.0], [0.1, 0.1, 1.0], [-0.1, 0.1, 1.0]]
def pose_error(t):
return norm(so3_log([row[:3] for row in t[:3]])), norm([t[0][3], t[1][3], t[2][3]])
def test_interaction_matrix_matches_finite_differences():
rng = random.Random(7)
h = 1e-6
for _ in range(10):
t = make_T(so3_exp([rng.uniform(-0.3, 0.3) for _ in range(3)]), [rng.uniform(-0.2, 0.2) for _ in range(3)])
pts = [[rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(1.0, 2.0)] for _ in range(3)]
s, depths = features(t, pts)
lmat = interaction_matrix(s, depths)
for j in range(6):
d = [0.0] * 6
d[j] = h
sp = features(mul(t, se3_exp(d)), pts)[0]
sm = features(mul(t, se3_exp([-x for x in d])), pts)[0]
for i in range(len(s)):
assert abs((sp[i] - sm[i]) / (2 * h) - lmat[i][j]) < 1e-6
def test_converges_to_the_goal_pose_with_each_matrix():
s_star, z_star = features(eye(4), SQUARE)
t0 = make_T(mul(rot_z(0.6), rot_x(0.1)), [0.05, -0.04, -0.3])
for choice in ("current", "desired", "mean"):
out = simulate(SQUARE, t0, s_star, 1.0, 0.05, 200, choice, z_star)
errs = [o[2] for o in out]
assert all(b <= a * (1 + 1e-9) for a, b in zip(errs, errs[1:]))
ang, dist = pose_error(out[-1][0])
assert ang < 1e-4 and dist < 1e-4
def test_quarter_turn_about_the_optical_axis():
# With L at the current features the camera first moves back; with L at
# the desired features it first moves forward. Both end at the goal.
s_star, z_star = features(eye(4), SQUARE)
t0 = make_T(rot_z(math.pi / 2), [0.0, 0.0, 0.0])
s0, z0 = features(t0, SQUARE)
v = ibvs_step(s0, s_star, z0, 1.0)
assert max(abs(a - b) for a, b in zip(v, [0, 0, -1, 0, 0, -1])) < 1e-12
extremes = []
for choice in ("current", "desired"):
out = simulate(SQUARE, t0, s_star, 1.0, 0.02, 500, choice, z_star)
back = [-o[0][2][3] for o in out]
extremes.append((max(back), min(back)))
assert all(abs(o[0][0][3]) < 1e-12 and abs(o[0][1][3]) < 1e-12 for o in out)
assert max(pose_error(out[-1][0])) < 1e-3
assert extremes[0][0] > 0.4 and extremes[0][1] > -1e-12
assert extremes[1][1] < -0.3 and extremes[1][0] < 1e-12
def test_half_turn_sends_the_camera_back_without_rotation():
# At a rotation of pi, L^+ e is a pure backward translation, and the depth
# follows Z <- Z + lam dt Z (1 + Z), which grows without bound.
s_star, _ = features(eye(4), SQUARE)
t0 = make_T(rot_z(math.pi), [0.0, 0.0, 0.0])
out = simulate(SQUARE, t0, s_star, 1.0, 0.01, 60)
z = 1.0
for t, _, _ in out:
depths = features(t, SQUARE)[1]
assert abs(depths[0] - z) < 1e-12 * z
assert max(abs(t[i][j] - t0[i][j]) for i in range(3) for j in range(3)) < 1e-12
z += 0.01 * z * (1.0 + z)
assert features(out[-1][0], SQUARE)[1][0] > 8.0
History
Weiss, Sanderson and Neuman studied image-based control of robots in the 1980s. In 1992, Espiau, Chaumette and Rives wrote IBVS as the regulation of a task function with the interaction matrix, the form used today. Hutchinson, Hager and Corke wrote the 1996 tutorial that classified the methods into image-based and position-based. In 1998, Chaumette described the stability problems of both schemes, including the local minima of IBVS and the retreat for a rotation about the optical axis, and in 2006 Chaumette and Hutchinson wrote a two-part tutorial that is now the standard reference.
References
- Bernard Espiau, Francois Chaumette and Patrick Rives, A new approach to visual servoing in robotics, IEEE Transactions on Robotics and Automation 8(3), 1992, pages 313 to 326
- Seth Hutchinson, Gregory D. Hager and Peter I. Corke, A tutorial on visual servo control, IEEE Transactions on Robotics and Automation 12(5), 1996, pages 651 to 670
- Francois Chaumette and Seth Hutchinson, Visual servo control, Part I, Basic approaches, IEEE Robotics and Automation Magazine 13(4), 2006, pages 82 to 90
- Francois Chaumette, Potential problems of stability and convergence in image-based and position-based visual servoing, in The Confluence of Vision and Control, Lecture Notes in Control and Information Sciences 237, Springer, 1998, pages 66 to 78
- Mark W. Spong, Seth Hutchinson and M. Vidyasagar, Robot Modeling and Control, second edition, Wiley, 2020, Chapter 11 (vision-based control), Section 11.5 (image-based control laws)
- Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 34 (Visual Servoing, by Francois Chaumette, Seth Hutchinson and Peter Corke)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag A4GWRN Edit this page History Report an error Markdown