Algorithm Search⌘K

Algorithmcore

Position-based visual servoing

Also called PBVS.

Estimates the target pose from the image and controls the camera by the pose error in Cartesian space.

Time
O(1) per_step
Space
O(1) extra
Where
k = the number of image features used by the pose estimator; the bounds are for one control step after the pose estimate
Properties
deterministicnot exactonline
Origin
Seth Hutchinson, Gregory D. Hager, Peter I. Corke, 1996

Position-based visual servoing (PBVS) uses the camera as a pose sensor. At each step it estimates the pose of the target in the camera frame from the image, for example by perspective-n-point with a calibrated camera and a model of the target. From this estimate and the desired pose of the target in the camera frame, it computes the pose of the current camera in the desired camera frame, and it drives this pose error to zero with a Cartesian control law. With the error written as a translation tt and an axis-angle rotation θu\theta u, the law v=−λRTtv = -\lambda R^T t, ω=−λθu\omega = -\lambda\theta u moves the camera center on a straight line and turns it about a fixed axis. The quality of the result depends on the pose estimate: errors in the calibration or in the target model move the final pose.

In plain words

Instead of looking at how the target moves in the image, you first work out where the target is in 3D, relative to the camera. You know where it should be when you reach the goal. The difference tells you how far, and in which direction, the camera must move and turn. You move and turn the camera a fixed fraction of that difference per second, so you approach the goal smoothly along a straight line and turn about one fixed axis.

The image is used only to find the target pose. If that pose is wrong, you stop at the wrong place and never notice, because you trust the estimate.

The problem

A calibrated camera on a robot accepts a twist V=(ω,v)V = (\omega, v), angular part first, in the camera frame. A pose estimator returns T^ct\hat T_{ct}, the pose of the target in the current camera frame. The task gives Tc∗tT_{c^*t}, the pose of the target in the desired camera frame. Find VV at each step so that the camera reaches the desired pose, that is, E=Tc∗tTct−1→IE = T_{c^*t}T_{ct}^{-1} \to I.

The algorithm

Each control step takes the pose estimate and returns a twist.

  1. PBVS-STEP(T̂_ct, T_c*t, λ)
  2. 1E ← T_c*t T̂_ct⁻¹ ▷ the current camera in the desired camera frame
  3. 2(R, t) ← rotation and translation of E
  4. 3θu ← log(R)
  5. 4v ← -λ Rᵀ t
  6. 5ω ← -λ θu
  7. 6return V = (ω, v)

Line L3 is the SO(3) logarithm, which returns the axis-angle vector with θ∈[0,π]\theta \in [0, \pi]. Line L4 expresses the translation error in the current camera frame, because the twist is a camera-frame velocity. The pose estimate comes from outside the step, usually from PnP on the same image features that IBVS would use.

Example

The target is 1 m in front of the desired camera, so Tc∗tT_{c^*t} is a pure translation by (0,0,1)(0, 0, 1). The camera starts rotated by π/2\pi/2 about its optical axis and displaced by t=(0.2,0.1,−0.3)t = (0.2, 0.1, -0.3) m in the desired camera frame. Then RTt=(0.1,−0.2,−0.3)R^T t = (0.1, -0.2, -0.3), and with λ=1\lambda = 1 lines L4 and L5 give

V=(0,0,−π/2, −0.1,0.2,0.3).V = (0, 0, -\pi/2,\ -0.1, 0.2, 0.3).

Applying each twist for 10 ms gives:

time (s) camera center in the desired frame (m) angle left (rad)
0 (0.200, 0.100, -0.300) 1.571
0.5 (0.121, 0.061, -0.182) 0.950
1 (0.073, 0.037, -0.110) 0.575
2 (0.027, 0.014, -0.040) 0.211
3 (0.010, 0.005, -0.015) 0.077

The angle shrinks exactly by the factor 0.99100t0.99^{100 t}, close to e−te^{-t}, and the center shrinks by almost the same factor, so it stays within 0.5 mm of the line toward the goal. For the same quarter turn without the displacement, the camera only rotates, while IBVS first moves 0.42 m back.

