CmvrControlStation/scripts/handeye_refinement.py

325 lines
16 KiB
Python

"""Joint robot-world/hand-eye pixel refinement (new extension, not a phone port).
Related formulation: Tabb and Ahmad Yousef (2017), 'Solving the robot-world,
hand-eye(s) calibration problem with iterative methods', reprojection class:
https://doi.org/10.1007/s00138-017-0841-7 ; author manuscript with erratum:
https://arxiv.org/abs/1907.12425 . This is an independent NumPy/OpenCV LM
implementation, with fixed intrinsics, distortion and robot poses.
Column-vector T_parent_child matrices use metres. X is flange<-camera for
eye-in-hand, base<-camera otherwise. Y is base<-target / flange<-target.
Predicted camera<-target is inv(X) inv(G) Y / inv(X) G Y, respectively.
All RMS values are sqrt(mean(||pixel residual||^2)), including outliers.
Acceptance is a pixel consistency gate, never a hardware/mm accuracy claim.
"""
from __future__ import annotations
import math
from typing import Any
import cv2
import numpy as np
from handeye_math import solve_handeye_matrix
HUBER_PX = 1.5
MAX_ITERATIONS = 80
MAX_CONDITION = 1e6
MAX_POINTS_PER_FRAME = 10000
MAX_TOTAL_POINTS = 100000
PARAMETER_SCALE = np.tile([1., 1., 1., .2, .2, .2], 2)
def _array(value, shape, name):
try:
result = np.asarray(value, dtype=np.float64)
except (TypeError, ValueError) as exc:
raise ValueError(f'{name}: expected finite numeric array') from exc
if result.size != math.prod(shape) or not np.all(np.isfinite(result)):
raise ValueError(f'{name}: expected {math.prod(shape)} finite numbers')
return result.reshape(shape)
def _matrix(value, name):
matrix = _array(value, (4, 4), name)
r = matrix[:3, :3]
if (not np.allclose(matrix[3], [0, 0, 0, 1], atol=1e-8, rtol=0)
or not np.allclose(r.T @ r, np.eye(3), atol=1e-5, rtol=0)
or abs(np.linalg.det(r)-1.) > 1e-5):
raise ValueError(f'{name}: expected a proper SE(3) transform')
return matrix.copy()
def _inverse(t):
result = np.eye(4)
result[:3, :3] = t[:3, :3].T
result[:3, 3] = -result[:3, :3] @ t[:3, 3]
return result
def _skew(points):
p = np.asarray(points).reshape(-1, 3)
result = np.zeros((len(p), 3, 3))
result[:, 0, 1], result[:, 0, 2] = -p[:, 2], p[:, 1]
result[:, 1, 0], result[:, 1, 2] = p[:, 2], -p[:, 0]
result[:, 2, 0], result[:, 2, 1] = -p[:, 1], p[:, 0]
return result
def _increment(t, delta):
"""Right multiplication by the SE(3) exponential; twist = [omega, v]."""
omega, velocity = delta[:3], delta[3:]
theta = float(np.linalg.norm(omega))
w = _skew(omega)[0]
if theta < 1e-6:
a, b = .5-theta**2/24., 1./6.-theta**2/120.
else:
a, b = (1.-math.cos(theta))/theta**2, (theta-math.sin(theta))/theta**3
exp = np.eye(4)
exp[:3, :3] = cv2.Rodrigues(omega)[0]
exp[:3, 3] = (np.eye(3)+a*w+b*w@w) @ velocity
return t @ exp
def _validated(robot_poses, observations, initial_matrix, eye_in_hand):
if not isinstance(eye_in_hand, (bool, np.bool_)):
raise ValueError('eye_in_hand must be boolean')
if not isinstance(observations, (list, tuple)) or not 6 <= len(observations) <= 100:
raise ValueError('Joint refinement requires 6..100 observations')
if not isinstance(robot_poses, (list, tuple, np.ndarray)) or len(robot_poses) != len(observations):
raise ValueError('Robot poses and observations must be paired')
x = _matrix(initial_matrix, 'initial_matrix')
robots, data, total = [], [], 0
id_coordinates = {}
for i, (pose, obs) in enumerate(zip(robot_poses, observations)):
try:
g = _matrix(pose, f'robot[{i}]')
c = _matrix(obs['T_camera_target'], f'observation[{i}].T_camera_target')
count = len(obs['object_points'])
if not 6 <= count <= MAX_POINTS_PER_FRAME:
raise ValueError('Each frame requires 6..10000 matched corners')
total += count
if total > MAX_TOTAL_POINTS:
raise ValueError('Total corner count exceeds 100000')
obj = _array(obs['object_points'], (count, 3), 'object_points')
img = _array(obs['image_points'], (count, 2), 'image_points')
ids = _array(obs['corner_ids'], (count,), 'corner_ids')
if (np.shape(obs['object_points']) != (count, 3) or np.shape(obs['image_points']) != (count, 2)
or np.shape(obs['corner_ids']) != (count,)):
raise ValueError('Expected matched N x 3 object points, N x 2 image points and N corner IDs')
if np.any(ids < 0) or np.any(ids > 2147483647) or np.any(ids != np.floor(ids)) or len(np.unique(ids)) != count:
raise ValueError('corner_ids must be unique nonnegative integers')
for corner_id, point in zip(ids, obj):
previous = id_coordinates.setdefault(int(corner_id), point)
if not np.allclose(previous, point, atol=1e-9, rtol=0):
raise ValueError('A corner ID must refer to the same object point in every frame')
centered = obj - obj.mean(axis=0)
singular = np.linalg.svd(centered, compute_uv=False)
if singular[1] <= max(1e-9, singular[0]*1e-6) or singular[2] > max(1e-9, singular[0]*1e-6):
raise ValueError('Object points must be planar and noncollinear')
if len(np.unique(obj, axis=0)) != count:
raise ValueError('Duplicate object points')
k = _array(obs['K'], (3, 3), 'K')
if k[0,0] <= 0 or k[1,1] <= 0 or not np.allclose(k[2], [0,0,1], atol=1e-10, rtol=0) or abs(k[0,1])+abs(k[1,0]) > 1e-10:
raise ValueError('K must have positive focal lengths and standard zero-skew form')
d = np.asarray(obs['D'], dtype=np.float64).reshape(-1)
if len(d) not in (0,4,5,8,12,14) or not np.all(np.isfinite(d)):
raise ValueError('Invalid distortion coefficients')
width, height = obs['width'], obs['height']
if (isinstance(width, bool) or isinstance(height, bool) or int(width) != width or int(height) != height
or min(width, height) < 2 or max(width, height) > 8192 or width*height > 32000000):
raise ValueError('Invalid image dimensions')
if np.any(img < 0) or np.any(img[:,0] >= width) or np.any(img[:,1] >= height):
raise ValueError('Image corners must be inside the calibrated image')
depths = (obj @ c[:3,:3].T + c[:3,3])[:,2]
if np.min(depths) <= 1e-8:
raise ValueError('All PnP corners must have positive depth')
robots.append(g)
data.append(dict(c=c, obj=obj, skew=_skew(obj), img=img, k=k, d=d,
motion=_inverse(g) if eye_in_hand else g))
except (KeyError, TypeError, OverflowError) as exc:
raise ValueError(f'Invalid observation {i}: {exc}') from exc
return robots, data, x
def _initial_fixed(data, x):
poses = [_inverse(o['motion']) @ x @ o['c'] for o in data]
u, _, vt = np.linalg.svd(np.sum([p[:3,:3] for p in poses], axis=0))
y = np.eye(4)
y[:3,:3] = u @ np.diag([1., 1., np.linalg.det(u@vt)]) @ vt
y[:3,3] = np.median([p[:3,3] for p in poses], axis=0)
return y
def _evaluate(data, x, y, jacobian=False):
residuals, blocks = [], []
xi = _inverse(x)
for obs in data:
prediction = xi @ obs['motion'] @ y
pc = obs['obj'] @ prediction[:3,:3].T + prediction[:3,3]
if not np.all(np.isfinite(pc)) or np.min(pc[:,2]) <= 1e-8:
raise ValueError('Predicted corners violate positive depth')
projected, camera_j = cv2.projectPoints(pc, np.zeros(3), np.zeros(3), obs['k'], obs['d'])
residuals.append((projected.reshape(-1,2)-obs['img']).ravel())
if jacobian:
dp = camera_j[:,3:6].reshape(-1,2,3)
geometric = np.concatenate((_skew(pc), np.broadcast_to(-np.eye(3), (len(pc),3,3)),
-prediction[:3,:3] @ obs['skew'], np.broadcast_to(prediction[:3,:3], (len(pc),3,3))), axis=2)
blocks.append((dp @ geometric).reshape(-1,12)*PARAMETER_SCALE)
residual = np.concatenate(residuals)
if not np.all(np.isfinite(residual)):
raise ValueError('Nonfinite reprojection')
return residual, np.vstack(blocks) if jacobian else None
def _cost_weights(residual):
norms = np.linalg.norm(residual.reshape(-1,2), axis=1)
cost = np.sum(np.where(norms <= HUBER_PX, .5*norms**2, HUBER_PX*(norms-.5*HUBER_PX)))
weights = np.repeat(np.minimum(1., HUBER_PX/np.maximum(norms, 1e-15)), 2)
return float(cost), weights
def _condition(jacobian, weights):
weighted = jacobian*np.sqrt(weights[:,None])
if not np.all(np.isfinite(weighted)):
raise ValueError('Nonfinite joint Jacobian')
singular = np.linalg.svd(weighted, compute_uv=False)
if singular[-1] <= singular[0]/MAX_CONDITION or singular[0] <= 1e-12:
raise ValueError('Joint Jacobian is rank deficient or poorly conditioned; increase robot pose diversity')
return weighted, float(singular[0]/singular[-1])
def _fit(data, x, y):
x, y = x.copy(), y.copy()
damping, converged, iterations = 1e-3, False, 0
initial_residual, _ = _evaluate(data, x, y)
initial_cost, _ = _cost_weights(initial_residual)
for iteration in range(MAX_ITERATIONS):
iterations = iteration+1
residual, j = _evaluate(data, x, y, True)
cost, weights = _cost_weights(residual)
jw, condition = _condition(j, weights)
h = jw.T @ jw
gradient = j.T @ (weights*residual)
diagonal = np.maximum(np.diag(h), 1e-12)
if np.max(np.abs(gradient)/np.sqrt(diagonal)) < 1e-7:
converged = True
break
accepted_step = False
for _ in range(16):
step = np.linalg.solve(h+damping*np.diag(diagonal), -gradient)
# Bound trial motion to a local basin; translation scale is 0.2m.
length = max(np.linalg.norm(step[:3]), np.linalg.norm(step[6:9]),
np.linalg.norm(step[3:6]), np.linalg.norm(step[9:12]))
if length > .3:
step *= .3/length
physical = step*PARAMETER_SCALE
trial_x = _increment(x, physical[:6])
trial_y = _increment(y, physical[6:])
try:
trial_residual, _ = _evaluate(data, trial_x, trial_y)
trial_cost, _ = _cost_weights(trial_residual)
except (ValueError, cv2.error):
trial_cost = math.inf
if trial_cost < cost:
x, y = trial_x, trial_y
accepted_step = True
damping = max(damping/3., 1e-12)
# Small progress alone is insufficient while heavily damped.
if (np.linalg.norm(step) < 1e-9 or cost-trial_cost < 1e-10*max(1., cost)) and damping < 1e-3:
converged = True
break
damping *= 10.
if damping > 1e14:
break
if converged or not accepted_step:
break
residual, j = _evaluate(data, x, y, True)
cost, weights = _cost_weights(residual)
_, condition = _condition(j, weights)
return dict(x=x, y=y, residual=residual, initial_residual=initial_residual,
initial_cost=initial_cost, cost=cost, condition=condition,
converged=converged, iterations=iterations)
def _rms(residual):
return float(np.sqrt(np.mean(np.sum(residual.reshape(-1,2)**2, axis=1))))
def refine_joint(robot_poses, observations, initial_matrix, eye_in_hand) -> dict[str, Any]:
"""Fit both transforms; reject quality failures without a successful fallback.
Invalid/degenerate input raises ValueError. Numerical nonconvergence and
cross-validation failures return accepted=False and explicit quality_flags.
Validation fits see only their training poses, PnP estimates and corners;
neither the supplied initial matrix nor the full-fit matrices are reused.
The robust loss must not increase (relative tolerance 1e-9); all-point RMS
may rise by at most max(0.01px, 1% of initial RMS), and must be <=1.5px.
Held-out all-point RMS must be <=3px with every frame validated exactly once.
"""
robots, data, x0 = _validated(robot_poses, observations, initial_matrix, eye_in_hand)
y0 = _initial_fixed(data, x0)
full = _fit(data, x0, y0)
flags = []
if not full['converged']:
flags.append('refinement_not_converged')
initial_rms, final_rms = _rms(full['initial_residual']), _rms(full['residual'])
if full['cost'] > full['initial_cost']+1e-9*max(1., full['initial_cost']):
flags.append('robust_objective_not_improved')
if final_rms > initial_rms+max(.01, .01*initial_rms):
flags.append('all_point_rms_increased')
if final_rms > 1.5:
flags.append('high_refinement_reprojection')
n = len(data)
folds = [list(range(i, n, 3)) for i in range(3)] if n >= 9 else [[i] for i in range(n)]
heldout, fold_reports, validation_residuals = {}, [], []
for fold_id, test in enumerate(folds):
test_set = set(test)
train = [i for i in range(n) if i not in test_set]
report = dict(fold=fold_id, train_indices=train, held_out_indices=test, valid=False)
try:
train_data = [data[i] for i in train]
train_x = _matrix(solve_handeye_matrix([robots[i] for i in train], [data[i]['c'] for i in train],
eye_in_hand, cv2.CALIB_HAND_EYE_PARK), 'validation initialization')
fit = _fit(train_data, train_x, _initial_fixed(train_data, train_x))
if not fit['converged']:
raise ValueError('Validation fit did not converge')
fold_residuals = []
for i in test:
residual, _ = _evaluate([data[i]], fit['x'], fit['y'])
fold_residuals.append((i, residual))
for i, residual in fold_residuals:
heldout[i] = _rms(residual)
validation_residuals.append(residual)
report.update(valid=True, rms_px=_rms(np.concatenate([r for _, r in fold_residuals])),
iterations=fit['iterations'], jacobian_condition=fit['condition'])
except (ValueError, cv2.error, np.linalg.LinAlgError) as exc:
report['error'] = str(exc)
fold_reports.append(report)
validation_rms = _rms(np.concatenate(validation_residuals)) if validation_residuals else None
if len(heldout) != n:
flags.append('incomplete_cross_validation')
if validation_rms is not None and validation_rms > 3.:
flags.append('high_validation_reprojection')
details, offset = [], 0
for i, obs in enumerate(data):
end = offset+2*len(obs['obj'])
details.append(dict(input_index=i, used=True, corner_count=len(obs['obj']),
initial_rms_px=_rms(full['initial_residual'][offset:end]),
final_rms_px=_rms(full['residual'][offset:end]), validation_rms_px=heldout.get(i),
validation_used=i in heldout))
offset = end
metrics = dict(initial_rms_px=initial_rms, final_rms_px=final_rms, validation_rms_px=validation_rms,
validation_sample_count=len(heldout), validation_coverage=len(heldout)/n,
validation_fold_count=len(folds), validation_point_count=sum(len(data[i]['obj']) for i in heldout),
iterations=full['iterations'], jacobian_condition=full['condition'],
initial_robust_cost=full['initial_cost'], final_robust_cost=full['cost'], huber_delta_px=HUBER_PX,
final_rms_limit_px=1.5, validation_rms_limit_px=3., max_jacobian_condition=MAX_CONDITION,
samples_total=n, samples_used=n, point_count=offset//2, accepted=not flags)
return dict(matrix=full['x'].ravel().tolist(), fixed_matrix=full['y'].ravel().tolist(),
initial_matrix=x0.ravel().tolist(), initial_fixed_matrix=y0.ravel().tolist(),
matrix_name='T_flange_camera' if eye_in_hand else 'T_base_camera',
fixed_matrix_name='T_base_target' if eye_in_hand else 'T_flange_target',
method='joint_reprojection_lm', converged=full['converged'], accepted=not flags,
metrics=metrics, quality_flags=flags, sample_diagnostics=details, validation_folds=fold_reports)