Algorithm Search⌘K

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
Properties
deterministicnot exactonline
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 e=s−s∗e = s - s^*. It computes the camera velocity V=−λL+eV = -\lambda L^+ e, where LL is the interaction matrix that maps camera velocity to feature velocity and L+L^+ 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 V=(ω,v)∈R6V = (\omega, v) \in \mathbb{R}^6, angular part first, in the camera frame. It sees k≥3k \ge 3 points of a fixed target, with normalized image coordinates s=(x1,y1,…,xk,yk)s = (x_1, y_1, \dots, x_k, y_k) and depths Zi>0Z_i > 0. The desired features s∗s^* are those seen at the goal pose. Find VV at each step so that e=s−s∗→0e = s - s^* \to 0, 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.

  1. IBVS-STEP(s, Z, s*, λ)
  2. 1e ← s - s*
  3. 2L ← 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]]
  4. 3L⁺ ← (Lᵀ L)⁻¹ Lᵀ
  5. 4V ← -λ L⁺ e
  6. 5return V

The robot applies VV 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 L∗L^* at the goal, with the goal depths, which is constant and needs no depth estimate during the motion, and the mean (L+L∗)/2(L + L^*)/2. The columns are ordered as (ω,v)(\omega, v) here; Chaumette and Hutchinson order them as (v,ω)(v, \omega). With exactly three points, LL 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 s∗=(±0.1,±0.1)s^* = (\pm 0.1, \pm 0.1). The camera starts at the goal position, but rotated by π/2\pi/2 about its optical axis. Each point now appears where its neighbor should be: the first point is seen at (−0.1,0.1)(-0.1, 0.1) but should be at (−0.1,−0.1)(-0.1, -0.1), so its error is (0,0.2)(0, 0.2). With Z=1Z = 1, line L2 gives its two rows as (−0.01,−1.01,0.1,−1,0,−0.1)(-0.01, -1.01, 0.1, -1, 0, -0.1) and (1.01,0.01,0.1,0,−1,0.1)(1.01, 0.01, 0.1, 0, -1, 0.1). With λ=1\lambda = 1, lines L3 and L4 give

V=(0,0,−1,0,0,−1),V = (0, 0, -1, 0, 0, -1),

a rotation about the optical axis and a translation backward along it. As a check, the two rows times VV give (0,−0.2)(0, -0.2), which is −e-e for this point.

Applying each twist for 10 ms gives:

time (s) ∥e∥\lVert e\rVert 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 t=0.69t = 0.69 s and then returns. With the constant matrix L∗L^* 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 e−λte^{-\lambda t}.

Correctness

Under the law, e˙=LV=−λLL+e\dot e = LV = -\lambda L L^+ e. The matrix LL+LL^+ is the orthogonal projection onto the range of LL, so ddt12∥e∥2=−λ∥LL+e∥2≤0\frac{d}{dt}\tfrac12\lVert e\rVert^2 = -\lambda\lVert LL^+ e\rVert^2 \le 0: the image error never grows. With three points the projection is the identity and ee decays exactly like e−λte^{-\lambda t}. With more points the error can stop at e≠0e \ne 0 with LTe=0L^T e = 0, a local minimum. Near the goal, the linearized loop in pose coordinates is ξ˙=−λξ\dot\xi = -\lambda\xi, so the goal is locally exponentially stable. For a rotation by θ\theta about the optical axis with the target plane parallel to the image, the first twist is ωz=−λsin⁡θ\omega_z = -\lambda\sin\theta and vz=−λZ(1−cos⁡θ)v_z = -\lambda Z(1 - \cos\theta). At θ=π\theta = \pi 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 V=(ω,v)V = (\omega, v), angular part first, expressed in the camera frame. A point fixed in the world has camera coordinates P=(X,Y,Z)P = (X, Y, Z) with Z>0Z > 0 and image coordinates x=X/Zx = X/Z, y=Y/Zy = Y/Z. The feature vector ss stacks the image coordinates of kk points, e=s−s∗e = s - s^*, and LL is the stacked interaction matrix. We assume that LL has full column rank 6 along the motion, so L+=(LTL)−1LTL^+ = (L^T L)^{-1}L^T, and that the depths in LL are exact.

Lemma 1 (interaction matrix of a point). x˙=xy ωx−(1+x2)ωy+y ωz−vx/Z+xvz/Z\dot x = xy\,\omega_x - (1 + x^2)\omega_y + y\,\omega_z - v_x/Z + x v_z/Z and y˙=(1+y2)ωx−xy ωy−x ωz−vy/Z+yvz/Z\dot y = (1 + y^2)\omega_x - xy\,\omega_y - x\,\omega_z - v_y/Z + y v_z/Z.