Now let the estimator be biased: it reports the target turned by 0.02 rad about the camera yy axis and shifted by 1 cm. The loop converges as before, but to a camera pose 1 cm away from the goal and tilted by 0.02 rad about yy: the final error is the bias itself, moved to the desired camera frame. The image at the end does not match the reference image, and the controller cannot see this.

Correctness

The error pose obeys E˙=E[V]\dot E = E[V], so t˙=Rv=−λt\dot t = Rv = -\lambda t and R˙=R[ω]\dot R = R[\omega]. Hence t(τ)=e−λτt(0)t(\tau) = e^{-\lambda\tau}t(0), and the rotation keeps its axis while θ(τ)=e−λτθ(0)\theta(\tau) = e^{-\lambda\tau}\theta(0). With an exact estimate the goal is reached from every start with θ<π\theta < \pi, with no local minima. With sampling and a held twist, the angle is exactly (1−λh)kθ0(1 - \lambda h)^k\theta_0 and the translation leaves the straight line by O(h)O(h). If the estimator returns TctBT_{ct}B with a fixed error BB, the same argument applies to the estimated error, so the true target pose TctT_{ct} converges to Tc∗tB−1T_{c^*t}B^{-1}, not to Tc∗tT_{c^*t}. The proofs are in the proof file.

Proof: PBVS makes the pose error decay exponentially and stops at the estimated goalfull

Write E=Tc∗tTct−1E = T_{c^*t}T_{ct}^{-1} for the pose of the current camera frame in the desired camera frame, with rotation RR and translation tt, and θu=log⁡R\theta u = \log R with θ∈[0,π]\theta \in [0, \pi]. The camera moves with the body twist V=(ω,v)V = (\omega, v) in the camera frame, and the target is fixed.

Lemma 1 (error kinematics). E˙=E[V]\dot E = E[V], that is, R˙=R[ω]\dot R = R[\omega] and t˙=Rv\dot t = Rv.

Proof. Tct−1=Ttc=TtwTwcT_{ct}^{-1} = T_{tc} = T_{tw}T_{wc}, where TtwT_{tw} is constant because the target is fixed. So E=Tc∗tTtwTwcE = T_{c^*t}T_{tw}T_{wc} is a constant pose times TwcT_{wc}, and T˙wc=Twc[V]\dot T_{wc} = T_{wc}[V] for a body twist. Hence E˙=E[V]\dot E = E[V]. Writing out the blocks of E[V]E[V] gives the two formulas. □\square

Theorem 1 (exponential decay with an exact estimate). Let the estimate be exact and let θ(0)<π\theta(0) < \pi. Under v=−λRTtv = -\lambda R^T t and ω=−λθu\omega = -\lambda\theta u, the solution is t(τ)=e−λτt(0)t(\tau) = e^{-\lambda\tau}t(0), u(τ)=u(0)u(\tau) = u(0) and θ(τ)=e−λτθ(0)\theta(\tau) = e^{-\lambda\tau}\theta(0) for all τ≥0\tau \ge 0. In particular the camera center moves on the straight segment from t(0)t(0) to the goal.

Proof. By Lemma 1, t˙=Rv=−λRRTt=−λt\dot t = Rv = -\lambda RR^T t = -\lambda t, which gives the formula for tt. For the rotation, let ϕ(τ)=e−λτθ(0)\phi(\tau) = e^{-\lambda\tau}\theta(0) and R~(τ)=exp⁡(ϕ(τ)[u(0)])\tilde R(\tau) = \exp(\phi(\tau)[u(0)]). Since ϕ(τ)∈[0,π)\phi(\tau) \in [0, \pi), log⁡R~=ϕu(0)\log\tilde R = \phi u(0). Because R~\tilde R commutes with [u(0)][u(0)], R~˙=ϕ˙ R~[u(0)]=R~[−λϕu(0)]=R~[−λlog⁡R~]\dot{\tilde R} = \dot\phi\,\tilde R[u(0)] = \tilde R[-\lambda\phi u(0)] = \tilde R[-\lambda\log\tilde R]. So R~\tilde R solves R˙=R[−λlog⁡R]\dot R = R[-\lambda\log R] with the same initial value as RR. The right side is a smooth function of RR on the set θ<π\theta < \pi, which R~\tilde R never leaves, so the solution is unique there and R=R~R = \tilde R. □\square

