×

C#实现手眼坐标转换:使用标定矩阵与刚体变换实现抓取点求解

独孤求败 独孤求败 发表于2026-11-02 11:18:36 浏览67 评论0

抢沙发发表评论

手眼标定做完,抓取还是偏?矩阵求对了,坐标转换的链路没串对

之前做一个3C零件抓取的项目,相机装在小臂上,机器人从料框里取零件放到流水线上。手眼标定做完了,重投影误差0.3像素,看着挺好。但实际抓取的时候,末端夹爪总是差那么一点——有时候偏2mm,有时候偏3mm,方向还不固定。

查了一个礼拜,标定矩阵本身没问题,问题出在坐标转换的链路上。从相机像素坐标到机器人基坐标,中间要经过四五次变换,每一步都涉及坐标系定义、旋转方向、单位换算。哪一步搞错了,误差就累积到抓取点上。

后来把整条链路画出来,一步步核对,才发现是机器人末端坐标系的定义和标定时用的定义不一致——标定用的是法兰坐标系,抓取用的是TCP坐标系,两者差了一个工具偏移。

这篇把坐标转换的完整链路和代码整理一下。

一、先搞清楚是哪种手眼配置

手眼标定分两种,坐标系转换的链路完全不同。

眼在手上(Eye-in-Hand):相机装在机械臂末端,跟着机械臂一起动。相机坐标系和机器人末端坐标系是固定关系,标定求的是相机到末端的变换矩阵。

抓取时的转换链路:

像素坐标 → 相机坐标 → 机器人末端坐标 → 机器人基坐标

眼在手外(Eye-to-Hand):相机固定在支架上,不跟着机械臂动。相机坐标系和机器人基坐标系是固定关系,标定求的是相机到基座的变换矩阵。

抓取时的转换链路:

像素坐标 → 相机坐标 → 机器人基坐标

项目里是眼在手上,所以转换链路多了一步——要经过末端坐标系。

二、2D抓取:九点标定

如果是平面抓取(零件在传送带上,抓取姿态只有XY平移和绕Z旋转),用九点标定就够了。

机器人末端带一个尖点,在相机视野内走9个点(3×3网格)。每个点记录两个坐标:机器人基坐标系的XY,相机图像里的像素坐标uv。

9组对应点,用仿射变换或者透视变换求解映射矩阵。

using System;
using System.Collections.Generic;
using OpenCvSharp;

/// <summary>
/// 九点标定器(2D)
/// </summary>
publicclassNinePointCalibrator
{
    privatereadonly List<Point2d> _robotPoints = new();  // 机器人坐标(mm)
    privatereadonly List<Point2d> _pixelPoints = new();  // 像素坐标

    /// <summary>
    /// 添加一组对应点
    /// </summary>
    public void AddPoint(double robotX, double robotY, 
        double pixelU, double pixelV
)

    {
        _robotPoints.Add(new Point2d(robotX, robotY));
        _pixelPoints.Add(new Point2d(pixelU, pixelV));
    }

    /// <summary>
    /// 求解仿射变换矩阵(像素 → 机器人)
    /// </summary>
    public Mat CalibrateAffine()
    {
        if (_pixelPoints.Count < 3)
            thrownew InvalidOperationException("至少需要3组点");

        // 至少需要3个点求仿射变换,9个点求最小二乘
        Mat affineMat = Cv2.EstimateAffine2D(_pixelPoints, _robotPoints);

        // 计算标定误差
        double maxError = 0, sumError = 0;
        foreach (var (pixel, robot) in
            _pixelPoints.Zip(_robotPoints, (p, r) => (p, r)))
        {
            // 用矩阵变换像素坐标
            var transformed = TransformPoint(affineMat, pixel);
            double error = Math.Sqrt(
                Math.Pow(transformed.X - robot.X, 2) +
                Math.Pow(transformed.Y - robot.Y, 2));
            maxError = Math.Max(maxError, error);
            sumError += error;
        }

        Console.WriteLine($"仿射标定完成: 平均误差={sumError / _pixelPoints.Count:F3}mm, " +
            $"最大误差={maxError:F3}mm");

        return affineMat;
    }

    /// <summary>
    /// 用仿射矩阵变换点
    /// </summary>
    public static Point2d TransformPoint(Mat mat, Point2d point)
    {
        double x = mat.At<double>(0, 0) * point.X + 
                   mat.At<double>(0, 1) * point.Y + 
                   mat.At<double>(0, 2);
        double y = mat.At<double>(1, 0) * point.X + 
                   mat.At<double>(1, 1) * point.Y + 
                   mat.At<double>(1, 2);
        returnnew Point2d(x, y);
    }
}