Proof. A point fixed in the world moves in the camera frame as P˙=−v−ω×P\dot P = -v - \omega \times P. So X˙=−vx−ωyZ+ωzY\dot X = -v_x - \omega_y Z + \omega_z Y, Y˙=−vy−ωzX+ωxZ\dot Y = -v_y - \omega_z X + \omega_x Z and Z˙=−vz−ωxY+ωyX\dot Z = -v_z - \omega_x Y + \omega_y X. Then x˙=X˙/Z−xZ˙/Z\dot x = \dot X/Z - x\dot Z/Z. Putting in the three derivatives and X=xZX = xZ, Y=yZY = yZ gives x˙=−vx/Z−ωy+yωz+xvz/Z+x(yωx−xωy)\dot x = -v_x/Z - \omega_y + y\omega_z + x v_z/Z + x(y\omega_x - x\omega_y), which is the first formula. The second follows in the same way from y˙=Y˙/Z−yZ˙/Z\dot y = \dot Y/Z - y\dot Z/Z. □\square

So s˙=LV\dot s = LV, and under the law V=−λL+eV = -\lambda L^+ e the error obeys e˙=−λLL+e\dot e = -\lambda L L^+ e.

Theorem 1 (the image error does not grow). Along the closed loop, ddt12∥e∥2=−λ∥LL+e∥2≤0\frac{d}{dt}\tfrac12\|e\|^2 = -\lambda\|L L^+ e\|^2 \le 0. It is zero exactly when LTe=0L^T e = 0.

Proof. P=LL+=L(LTL)−1LTP = L L^+ = L(L^T L)^{-1}L^T is symmetric and P2=PP^2 = P, so it is the orthogonal projection onto the range of LL. Then ddt12∥e∥2=eTe˙=−λeTPe=−λeTPTPe=−λ∥Pe∥2\frac{d}{dt}\tfrac12\|e\|^2 = e^T\dot e = -\lambda e^T P e = -\lambda e^T P^T P e = -\lambda\|Pe\|^2. The projection PePe is zero if and only if ee is orthogonal to the range of LL, that is LTe=0L^T e = 0. □\square

With three points, LL is square and P=IP = I, so e˙=−λe\dot e = -\lambda e and e(t)=e−λte(0)e(t) = e^{-\lambda t}e(0) while LL stays invertible. With four or more points, 2k>62k > 6, and the set LTe=0L^T e = 0 with e≠0e \ne 0 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 s(T)s(T) be the features at the camera pose TT, and let L0L_0, the interaction matrix at the goal, have rank 6. Write T=exp⁡([ξ])T = \exp([\xi]). Then the linearization of the closed loop at ξ=0\xi = 0 is ξ˙=−λξ\dot\xi = -\lambda\xi, so the goal is locally exponentially stable with rate λ\lambda.

Proof. Near the identity, ξ˙=V+O(∥ξ∥ ∥V∥)\dot\xi = V + O(\|\xi\|\,\|V\|), because the right Jacobian of the exponential map is I+O(∥ξ∥)I + O(\|\xi\|). By Lemma 1, s(exp⁡([ξ]))=s∗+L0ξ+O(∥ξ∥2)s(\exp([\xi])) = s^* + L_0\xi + O(\|\xi\|^2). The matrices LL and L+L^+ depend smoothly on ξ\xi near 0, so V=−λL+e=−λL0+L0ξ+O(∥ξ∥2)=−λξ+O(∥ξ∥2)V = -\lambda L^+ e = -\lambda L_0^+ L_0\xi + O(\|\xi\|^2) = -\lambda\xi + O(\|\xi\|^2), since L0+L0=IL_0^+ L_0 = I for full column rank. So ξ˙=−λξ+O(∥ξ∥2)\dot\xi = -\lambda\xi + O(\|\xi\|^2), and Lyapunov's indirect method gives local exponential stability. □\square

Proposition 3 (rotation about the optical axis). Let all points have the same depth ZZ in both poses, with the target plane parallel to the image plane, and let the camera be rotated by an angle θ∈(−π,π]\theta \in (-\pi, \pi] about its optical axis, so that every current feature is si=R(−θ)si∗s_i = R(-\theta)s_i^*, with R(⋅)R(\cdot) the plane rotation. With LL at the current features, the first twist is ωz=−λsin⁡θ\omega_z = -\lambda\sin\theta, vz=−λZ(1−cos⁡θ)v_z = -\lambda Z(1 - \cos\theta), and all other components are zero.