If θ(0)=π\theta(0) = \pi, the logarithm chooses one of the two axes, and after the first instant θ<π\theta < \pi and the theorem applies. So with an exact estimate the goal is reached from every start, with no local minima, as long as the pose can be estimated along the way.

Proposition 2 (sampled rotation). If the twist is held constant for each sample time hh with λh<1\lambda h < 1, then θk=(1−λh)kθ0\theta_k = (1 - \lambda h)^k\theta_0 and uk=u0u_k = u_0 exactly, for θ0<π\theta_0 < \pi.

Proof. With ω\omega constant on the step, Rk+1=Rkexp⁡(−λhθk[uk])R_{k+1} = R_k\exp(-\lambda h\theta_k[u_k]). If Rk=exp⁡(θk[u0])R_k = \exp(\theta_k[u_0]), the two exponentials have the same axis and add: Rk+1=exp⁡((1−λh)θk[u0])R_{k+1} = \exp((1 - \lambda h)\theta_k[u_0]), and (1−λh)θk∈[0,π)(1 - \lambda h)\theta_k \in [0, \pi), so the logarithm returns this angle and axis. Induction on kk gives the claim. □\square

The translation of the sampled loop is not exactly geometric, because vv is held in the rotating camera frame during the step; its distance from the straight segment is O(h)O(h).

Theorem 3 (biased estimate). Let the estimator return TctBT_{ct}B for a fixed pose BB instead of TctT_{ct}, and let the estimated rotation error start below π\pi. Then the true pose of the target in the camera frame tends to Tc∗tB−1T_{c^*t}B^{-1}, and the true error pose tends to Tc∗tBTc∗t−1T_{c^*t}BT_{c^*t}^{-1}, which is the identity only if B=IB = I.

Proof. The law uses E^=Tc∗t(TctB)−1=Tc∗tB−1TtwTwc\hat E = T_{c^*t}(T_{ct}B)^{-1} = T_{c^*t}B^{-1}T_{tw}T_{wc}. This is again a constant pose times TwcT_{wc}, so Lemma 1 holds for E^\hat E, and the law is the law of Theorem 1 written for E^\hat E. So E^→I\hat E \to I exponentially, which means TctB→Tc∗tT_{ct}B \to T_{c^*t}, that is Tct→Tc∗tB−1T_{ct} \to T_{c^*t}B^{-1}. The true error is E=Tc∗tTct−1→Tc∗tBTc∗t−1E = T_{c^*t}T_{ct}^{-1} \to T_{c^*t}BT_{c^*t}^{-1}. ■\blacksquare

The theorems say nothing about the image: the target can leave the field of view on the way, and then the pose estimate, which the proofs assume, is lost.

Complexity

In the real-RAM model, one step of lines L1 to L6 is a fixed number of 4×44 \times 4 products, one inverse and one logarithm: O(1)O(1) time and memory. The pose estimate dominates the cost: PnP on kk points costs O(k)O(k) for a linear method, times the number of iterations for an iterative refinement.

Properties

  • Straight camera path. With an exact estimate, the camera center moves on a straight line and the rotation keeps a fixed axis, so the 3D motion is the shortest and most predictable one.
  • Global convergence in pose. No local minima and no singularities in the law itself, unlike IBVS. A half turn about the optical axis is a pure rotation.
  • Needs a model and a calibration. The pose estimate needs the intrinsic parameters, a 3D model of the target and, for an arm, the hand-eye transform. Errors in any of these move the final pose.
  • Image not controlled. The features follow whatever paths the 3D motion gives them, and they can leave the field of view.
  • Noise sensitivity. Pose estimates from a small or distant target are noisy, especially in depth and in rotations about axes in the image plane, and the noise goes straight into the control.