仿射变换能处理平移、旋转、缩放、剪切,但不能处理透视变形。相机垂直向下拍平面工件的时候,仿射够了。如果相机有倾角,需要透视变换(Cv2.FindHomography)。

三、3D抓取:刚体变换

3D抓取需要完整的旋转矩阵 + 平移向量。从相机坐标到机器人坐标的变换是一个刚体变换:

P_robot = R × P_camera + T

其中R是3×3旋转矩阵,T是3×1平移向量。

标定的方法:机器人带标定板走多个位姿,相机拍标定板,用OpenCV的SolvePnP求出每个位姿下标定板相对于相机的位姿。同时记录机器人末端的位姿。两组位姿做手眼标定(AX=XB),求出相机到末端的变换。

OpenCV提供了CalibrateHandEye函数:

using System;
using System.Collections.Generic;
using OpenCvSharp;

/// <summary>
/// 手眼标定器(3D,Eye-in-Hand)
/// </summary>
publicclassHandEyeCalibrator
{
    privatereadonly List<Mat> _robotRotations = new();   // 机器人末端旋转矩阵
    privatereadonly List<Mat> _robotTranslations = new(); // 机器人末端平移向量
    privatereadonly List<Mat> _cameraRotations = new();   // 标定板相对于相机的旋转
    privatereadonly List<Mat> _cameraTranslations = new(); // 标定板相对于相机的平移

    /// <summary>
    /// 添加一个标定位姿
    /// </summary>
    public void AddPose(Mat robotR, Mat robotT, Mat cameraR, Mat cameraT)
    {
        _robotRotations.Add(robotR.Clone());
        _robotTranslations.Add(robotT.Clone());
        _cameraRotations.Add(cameraR.Clone());
        _cameraTranslations.Add(cameraT.Clone());
    }

    /// <summary>
    /// 求解手眼变换矩阵
    /// </summary>
    public HandEyeResult Calibrate()
    {
        if (_robotRotations.Count < 3)
            thrownew InvalidOperationException("至少需要3个位姿");

        Mat R_cam2end = new Mat();
        Mat T_cam2end = new Mat();

        // 手眼标定:AX=XB
        // CalibrateHandEye求解的是相机到末端的变换
        Cv2.CalibrateHandEye(
            _robotRotations, _robotTranslations,
            _cameraRotations, _cameraTranslations,
            out R_cam2end, out T_cam2end,
            HandEyeCalibrationMethod.TSAI);

        // 构建4×4齐次变换矩阵
        Mat transform = Mat.Eye(4, 4, MatType.CV_64F);
        for (int r = 0; r < 3; r++)
        {
            for (int c = 0; c < 3; c++)
                transform.Set(r, c, R_cam2end.At<double>(r, c));
            transform.Set(r, 3, T_cam2end.At<double>(r, 0));
        }

        Console.WriteLine("相机到末端的变换矩阵:");
        Console.WriteLine($"  旋转: {R_cam2end.Dump()}");
        Console.WriteLine($"  平移: {T_cam2end.Dump()}");

        returnnew HandEyeResult
        {
            Rotation = R_cam2end,
            Translation = T_cam2end,
            TransformMatrix = transform
        };
    }
}

publicclassHandEyeResult
{
    public Mat Rotation { get; set; }
    public Mat Translation { get; set; }
    public Mat TransformMatrix { get; set; }
}

CalibrateHandEye的HandEyeCalibrationMethod有几种:TSAI、PARK、HORAUD、ANDREFF、DANIILIDIS。TSAI最常用,对噪声鲁棒性好。

四、抓取点求解

标定完之后,坐标转换的链路是:

眼在手上:

像素坐标 → 相机坐标(内参反投影) → 末端坐标(手眼矩阵) → 基坐标(机器人位姿)

眼在手外:

像素坐标 → 相机坐标(内参反投影) → 基坐标(手眼矩阵)

2D抓取场景下,像素坐标直接通过仿射矩阵转到机器人基坐标。3D抓取需要完整的变换链路。

