CmvrControlStation/scripts/handeye_math.py

459 lines
20 KiB
Python

"""Numerical hand-eye algorithms migrated from phone/scripts/handeye_calibration_gui.py.
Provenance: rotation angle 132-134, pose conversion 167-171, planar/IPPE
and ChArUco 174-266, AX=XB, robust MAD, and cross validation 269-592
(source snapshot 2026-09-30). Functions retain the upstream frame convention:
T_parent_child maps child coordinates into parent coordinates, metres.
No runtime dependency on the original GUI or phone project.
"""
from __future__ import annotations
import math
from typing import Any
import cv2
import numpy as np
AUTO_SOLVER_LABEL = "auto"
HAND_EYE_SOLVER_METHODS = {
"TsaiLenz1989": cv2.CALIB_HAND_EYE_TSAI,
"ParkBryan1994": cv2.CALIB_HAND_EYE_PARK,
"HoraudDornaika1995": cv2.CALIB_HAND_EYE_HORAUD,
"AndreffHoraudEspiau1999": cv2.CALIB_HAND_EYE_ANDREFF,
"Daniilidis1999": cv2.CALIB_HAND_EYE_DANIILIDIS,
}
HAND_EYE_CHARACTERISTIC_LENGTH_M = .20
HAND_EYE_OUTLIER_TRANSLATION_FLOOR_M = .002
HAND_EYE_OUTLIER_ROTATION_FLOOR_RAD = math.radians(.35)
# Upstream handeye_calibration_gui.py:132-134
def rotation_angle_degrees(R: np.ndarray) -> float:
trace = float(np.clip((np.trace(np.asarray(R, dtype=float)) - 1.0) / 2.0, -1.0, 1.0))
return math.degrees(math.acos(trace))
# Upstream handeye_calibration_gui.py:167-171
def rvec_tvec_to_matrix(rvec: np.ndarray, tvec: np.ndarray) -> np.ndarray:
out = np.eye(4, dtype=np.float64)
out[:3, :3] = cv2.Rodrigues(np.asarray(rvec, dtype=np.float64).reshape(3, 1))[0]
out[:3, 3] = np.asarray(tvec, dtype=np.float64).reshape(3)
return out
# Upstream handeye_calibration_gui.py:174-247
def estimate_planar_pose(
object_points: np.ndarray,
image_points: np.ndarray,
camera_matrix: np.ndarray,
dist_coeffs: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Estimate a planar target pose with IPPE candidates and LM refinement.
IPPE explicitly handles the two-solution ambiguity of a planar target. The
physically valid solution with the smallest reprojection error is refined
by Levenberg-Marquardt. ITERATIVE remains as a compatibility fallback.
"""
obj = np.asarray(object_points, dtype=np.float64).reshape(-1, 3)
img = np.asarray(image_points, dtype=np.float64).reshape(-1, 2)
if len(obj) < 4 or len(obj) != len(img):
raise ValueError("平面目标至少需要 4 个有效的二维-三维对应点")
candidates: list[tuple[np.ndarray, np.ndarray]] = []
if hasattr(cv2, "solvePnPGeneric") and hasattr(cv2, "SOLVEPNP_IPPE"):
try:
result = cv2.solvePnPGeneric(
obj,
img,
camera_matrix,
dist_coeffs,
flags=cv2.SOLVEPNP_IPPE,
)
if result and bool(result[0]):
candidates.extend(
(np.asarray(rvec, dtype=np.float64).reshape(3, 1),
np.asarray(tvec, dtype=np.float64).reshape(3, 1))
for rvec, tvec in zip(result[1], result[2])
)
except cv2.error:
candidates.clear()
if not candidates:
ok, rvec, tvec = cv2.solvePnP(
obj,
img,
camera_matrix,
dist_coeffs,
flags=cv2.SOLVEPNP_ITERATIVE,
)
if not ok:
raise ValueError("无法估计平面目标位姿")
candidates.append((rvec, tvec))
ranked: list[tuple[float, np.ndarray, np.ndarray]] = []
for rvec, tvec in candidates:
try:
if hasattr(cv2, "solvePnPRefineLM"):
rvec, tvec = cv2.solvePnPRefineLM(
obj,
img,
camera_matrix,
dist_coeffs,
rvec,
tvec,
)
rotation = cv2.Rodrigues(np.asarray(rvec, dtype=np.float64).reshape(3, 1))[0]
camera_points = (rotation @ obj.T).T + np.asarray(tvec, dtype=np.float64).reshape(1, 3)
if not np.all(np.isfinite(camera_points)) or np.min(camera_points[:, 2]) <= 0:
continue
projected = cv2.projectPoints(obj, rvec, tvec, camera_matrix, dist_coeffs)[0].reshape(-1, 2)
error = float(np.sqrt(np.mean(np.sum(np.square(projected - img), axis=1))))
if math.isfinite(error):
ranked.append((error, np.asarray(rvec, dtype=np.float64), np.asarray(tvec, dtype=np.float64)))
except cv2.error:
continue
if not ranked:
raise ValueError("平面目标 PnP 候选解均不满足正深度约束")
_, best_rvec, best_tvec = min(ranked, key=lambda item: item[0])
return best_rvec.reshape(3, 1), best_tvec.reshape(3, 1)
# Upstream handeye_calibration_gui.py:250-266
def estimate_charuco_pose(
board: Any,
corners: np.ndarray,
ids: np.ndarray,
camera_matrix: np.ndarray,
dist_coeffs: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Estimate ``T_camera_target`` from the detected ChArUco corners."""
detected_corners = np.asarray(corners, dtype=np.float32).reshape(-1, 1, 2)
detected_ids = np.asarray(ids, dtype=np.int32).reshape(-1, 1)
object_points, image_points = board.matchImagePoints(detected_corners, detected_ids)
if object_points is None or image_points is None or len(object_points) < 4:
raise ValueError("有效 ChArUco 角点不足,至少需要 4 个对应点")
rvec, tvec = estimate_planar_pose(object_points, image_points, camera_matrix, dist_coeffs)
if not np.all(np.isfinite(rvec)) or not np.all(np.isfinite(tvec)):
raise ValueError("无法从 ChArUco 角点估计 camera→target 位姿")
return rvec, tvec
# Upstream handeye_calibration_gui.py:269-286
def ax_xb_motion(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
first: int,
second: int,
eye_in_hand: bool,
) -> tuple[np.ndarray, np.ndarray]:
"""Return the OpenCV/MoveIt motion pair satisfying ``A X = X B``."""
base_to_eef_i, base_to_eef_j = robot_poses[first], robot_poses[second]
if eye_in_hand:
# (T_base_eef[j])^-1 T_base_eef[i] X = X T_cam_target[j] (T_cam_target[i])^-1
A = np.linalg.inv(base_to_eef_j) @ base_to_eef_i
else:
# OpenCV's eye-to-hand form uses T_eef_base = (T_base_eef)^-1.
# Its returned X is then T_base_camera.
A = base_to_eef_j @ np.linalg.inv(base_to_eef_i)
B = target_poses[second] @ np.linalg.inv(target_poses[first])
return A, B
# Upstream handeye_calibration_gui.py:289-311
def solve_handeye_matrix(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
eye_in_hand: bool,
method: int,
) -> np.ndarray:
"""Run one OpenCV hand-eye solver and validate its SE(3) result."""
if len(robot_poses) != len(target_poses) or len(robot_poses) < 5:
raise ValueError("手眼标定至少需要 5 组配对位姿")
inputs = robot_poses if eye_in_hand else [np.linalg.inv(pose) for pose in robot_poses]
rotation, translation = cv2.calibrateHandEye(
[pose[:3, :3] for pose in inputs],
[pose[:3, 3].reshape(3, 1) for pose in inputs],
[pose[:3, :3] for pose in target_poses],
[pose[:3, 3].reshape(3, 1) for pose in target_poses],
method=method,
)
solution = np.eye(4, dtype=np.float64)
solution[:3, :3] = np.asarray(rotation, dtype=np.float64).reshape(3, 3)
solution[:3, 3] = np.asarray(translation, dtype=np.float64).reshape(3)
if not np.all(np.isfinite(solution)) or abs(np.linalg.det(solution[:3, :3]) - 1.0) > 1e-3:
raise ValueError("求解器返回了无效的刚体变换")
return solution
# Upstream handeye_calibration_gui.py:314-319
def _rotation_mean(rotations: list[np.ndarray]) -> np.ndarray:
accumulator = np.sum(np.asarray(rotations, dtype=np.float64), axis=0)
left, _, right_t = np.linalg.svd(accumulator)
correction = np.eye(3)
correction[2, 2] = np.linalg.det(left @ right_t)
return left @ correction @ right_t
# Upstream handeye_calibration_gui.py:322-361
def fixed_target_consistency(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
solution: np.ndarray,
eye_in_hand: bool,
) -> dict[str, Any]:
"""Measure how constant the physically fixed target/tool transform remains."""
fixed_poses = []
for robot_pose, target_pose in zip(robot_poses, target_poses):
if eye_in_hand:
fixed_poses.append(robot_pose @ solution @ target_pose)
else:
fixed_poses.append(np.linalg.inv(robot_pose) @ solution @ target_pose)
center_translation = np.median(np.asarray([pose[:3, 3] for pose in fixed_poses]), axis=0)
center_rotation = _rotation_mean([pose[:3, :3] for pose in fixed_poses])
translation_errors = np.asarray(
[np.linalg.norm(pose[:3, 3] - center_translation) for pose in fixed_poses],
dtype=np.float64,
)
rotation_errors = np.asarray(
[math.radians(rotation_angle_degrees(center_rotation.T @ pose[:3, :3])) for pose in fixed_poses],
dtype=np.float64,
)
trans_p95 = float(np.percentile(translation_errors, 95))
rot_p95 = float(np.percentile(rotation_errors, 95))
# Convert angular scatter to an equivalent displacement at a 20 cm lever arm.
score_m = trans_p95 + HAND_EYE_CHARACTERISTIC_LENGTH_M * rot_p95
return {
"translation_errors_m": translation_errors,
"rotation_errors_rad": rotation_errors,
"translation_median_m": float(np.median(translation_errors)),
"translation_rms_m": float(np.sqrt(np.mean(np.square(translation_errors)))),
"translation_p95_m": trans_p95,
"translation_max_m": float(np.max(translation_errors)),
"rotation_median_rad": float(np.median(rotation_errors)),
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rotation_errors)))),
"rotation_p95_rad": rot_p95,
"rotation_max_rad": float(np.max(rotation_errors)),
"score_m": float(score_m),
}
# Upstream handeye_calibration_gui.py:364-389
def ax_xb_all_pair_metrics(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
solution: np.ndarray,
eye_in_hand: bool,
) -> dict[str, float]:
"""Evaluate AX=XB on all pose pairs so metrics do not depend on capture order."""
translations: list[float] = []
rotations: list[float] = []
for first in range(len(robot_poses) - 1):
for second in range(first + 1, len(robot_poses)):
A, B = ax_xb_motion(robot_poses, target_poses, first, second, eye_in_hand)
residual = np.linalg.inv(A @ solution) @ (solution @ B)
translations.append(float(np.linalg.norm(residual[:3, 3])))
rotations.append(math.radians(rotation_angle_degrees(residual[:3, :3])))
return {
"pair_count": len(translations),
"translation_rms_m": float(np.sqrt(np.mean(np.square(translations)))),
"translation_median_m": float(np.median(translations)),
"translation_p95_m": float(np.percentile(translations, 95)),
"translation_max_m": float(np.max(translations)),
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rotations)))),
"rotation_median_rad": float(np.median(rotations)),
"rotation_p95_rad": float(np.percentile(rotations, 95)),
"rotation_max_rad": float(np.max(rotations)),
}
# Upstream handeye_calibration_gui.py:392-407
def dominant_rotation_axes(robot_poses: list[np.ndarray]) -> set[int]:
"""Return the base-frame axes covered by meaningful relative rotations."""
axes: set[int] = set()
for first in range(len(robot_poses) - 1):
for second in range(first + 1, len(robot_poses)):
relative = np.linalg.inv(robot_poses[first]) @ robot_poses[second]
if rotation_angle_degrees(relative[:3, :3]) < 3.0:
continue
rotvec = cv2.Rodrigues(relative[:3, :3])[0].reshape(3)
norm = float(np.linalg.norm(rotvec))
if norm <= 1e-9:
continue
axis = np.abs(rotvec / norm)
if float(np.max(axis)) > 0.70:
axes.add(int(np.argmax(axis)))
return axes
# Upstream handeye_calibration_gui.py:410-418
def _fixed_pose(
robot_pose: np.ndarray,
target_pose: np.ndarray,
solution: np.ndarray,
eye_in_hand: bool,
) -> np.ndarray:
if eye_in_hand:
return robot_pose @ solution @ target_pose
return np.linalg.inv(robot_pose) @ solution @ target_pose
# Upstream handeye_calibration_gui.py:421-424
def _pose_center(poses: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
translation = np.median(np.asarray([pose[:3, 3] for pose in poses]), axis=0)
rotation = _rotation_mean([pose[:3, :3] for pose in poses])
return rotation, translation
# Upstream handeye_calibration_gui.py:427-478
def leave_one_out_handeye_metrics(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
eye_in_hand: bool,
method: int,
) -> dict[str, float]:
"""Evaluate a solver on poses excluded from each individual fit."""
translation_errors: list[float] = []
rotation_errors: list[float] = []
for held_out in range(len(robot_poses)):
train_ids = [index for index in range(len(robot_poses)) if index != held_out]
if len(train_ids) < 5:
continue
train_robot = [robot_poses[index] for index in train_ids]
train_target = [target_poses[index] for index in train_ids]
try:
solution = solve_handeye_matrix(train_robot, train_target, eye_in_hand, method)
except (ValueError, cv2.error, np.linalg.LinAlgError):
continue
train_fixed = [
_fixed_pose(robot_pose, target_pose, solution, eye_in_hand)
for robot_pose, target_pose in zip(train_robot, train_target)
]
center_rotation, center_translation = _pose_center(train_fixed)
test_fixed = _fixed_pose(
robot_poses[held_out],
target_poses[held_out],
solution,
eye_in_hand,
)
translation_errors.append(float(np.linalg.norm(test_fixed[:3, 3] - center_translation)))
rotation_errors.append(
math.radians(rotation_angle_degrees(center_rotation.T @ test_fixed[:3, :3]))
)
if not translation_errors:
raise ValueError("留一验证没有得到有效结果")
trans = np.asarray(translation_errors, dtype=np.float64)
rot = np.asarray(rotation_errors, dtype=np.float64)
trans_p95 = float(np.percentile(trans, 95))
rot_p95 = float(np.percentile(rot, 95))
return {
"sample_count": len(translation_errors),
"translation_median_m": float(np.median(trans)),
"translation_rms_m": float(np.sqrt(np.mean(np.square(trans)))),
"translation_p95_m": trans_p95,
"translation_max_m": float(np.max(trans)),
"rotation_median_rad": float(np.median(rot)),
"rotation_rms_rad": float(np.sqrt(np.mean(np.square(rot)))),
"rotation_p95_rad": rot_p95,
"rotation_max_rad": float(np.max(rot)),
"score_m": trans_p95 + HAND_EYE_CHARACTERISTIC_LENGTH_M * rot_p95,
}
# Upstream handeye_calibration_gui.py:481-592
def robust_handeye_calibration(
robot_poses: list[np.ndarray],
target_poses: list[np.ndarray],
eye_in_hand: bool,
requested_solver: str = AUTO_SOLVER_LABEL,
) -> dict[str, Any]:
"""Reject transform outliers, compare solvers and return the best solution."""
if len(robot_poses) != len(target_poses) or len(robot_poses) < 5:
raise ValueError("手眼标定至少需要 5 组配对位姿")
active = list(range(len(robot_poses)))
rejected: list[dict[str, Any]] = []
maximum_rejections = min(4, max(0, len(active) // 5), max(0, len(active) - 6))
# Remove at most one sample per iteration and recompute the solution. This
# avoids a single bad pose shifting the robust center enough to hide itself.
while len(rejected) < maximum_rejections and len(active) > 6:
active_robot = [robot_poses[index] for index in active]
active_target = [target_poses[index] for index in active]
candidates: list[tuple[float, str, np.ndarray, dict[str, Any]]] = []
method_items = HAND_EYE_SOLVER_METHODS.items()
if requested_solver in HAND_EYE_SOLVER_METHODS:
method_items = [(requested_solver, HAND_EYE_SOLVER_METHODS[requested_solver])]
for name, method in method_items:
try:
solution = solve_handeye_matrix(active_robot, active_target, eye_in_hand, method)
consistency = fixed_target_consistency(active_robot, active_target, solution, eye_in_hand)
candidates.append((consistency["score_m"], name, solution, consistency))
except (ValueError, cv2.error, np.linalg.LinAlgError):
continue
if not candidates:
raise ValueError("全部手眼求解器均失败,请增加姿态变化后重新采集")
_, provisional_name, _, consistency = min(candidates, key=lambda item: item[0])
trans = consistency["translation_errors_m"]
rot = consistency["rotation_errors_rad"]
trans_median = float(np.median(trans))
rot_median = float(np.median(rot))
trans_mad = float(np.median(np.abs(trans - trans_median)))
rot_mad = float(np.median(np.abs(rot - rot_median)))
trans_limit = max(
HAND_EYE_OUTLIER_TRANSLATION_FLOOR_M,
trans_median + 3.5 * 1.4826 * trans_mad,
)
rot_limit = max(
HAND_EYE_OUTLIER_ROTATION_FLOOR_RAD,
rot_median + 3.5 * 1.4826 * rot_mad,
)
severities = np.maximum(trans / trans_limit, rot / rot_limit)
worst_local = int(np.argmax(severities))
if float(severities[worst_local]) <= 1.0:
break
rejected.append({
"input_index": int(active[worst_local]),
"translation_error_m": float(trans[worst_local]),
"rotation_error_rad": float(rot[worst_local]),
"translation_limit_m": trans_limit,
"rotation_limit_rad": rot_limit,
"provisional_solver": provisional_name,
})
del active[worst_local]
active_robot = [robot_poses[index] for index in active]
active_target = [target_poses[index] for index in active]
reports: dict[str, dict[str, Any]] = {}
solved: dict[str, np.ndarray] = {}
for name, method in HAND_EYE_SOLVER_METHODS.items():
try:
solution = solve_handeye_matrix(active_robot, active_target, eye_in_hand, method)
consistency = fixed_target_consistency(active_robot, active_target, solution, eye_in_hand)
in_sample = {
key: value for key, value in consistency.items()
if key not in {"translation_errors_m", "rotation_errors_rad"}
}
try:
cross_validation = leave_one_out_handeye_metrics(
active_robot,
active_target,
eye_in_hand,
method,
)
except (ValueError, cv2.error, np.linalg.LinAlgError):
cross_validation = None
reports[name] = {
"status": "ok",
"in_sample": in_sample,
"leave_one_out": cross_validation,
}
solved[name] = solution
except (ValueError, cv2.error, np.linalg.LinAlgError) as exc:
reports[name] = {"status": "failed", "error": str(exc)}
available = [name for name in HAND_EYE_SOLVER_METHODS if name in solved]
if not available:
raise ValueError("异常样本筛选后全部手眼求解器均失败")
if requested_solver in solved:
selected_name = requested_solver
else:
def solver_rank(name: str) -> float:
validation = reports[name].get("leave_one_out")
if validation is not None:
return float(validation["score_m"])
return float(reports[name]["in_sample"]["score_m"])
selected_name = min(available, key=solver_rank)
solution = solved[selected_name]
return {
"solution": solution,
"selected_solver": selected_name,
"active_indices": active,
"rejected": rejected,
"solver_reports": reports,
"consistency": fixed_target_consistency(active_robot, active_target, solution, eye_in_hand),
"pair_metrics": ax_xb_all_pair_metrics(active_robot, active_target, solution, eye_in_hand),
}