Variants and improvements

  • Other error choices. Use the pose of the target in the camera frame as the feature. Then the origin of the target frame moves on a straight line in the image, which helps to keep it in view, but the camera path is no longer straight.
  • Pose from a homography. For a planar target, a homography between the current and the reference image gives the rotation and the scaled translation without a full 3D model.
  • 2.5D visual servoing. Control the rotation from a partial pose estimate and the translation from image coordinates and a depth ratio, which keeps one point in view and needs no 3D model.
  • Filtering. Run a Kalman filter on the pose estimate to reduce noise and to bridge frames where the estimator fails.
  • Switching with IBVS. Use PBVS far from the goal and IBVS near it, or switch when features approach the image border.

When to use it

Use it when a calibrated camera and a model of the target are available, when the motion is large, and when the camera path in space matters, for example to avoid obstacles or the workspace limits. For final precision with an uncertain calibration, finish with IBVS, which stops where the image equals the reference image.

Pitfalls

  • Biased pose estimates. A small error in the calibration or the model gives a fixed error in the final pose, which no gain removes.
  • Losing the target. If the target leaves the image, the estimator fails and the loop has no input. Watch the projected features and limit the rotation.
  • Rotation near pi. The logarithm is not unique at θ=π\theta = \pi and changes axis there; noise can make the axis jump between two choices.
  • Frame of the translation. The translation error is in the desired frame; using it without RTR^T as a camera-frame velocity gives a curved path or divergence for large rotations.
  • Depth noise. Monocular pose estimates are weakest along the optical axis; do not use a high gain on vzv_z with a small target.

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.

position_based_visual_servoing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-visual-servoing/. The authors are listed in prov/CP9B6Z.jsonl.

"""Position-based visual servoing (PBVS).

The input is an estimate of the target pose T_ct in the current camera
frame (from a pose estimator such as PnP) and the target pose T_c*t in
the desired camera frame. The error is the pose of the current camera in
the desired camera frame, T_c*c = T_c*t T_ct^-1 = (R, t), written as
(t, theta u) with theta u = log(R). The law

    v = -lambda R^T t,    omega = -lambda theta u

makes t and theta u decay like exp(-lambda time), so the camera center
moves on a straight line to its goal. The twist V = (omega, v) is in the
camera frame, angular part first, and the camera pose moves by
T_wc exp([V] dt).

Matrices are lists of rows and vectors are lists. Only the standard library.
"""

from rbm import T_inv, matvec, mul, so3_log, se3_exp, transpose


def pbvs_step(t_ct, t_cstar_t, lam):
    """Return the camera twist (omega, v) of PBVS for the estimate t_ct."""
    t_err = mul(t_cstar_t, T_inv(t_ct))  # @line L1
    r = [row[:3] for row in t_err[:3]]  # @line L2
    p = [t_err[0][3], t_err[1][3], t_err[2][3]]
    theta_u = so3_log(r)  # @line L3
    v = [-lam * x for x in matvec(transpose(r), p)]  # @line L4
    w = [-lam * x for x in theta_u]  # @line L5
    return w + v  # @line L6


def simulate(t_wc, t_wt, t_cstar_t, lam, dt, steps, estimate=None):
    """Run PBVS; the twist is held for dt.

    estimate(t_ct) returns the pose estimate from the true pose; the default
    is exact. Return the list of camera poses t_wc for the steps 0 to steps.
    """
    out = [t_wc]
    for _ in range(steps):
        t_ct = mul(T_inv(t_wc), t_wt)
        est = estimate(t_ct) if estimate else t_ct
        v = pbvs_step(est, t_cstar_t, lam)
        t_wc = mul(t_wc, se3_exp([dt * c for c in v]))
        out.append(t_wc)
    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_position_based_visual_servoing.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-visual-servoing/. The authors are listed in prov/CP9B6Z.jsonl.

import math
import random

from position_based_visual_servoing import pbvs_step, simulate
from rbm import T_inv, eye, make_T, mul, norm, rot_z, so3_exp, so3_log

GOAL = make_T(eye(3), [0.0, 0.0, 1.0])  # target 1 m ahead of the desired camera


def rand_pose(rng, ang, dist):
    return make_T(so3_exp([rng.uniform(-ang, ang) for _ in range(3)]), [rng.uniform(-dist, dist) for _ in range(3)])