/// <summary>
/// 抓取点求解器
/// </summary>
publicclassGraspPointSolver
{
    privatereadonly Mat _cameraMatrix;      // 相机内参
    privatereadonly Mat _handEyeTransform;  // 手眼矩阵(4×4)
    privatereadonlybool _isEyeInHand;

    public GraspPointSolver(Mat cameraMatrix, Mat handEyeTransform, 
        bool isEyeInHand
)

    {
        _cameraMatrix = cameraMatrix;
        _handEyeTransform = handEyeTransform;
        _isEyeInHand = isEyeInHand;
    }

    /// <summary>
    /// 从像素坐标求解基坐标系下的抓取点
    /// </summary>
    /// <param name="pixelU">像素u坐标</param>
    /// <param name="pixelV">像素v坐标</param>
    /// <param name="depthMm">深度值(从深度图或已知平面获取)</param>
    /// <param name="robotPose">机器人当前末端位姿(4×4齐次矩阵,眼在手上时需要)</param>
    public Point3d SolveGraspPoint(double pixelU, double pixelV, 
        double depthMm, Mat robotPose = null
)

    {
        // 1. 像素坐标 → 相机坐标
        Point3d cameraPoint = PixelToCamera(pixelU, pixelV, depthMm);

        // 2. 相机坐标 → 基坐标
        Point3d basePoint;
        if (_isEyeInHand)
        {
            // 眼在手上:相机 → 末端 → 基座
            if (robotPose == null)
                thrownew ArgumentNullException("眼在手上需要机器人位姿");

            // 相机 → 末端
            Point3d endPoint = TransformPoint(_handEyeTransform, cameraPoint);
            // 末端 → 基座
            basePoint = TransformPoint(robotPose, endPoint);
        }
        else
        {
            // 眼在手外:相机 → 基座
            basePoint = TransformPoint(_handEyeTransform, cameraPoint);
        }

        Console.WriteLine($"像素({pixelU:F1}, {pixelV:F1}) → " +
            $"相机({cameraPoint.X:F2}, {cameraPoint.Y:F2}, {cameraPoint.Z:F2}) → " +
            $"基座({basePoint.X:F2}, {basePoint.Y:F2}, {basePoint.Z:F2})");

        return basePoint;
    }

    /// <summary>
    /// 像素坐标反投影到相机坐标
    /// </summary>
    private Point3d PixelToCamera(double u, double v, double depthMm)
    {
        double fx = _cameraMatrix.At<double>(0, 0);
        double fy = _cameraMatrix.At<double>(1, 1);
        double cx = _cameraMatrix.At<double>(0, 2);
        double cy = _cameraMatrix.At<double>(1, 2);

        double x = (u - cx) * depthMm / fx;
        double y = (v - cy) * depthMm / fy;
        double z = depthMm;

        returnnew Point3d(x, y, z);
    }

    /// <summary>
    /// 用4×4齐次矩阵变换点
    /// </summary>
    private Point3d TransformPoint(Mat transform, Point3d point)
    {
        double x = transform.At<double>(0, 0) * point.X +
                   transform.At<double>(0, 1) * point.Y +
                   transform.At<double>(0, 2) * point.Z +
                   transform.At<double>(0, 3);

        double y = transform.At<double>(1, 0) * point.X +
                   transform.At<double>(1, 1) * point.Y +
                   transform.At<double>(1, 2) * point.Z +
                   transform.At<double>(1, 3);

        double z = transform.At<double>(2, 0) * point.X +
                   transform.At<double>(2, 1) * point.Y +
                   transform.At<double>(2, 2) * point.Z +
                   transform.At<double>(2, 3);

        returnnew Point3d(x, y, z);
    }
}

五、2D抓取完整流程

平面抓取场景,用仿射矩阵直接转换。