Proof. Write JJ for the rotation of the plane by π/2\pi/2. For one point, the ωz\omega_z column of Lemma 1 is (y,−x)=−Jsi(y, -x) = -Js_i and the vzv_z column is si/Zs_i/Z. Since si∗=R(θ)sis_i^* = R(\theta)s_i and R(θ)=cos⁡θ I+sin⁡θ JR(\theta) = \cos\theta\,I + \sin\theta\,J, we get ei=si−si∗=(1−cos⁡θ)si−sin⁡θ Jsie_i = s_i - s_i^* = (1 - \cos\theta)s_i - \sin\theta\,Js_i. The candidate twist gives LV=−ωzJsi+vzsi/Z=λsin⁡θ Jsi−λ(1−cos⁡θ)si=−λeiLV = -\omega_z Js_i + v_z s_i/Z = \lambda\sin\theta\,Js_i - \lambda(1 - \cos\theta)s_i = -\lambda e_i for every point. So −λe-\lambda e is in the range of LL, and since LL has full column rank, L+(−λe)L^+(-\lambda e) is the unique VV with LV=−λeLV = -\lambda e, which is the candidate. □\square

For θ≠0\theta \ne 0, vz<0v_z < 0, so the camera first moves backward along its optical axis. With LL at the desired features, the same computation with si∗s_i^* in place of sis_i gives vz=+λZ(1−cos⁡θ)v_z = +\lambda Z(1 - \cos\theta), 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 π\pi about its optical axis at depth Z0Z_0. Then the law is a pure backward translation for all time, and the depth is Z(t)=Z0eλt/(1+Z0−Z0eλt)Z(t) = Z_0 e^{\lambda t}/(1 + Z_0 - Z_0 e^{\lambda t}), which is infinite at t=ln⁡(1+1/Z0)/λt = \ln(1 + 1/Z_0)/\lambda.

Proof. While the rotation is π\pi and the camera has only moved along its optical axis, the current features are si=−si∗/Zs_i = -s_i^*/Z. Then ei=−(1+1/Z)si∗e_i = -(1 + 1/Z)s_i^*, and V=(0,0,0,0,0,−λZ(1+Z))V = (0, 0, 0, 0, 0, -\lambda Z(1 + Z)) gives LV=−λZ(1+Z) si/Z=λ(1+Z)si∗/Z=−λeiLV = -\lambda Z(1 + Z)\,s_i/Z = \lambda(1 + Z)s_i^*/Z = -\lambda e_i. By full column rank this is the twist of the law. It has ω=0\omega = 0 and moves the camera only along its optical axis, so the form si=−si∗/Zs_i = -s_i^*/Z stays valid, and Z˙=−vz=λZ(1+Z)\dot Z = -v_z = \lambda Z(1 + Z). Separating variables, ln⁡Z1+Z=λt+ln⁡Z01+Z0\ln\frac{Z}{1 + Z} = \lambda t + \ln\frac{Z_0}{1 + Z_0}, which solves to the formula. Its denominator vanishes at the stated time. ■\blacksquare

In this case the image error is e(t)=e−λte(0)e(t) = e^{-\lambda t}e(0) exactly, as Theorem 1 with Pe=ePe = e 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 kk points, line L2 builds a 2k×62k \times 6 matrix in O(k)O(k) time. Line L3 forms LTLL^T L in O(36⋅2k)O(36 \cdot 2k) operations and inverts a 6×66 \times 6 matrix in constant time, and line L4 is O(k)O(k). So one step takes O(k)O(k) time and O(k)O(k) 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, ∥e∥\lVert e\rVert 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 LL 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 LTe=0L^T e = 0 but e≠0e \ne 0. LL 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 L∗L^*. Compute LL 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 (L+L∗)/2(L + L^*)/2, 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 ZiZ_i online from the known camera motion, or use a constant guess such as Z∗Z^*.
  • 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 LL scale with 1/Zi1/Z_i. 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 LL.
  • Too few or degenerate features. Three points in general position give a square LL but several poses with the same image; four points avoid this but bring local minima. Collinear points make LL singular.
  • Gain and delay. The image is slow and delayed; a large λ\lambda 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.

image_based_visual_servoing.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. Francois Chaumette and Seth Hutchinson, Visual servo control, Part I, Basic approaches, IEEE Robotics and Automation Magazine 13(4), 2006, pages 82 to 90
  4. 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
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_step
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example