def error_pose(t_wc, t_wt):
    # The current camera in the desired camera frame: T_c*t T_ct^-1.
    return mul(GOAL, mul(T_inv(t_wt), t_wc))


def parts(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def test_first_twist_of_the_example():
    t0 = make_T(rot_z(math.pi / 2), [0.2, 0.1, -0.3])
    v = pbvs_step(mul(T_inv(t0), GOAL), GOAL, 1.0)
    want = [0.0, 0.0, -math.pi / 2, -0.1, 0.2, 0.3]
    assert max(abs(a - b) for a, b in zip(v, want)) < 1e-12


def test_rotation_decays_geometrically_about_a_fixed_axis():
    rng = random.Random(3)
    t_wt = rand_pose(rng, 1.0, 1.0)
    t_wc = mul(t_wt, mul(T_inv(GOAL), rand_pose(rng, 1.0, 0.3)))
    out = simulate(t_wc, t_wt, GOAL, 2.0, 0.01, 150)
    w0 = so3_log(parts(error_pose(out[0], t_wt))[0])
    for k, t in enumerate(out):
        w = so3_log(parts(error_pose(t, t_wt))[0])
        f = (1.0 - 2.0 * 0.01) ** k
        assert max(abs(a - f * b) for a, b in zip(w, w0)) < 1e-12


def test_camera_center_moves_on_a_straight_line():
    rng = random.Random(5)
    t_wt = rand_pose(rng, 1.0, 1.0)
    t_wc = mul(t_wt, mul(T_inv(GOAL), rand_pose(rng, 1.2, 0.4)))
    dt = 0.005
    out = simulate(t_wc, t_wt, GOAL, 1.0, dt, 600)
    p0 = parts(error_pose(out[0], t_wt))[1]
    for k, t in enumerate(out):
        p = parts(error_pose(t, t_wt))[1]
        assert norm([a - math.exp(-k * dt) * b for a, b in zip(p, p0)]) < 5e-3 * norm(p0)


def test_half_turn_about_the_optical_axis_is_a_pure_rotation():
    t0 = make_T(rot_z(math.pi), [0.0, 0.0, 0.0])
    out = simulate(t0, GOAL, GOAL, 1.0, 0.02, 400)
    for t in out:
        assert norm(parts(t)[1]) < 1e-12
    assert norm(so3_log(parts(out[-1])[0])) < 1e-3


def test_biased_pose_estimate_gives_a_wrong_final_pose():
    # The loop drives the estimate to the goal, so the true pose ends at
    # T_c*t B^-1 when the estimator returns T_ct B.
    bias = make_T(so3_exp([0.0, 0.02, 0.0]), [0.01, 0.0, 0.0])
    t0 = make_T(rot_z(math.pi / 2), [0.2, 0.1, -0.3])
    out = simulate(t0, GOAL, GOAL, 1.0, 0.02, 600, lambda t_ct: mul(t_ct, bias))
    want = mul(GOAL, mul(bias, T_inv(GOAL)))
    assert max(abs(out[-1][i][j] - want[i][j]) for i in range(3) for j in range(4)) < 1e-5
    assert norm(parts(out[-1])[1]) > 9e-3

History

Weiss and Sanderson used the terms position-based and image-based for the two ways to close a visual loop in the 1980s. The 1996 tutorial of Hutchinson, Hager and Corke presented PBVS and IBVS side by side. In 1998, Chaumette compared their stability problems: PBVS has no local minima in the law but depends on the pose estimate and does not control the image. In 1999, Malis, Chaumette and Boudet proposed 2.5D visual servoing, which combines both. The 2006 tutorial of Chaumette and Hutchinson gives the law with the error (t,θu)(t, \theta u) used here.

References

  1. 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
  2. Francois Chaumette and Seth Hutchinson, Visual servo control, Part I, Basic approaches, IEEE Robotics and Automation Magazine 13(4), 2006, pages 82 to 90
  3. 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
  4. Mark W. Spong, Seth Hutchinson and M. Vidyasagar, Robot Modeling and Control, second edition, Wiley, 2020, Chapter 11 (vision-based control)
  5. 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