/// <summary>
/// 2D抓取点求解(九点标定 + 仿射变换)
/// </summary>
publicclassGrasp2DSolver
{
    privatereadonly Mat _affineMat;  // 像素 → 机器人基坐标
    privatereadonlydouble _toolOffsetX;
    privatereadonlydouble _toolOffsetY;

    public Grasp2DSolver(Mat affineMat, 
        double toolOffsetX = 0, double toolOffsetY = 0
)

    {
        _affineMat = affineMat;
        _toolOffsetX = toolOffsetX;
        _toolOffsetY = toolOffsetY;
    }

    /// <summary>
    /// 求解抓取点
    /// </summary>
    public Point2d SolveGraspPoint(double pixelU, double pixelV)
    {
        // 像素坐标 → 机器人坐标
        double robotX = _affineMat.At<double>(0, 0) * pixelU +
                        _affineMat.At<double>(0, 1) * pixelV +
                        _affineMat.At<double>(0, 2);

        double robotY = _affineMat.At<double>(1, 0) * pixelU +
                        _affineMat.At<double>(1, 1) * pixelV +
                        _affineMat.At<double>(1, 2);

        // 工具偏移补偿
        robotX += _toolOffsetX;
        robotY += _toolOffsetY;

        returnnew Point2d(robotX, robotY);
    }

    /// <summary>
    /// 计算抓取角度(从图像中的目标方向)
    /// </summary>
    public double SolveGraspAngle(Point2d pixelCenter, Point2d pixelDirection)
    {
        double dx = pixelDirection.X - pixelCenter.X;
        double dy = pixelDirection.Y - pixelCenter.Y;
        return Math.Atan2(dy, dx) * 180.0 / Math.PI;
    }
}

六、几个容易踩的坑

坑一:坐标系定义不一致

标定的时候用的是机器人法兰坐标系,抓取的时候用的是TCP坐标系。两者差了一个工具偏移(夹爪长度)。标定前先确认机器人当前用的坐标系是哪个,标定和抓取用同一个坐标系。

坑二:旋转矩阵的乘法顺序搞错

多个变换串联的时候,矩阵乘法顺序决定最终结果。P_base = R_end2base × R_cam2end × P_camera。顺序搞反了,坐标全错。画个坐标转换图,每一步标清楚,写完代码对着图核对一遍。

坑三:单位不统一

相机内参的焦距是像素单位,平移向量可能是毫米或者米。机器人坐标单位可能是毫米或者米。所有数据统一到同一个单位再计算。

坑四:九点标定的点分布太集中

9个点在视野里挤在一个小角落,求出来的仿射矩阵外推到大范围就偏了。9个点要均匀覆盖整个工作视野,边缘也要有点。

坑五:手眼标定的位姿不够多

3个位姿能求出解,但精度没保证。至少10-15个位姿,姿态要有变化(平移和旋转都要有),标定结果才稳。

坑六:深度值不准导致3D抓取偏

像素反投影需要深度值。深度图不准或者深度值估计错误,XY坐标也跟着错。用结构光或者激光测距获取准确的深度值。

七、验证标定结果

标定完之后,用一组独立的点验证。

/// <summary>
/// 标定验证器
/// </summary>
publicclassCalibrationValidator
{
    /// <summary>
    /// 用验证点测试抓取精度
    /// </summary>
    public double Validate(Grasp2DSolver solver, 
        List<(Point2d pixel, Point2d expectedRobot
)> testPoints)

    {
        double maxError = 0;
        foreach (var (pixel, expected) in testPoints)
        {
            var actual = solver.SolveGraspPoint(pixel.X, pixel.Y);
            double error = Math.Sqrt(
                Math.Pow(actual.X - expected.X, 2) +
                Math.Pow(actual.Y - expected.Y, 2));
            maxError = Math.Max(maxError, error);
            Console.WriteLine($"验证点: 实际({actual.X:F2}, {actual.Y:F2}), " +
                $"预期({expected.X:F2}, {expected.Y:F2}), 误差={error:F3}mm");
        }
        return maxError;
    }
}

验证点的误差应该在±0.5mm以内。超过这个值,先查坐标系定义,再查单位换算。

八、什么时候用哪种

场景
推荐
平面抓取、相机垂直向下
九点标定 + 仿射变换
相机有倾角
九点标定 + 透视变换
3D抓取、需要姿态估计
手眼标定 + 刚体变换
眼在手上
链路多一步:相机→末端→基座
眼在手外
链路直接:相机→基座
精度要求±0.5mm以内
九点标定验证,必要时加补偿

九、总结

手眼坐标转换的核心本质上其实就三件事:

  1. 搞清楚坐标系链路——眼在手上多一步,眼在手外直接转
  2. 标定矩阵求对——2D用仿射,3D用刚体变换
  3. 验证标定结果——用独立点测误差,别只信标定过程的重投影误差

那个3C抓取的项目,最后查到问题出在末端坐标系和TCP坐标系混用。统一坐标系之后,抓取偏差从2-3mm降到了0.3mm以内。


群贤毕至

访客