172 lines
9.1 KiB
Python
172 lines
9.1 KiB
Python
"""Physical, deterministic joint-calibration tests; no hardware or SciPy."""
|
|
import copy
|
|
import importlib.util
|
|
from pathlib import Path
|
|
import sys
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
|
from handeye_math import solve_handeye_matrix
|
|
|
|
|
|
def transform(rv, t):
|
|
out = np.eye(4)
|
|
out[:3, :3] = cv2.Rodrigues(np.asarray(rv, dtype=float))[0]
|
|
out[:3, 3] = t
|
|
return out
|
|
|
|
|
|
def dataset(eih=True, count=12, noise=0., partial=False, pnp_noise=0.):
|
|
rng = np.random.default_rng(4261)
|
|
x = transform([.13, -.09, .04], [.06, -.03, .12])
|
|
y = transform([-.07, .04, .09], [.08, .04, .95] if eih else [.02, -.03, .13])
|
|
obj = np.array([[a*.025, b*.025, 0.] for a in range(-3, 4) for b in range(-2, 3)])
|
|
robots, observations = [], []
|
|
for i in range(count):
|
|
c = transform(rng.uniform(-.45, .45, 3), rng.uniform(-.05, .05, 3)+[0., 0., .7])
|
|
g = y @ np.linalg.inv(c) @ np.linalg.inv(x) if eih else x @ c @ np.linalg.inv(y)
|
|
ids = np.sort(rng.choice(len(obj), 15+i % 15, replace=False)) if partial else np.arange(len(obj))
|
|
points = obj[ids]
|
|
k = np.array([[850.+i, 0., 640.], [0., 860.+i, 480.], [0., 0., 1.]])
|
|
d = np.array([-.13, .03, .001, -.002, .005])
|
|
image = cv2.projectPoints(points, cv2.Rodrigues(c[:3, :3])[0], c[:3, 3], k, d)[0].reshape(-1, 2)
|
|
image += rng.normal(0, noise, image.shape)
|
|
cpnp = c @ transform(rng.normal(0, pnp_noise, 3), rng.normal(0, pnp_noise*.2, 3))
|
|
robots.append(g)
|
|
observations.append(dict(T_camera_target=cpnp.ravel().tolist(), image_points=image.tolist(),
|
|
object_points=points.tolist(), corner_ids=ids.tolist(), K=k.ravel().tolist(), D=d.tolist(), width=1280, height=960))
|
|
initial = solve_handeye_matrix(robots, [np.array(o['T_camera_target']).reshape(4,4) for o in observations], eih, cv2.CALIB_HAND_EYE_PARK)
|
|
return x, y, robots, observations, initial
|
|
|
|
|
|
class RefinementTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.assertIsNotNone(importlib.util.find_spec('handeye_refinement'), 'Joint refinement module is missing')
|
|
from handeye_refinement import refine_joint
|
|
self.refine = refine_joint
|
|
|
|
def test_exact_both_transforms_and_mounting_modes(self):
|
|
for mode in (True, False):
|
|
x, y, robots, observations, initial = dataset(mode)
|
|
initial = initial @ transform([.015, -.01, .008], [.002, -.001, .003])
|
|
result = self.refine(robots, observations, initial, mode)
|
|
self.assertTrue(result['accepted'], result['quality_flags'])
|
|
np.testing.assert_allclose(np.array(result['matrix']).reshape(4,4), x, atol=2e-7)
|
|
np.testing.assert_allclose(np.array(result['fixed_matrix']).reshape(4,4), y, atol=2e-7)
|
|
self.assertLess(result['metrics']['validation_rms_px'], 1e-5)
|
|
self.assertEqual(result['metrics']['validation_sample_count'], 12)
|
|
|
|
def test_noisy_pnp_partial_charuco_distortion_improves_truth(self):
|
|
for mode in (True, False):
|
|
x, y, robots, observations, initial = dataset(mode, noise=.12, partial=True, pnp_noise=.012)
|
|
result = self.refine(robots, observations, initial, mode)
|
|
self.assertTrue(result['accepted'], result['quality_flags'])
|
|
self.assertLess(result['metrics']['final_rms_px'], result['metrics']['initial_rms_px'])
|
|
self.assertLess(np.linalg.norm(np.array(result['matrix']).reshape(4,4)-x), np.linalg.norm(initial-x)*.15)
|
|
self.assertLess(np.linalg.norm(np.array(result['fixed_matrix']).reshape(4,4)-y), .002)
|
|
|
|
def test_six_samples_leave_one_out(self):
|
|
_, _, robots, obs, initial = dataset(count=6)
|
|
result = self.refine(robots, obs, initial, True)
|
|
self.assertTrue(result['accepted'])
|
|
self.assertEqual(result['metrics']['validation_sample_count'], 6)
|
|
self.assertEqual(result['metrics']['validation_fold_count'], 6)
|
|
|
|
def test_huber_fit_retains_outliers_in_reported_rms(self):
|
|
x, _, robots, obs, initial = dataset(noise=.08, pnp_noise=.012)
|
|
for o in obs:
|
|
o['image_points'][0] = (np.asarray(o['image_points'][0])+[3., -2.]).tolist()
|
|
result = self.refine(robots, obs, initial, True)
|
|
self.assertTrue(result['accepted'], result['quality_flags'])
|
|
metrics = result['metrics']
|
|
self.assertLess(metrics['final_robust_cost'], metrics['initial_robust_cost'])
|
|
self.assertGreater(metrics['final_rms_px'], .5)
|
|
self.assertEqual(metrics['point_count'], 12*35)
|
|
self.assertLess(np.linalg.norm(np.asarray(result['matrix']).reshape(4,4)-x), np.linalg.norm(initial-x)*.2)
|
|
|
|
def test_malformed_and_unphysical_input(self):
|
|
_, _, robots, obs, initial = dataset()
|
|
mutations = [lambda o: o[0].update(corner_ids=[0]),
|
|
lambda o: o[0].update(**{key: o[0][key][:4] for key in ('object_points', 'image_points', 'corner_ids')}),
|
|
lambda o: o[0].update(image_points=[np.asarray(o[0]['image_points']).ravel().tolist()]),
|
|
lambda o: o[0].update(image_points=[[float('nan'), 1.]]*35),
|
|
lambda o: o[0].update(object_points=[[i*.01, 0., 0.] for i in range(35)]),
|
|
lambda o: o[0].update(K=[0.]*9), lambda o: o[0].update(width=0),
|
|
lambda o: o[0].update(D=[0., 1.]),
|
|
lambda o: o[0].update(T_camera_target=transform([0.,0.,0.], [0.,0.,-1.]).ravel().tolist())]
|
|
for mutation in mutations:
|
|
with self.subTest(mutation=mutation):
|
|
bad = copy.deepcopy(obs)
|
|
mutation(bad)
|
|
with self.assertRaises(ValueError):
|
|
self.refine(robots, bad, initial, True)
|
|
with self.assertRaises(ValueError):
|
|
self.refine(robots[:5], obs[:5], initial, True)
|
|
with self.assertRaises(ValueError):
|
|
self.refine(robots, obs, np.zeros((4,4)), True)
|
|
|
|
def test_degenerate_robot_motion_fails_closed(self):
|
|
_, _, robots, obs, initial = dataset()
|
|
with self.assertRaises(ValueError):
|
|
self.refine([robots[0]]*12, [obs[0]]*12, initial, True)
|
|
|
|
def test_inconsistent_observations_fail_quality_gate(self):
|
|
_, _, robots, obs, initial = dataset()
|
|
for i, o in enumerate(obs):
|
|
o['image_points'] = (np.asarray(o['image_points']) + [8.*(-1)**i, 4.*(-1)**(i//2)]).tolist()
|
|
result = self.refine(robots, obs, initial, True)
|
|
self.assertFalse(result['accepted'])
|
|
self.assertIn('high_validation_reprojection', result['quality_flags'])
|
|
|
|
def test_fold_failure_reports_actual_coverage(self):
|
|
_, _, robots, obs, initial = dataset(count=9)
|
|
# Fold zero holds out every exciting pose: its training set is singular.
|
|
for i in (1, 2, 4, 5, 7, 8):
|
|
robots[i], obs[i] = robots[1], copy.deepcopy(obs[1])
|
|
result = self.refine(robots, obs, initial, True)
|
|
self.assertFalse(result['accepted'])
|
|
self.assertIn('incomplete_cross_validation', result['quality_flags'])
|
|
self.assertEqual(result['metrics']['validation_sample_count'], 6)
|
|
self.assertFalse(result['validation_folds'][0]['valid'])
|
|
|
|
def test_validation_does_not_use_full_initial_or_heldout_pnp(self):
|
|
_, _, robots, obs, initial = dataset(noise=.1, pnp_noise=.003)
|
|
baseline = self.refine(robots, obs, initial, True)
|
|
changed = copy.deepcopy(obs)
|
|
for i in (0, 3, 6, 9):
|
|
c = np.asarray(changed[i]['T_camera_target']).reshape(4,4)
|
|
changed[i]['T_camera_target'] = (c @ transform([.02, -.01, .01], [.01, 0., .02])).ravel().tolist()
|
|
result = self.refine(robots, changed, initial @ transform([.01, .02, 0.], [.003, 0., 0.]), True)
|
|
self.assertEqual(baseline['validation_folds'][0], result['validation_folds'][0])
|
|
|
|
def test_numerical_nonconvergence_never_accepts(self):
|
|
_, _, robots, obs, initial = dataset()
|
|
with patch('handeye_refinement.MAX_ITERATIONS', 0):
|
|
result = self.refine(robots, obs, initial, True)
|
|
self.assertFalse(result['accepted'])
|
|
self.assertFalse(result['converged'])
|
|
self.assertIn('refinement_not_converged', result['quality_flags'])
|
|
|
|
def test_analytic_jacobian_agrees_with_central_difference(self):
|
|
import handeye_refinement as refinement
|
|
for mode in (True, False):
|
|
_, y, robots, obs, initial = dataset(mode, partial=True)
|
|
_, data, x = refinement._validated(robots, obs, initial, mode)
|
|
_, actual = refinement._evaluate(data, x, y, True)
|
|
numeric = np.empty_like(actual)
|
|
for j in range(12):
|
|
delta = np.zeros(12)
|
|
delta[j] = 1e-6*refinement.PARAMETER_SCALE[j]
|
|
plus, _ = refinement._evaluate(data, refinement._increment(x, delta[:6]), refinement._increment(y, delta[6:]))
|
|
minus, _ = refinement._evaluate(data, refinement._increment(x, -delta[:6]), refinement._increment(y, -delta[6:]))
|
|
numeric[:, j] = (plus-minus)/2e-6
|
|
np.testing.assert_allclose(actual, numeric, atol=2e-6, rtol=2e-5)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|