Opencv_棋盘格标定相机

发布时间:2024年01月16日
文章内容:
  1. 读取棋盘格图片进行标定
  2. 生成棋盘格图片
  3. 保存标定后的内容

棋盘格下载:https://gitee.com/liangbo1996/chessboard_27mm

// // 生成棋盘格(demo)
// void CreateGridironPattern()
// {
//     // 单位转换
//     int dot_per_inch = 108;
//     /*
//     * 这里以我惠普 光影精灵9的参数计算如下:
//     *  公式: DPI = 1920 / sqrt(15.6 ^ 2 + (1920 / 1080 * 15.6)^2)
//     *  sqrt(15.6 ^ 2 + (1920 / 1080 * 15.6)^2) ≈ 17.76
//     */

//     double cm_to_inch = 0.3937;   // 1cm = 0.3937inch
//     double inch_to_cm = 2.54;    //  1inch = 2.54cm( 1 英寸 = 2.54 厘米 是一个国际公认的单位)
//     double inch_per_dot = 1.0 / 96.0;

//     // 自定义标定板
//     double blockSize_cm = 1.5;  // 方格尺寸: 边长1.5cm的正方形
//     // 设置横列方框数目
//     int blockcol = 10;
//     int blockrow = 8;

//     int blockSize = (int)(blockSize_cm / inch_to_cm * dot_per_inch);
//     cout << "标定板尺寸: " << blockSize << endl;

//     int imageSizeCol = blockSize * blockrow;
//     int imageSizeRow = blockSize * blockcol;

//     Mat chessBoard(imageSizeCol, imageSizeRow, CV_8UC3, Scalar::all(0));
//     unsigned char color = 0;

//     for (int i = 0; i < imageSizeRow; i = i + blockSize)
//     {
//         color = ~color; // 将颜色值取反,如果开始为0,取反后为255(即黑白互换)
//         for (int j = 0; j < imageSizeCol; j = j + blockSize)
//         {
//             Mat ROI = chessBoard(Rect(i, j, blockSize, blockSize));
//             ROI.setTo(Scalar::all(color));
//             color = ~color;
//         }
//     }

//     imshow("chess board", chessBoard);
//     imwrite("chessBard.jpg", chessBoard);

//     waitKey(0);
//     return;
// }
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <fstream>

using namespace cv;
using namespace std;

int main()
{
    // 读取文件
    std::vector<cv::String> images;
    std::string path = "./images/*.jpg";
    cv::glob(path, images);

    if(images.size() == 0)
    {
        cout << "path is error" << endl;
        return 0;
    }

    // 设置变量
    int image_count = 0;                        // 图像数量
    Size image_size;                            // 图像的尺寸
    Size board_size = Size(9, 6);               // 标定板上每行、列的角点数
    vector<Point2f> image_points_buf;           // 缓存每幅图像上检测到的角点
    vector<vector<Point2f>> image_points_seq;   // 保存检测到的所有角点

    // 读取文件并进行操作
    for (int i = 0; i < images.size(); i++)
    {
        image_count++;
        cout << "image_count: " << image_count << endl;

        Mat imageInput = cv::imread(images[i]);
        if(imageInput.empty())
        {
            cout << "read error" << endl;
            return 0;
        }

        //读入第一张图片时获取图像宽高信息
        if (image_count == 1)
        {
            image_size.width = imageInput.cols;
            image_size.height = imageInput.rows;
            cout << "image_size.width = " << image_size.width << endl;
            cout << "image_size.height = " << image_size.height << endl;
        }

        // 提取角点
        if (0 == findChessboardCorners(imageInput, board_size, image_points_buf))
        {
            cout << "can not find chessboard corners!\n"; //找不到角点
            exit(1);
        }
        else
        {
            Mat view_gray;
            cvtColor(imageInput, view_gray, COLOR_RGB2GRAY);
            // 亚像素精确化
            find4QuadCornerSubpix(view_gray, image_points_buf, Size(5, 5)); //对粗提取的角点进行精确化
            //cornerSubPix(view_gray,image_points_buf,Size(5,5),Size(-1,-1),TermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,0.1));
            image_points_seq.push_back(image_points_buf);  //保存亚像素角点
            // 在图像上显示角点位置
            drawChessboardCorners(view_gray, board_size, image_points_buf, false); //用于在图片中标记角点
            imshow("Camera Calibration", view_gray); //显示图片
            waitKey(500);//暂停0.5S
        }
    }

    int total = image_points_seq.size();
    cout << "total = " << total << endl;
    int CornerNum = board_size.width * board_size.height; //每张图片上总的角点数
    for (int ii = 0 ; ii < total ; ii++)
    {
        if (0 == ii % CornerNum) // 24 是每幅图片的角点个数。此判断语句是为了输出 图片号,便于控制台观看
        {
            int i = -1;
            i = ii / CornerNum;
            int j = i + 1;
            cout << "--> 第 " << j << "图片的数据 --> : " << endl;
        }
        if (0 == ii % 3)	// 此判断语句,格式化输出,便于控制台查看
        {
            cout << endl;
        }
        else
        {
            cout.width(10);
        }
        //输出所有的角点
        cout << " -->" << image_points_seq[ii][0].x;
        cout << " -->" << image_points_seq[ii][0].y;
    }
    cout << "角点提取完成!\n";

    //以下是摄像机标定
    cout << "开始标定………………";
    /*棋盘三维信息*/
    Size square_size = Size(10, 10); /* 实际测量得到的标定板上每个棋盘格的大小 */
    vector<vector<Point3f>> object_points; /* 保存标定板上角点的三维坐标 */
    /*内外参数*/
    Mat cameraMatrix = Mat(3, 3, CV_32FC1, Scalar::all(0)); /* 摄像机内参数矩阵 */
    vector<int> point_counts;  // 每幅图像中角点的数量
    Mat distCoeffs = Mat(1, 5, CV_32FC1, Scalar::all(0)); /* 摄像机的5个畸变系数:k1,k2,p1,p2,k3 */
    vector<Mat> tvecsMat;  /* 每幅图像的平移向量 */
    vector<Mat> rvecsMat; /* 每幅图像的旋转向量 */
    /* 初始化标定板上角点的三维坐标 */
    int i, j, t;
    for (t = 0; t < image_count; t++)
    {
        vector<Point3f> tempPointSet;
        for (i = 0; i < board_size.height; i++)
        {
            for (j = 0; j < board_size.width; j++)
            {
                Point3f realPoint;
                /* 假设标定板放在世界坐标系中z=0的平面上 */
                realPoint.x = i * square_size.width;
                realPoint.y = j * square_size.height;
                realPoint.z = 0;
                tempPointSet.push_back(realPoint);
            }
        }
        object_points.push_back(tempPointSet);
    }
    /* 初始化每幅图像中的角点数量,假定每幅图像中都可以看到完整的标定板 */
    for (i = 0; i < image_count; i++)
    {
        point_counts.push_back(board_size.width * board_size.height);
    }
    /* 开始标定 */
    calibrateCamera(object_points, image_points_seq, image_size, cameraMatrix, distCoeffs, rvecsMat, tvecsMat, 0);
    cout << "标定完成!\n";
    //对标定结果进行评价
    cout << "开始评价标定结果………………\n";
    double total_err = 0.0; /* 所有图像的平均误差的总和 */
    double err = 0.0; /* 每幅图像的平均误差 */
    vector<Point2f> image_points2; /* 保存重新计算得到的投影点 */
    cout << "\t每幅图像的标定误差:\n";
    cout << "每幅图像的标定误差:\n";
    for (i = 0; i < image_count; i++)
    {
        vector<Point3f> tempPointSet = object_points[i];
        /* 通过得到的摄像机内外参数,对空间的三维点进行重新投影计算,得到新的投影点 */
        projectPoints(tempPointSet, rvecsMat[i], tvecsMat[i], cameraMatrix, distCoeffs, image_points2);
        /* 计算新的投影点和旧的投影点之间的误差*/
        vector<Point2f> tempImagePoint = image_points_seq[i];
        Mat tempImagePointMat = Mat(1, tempImagePoint.size(), CV_32FC2);
        Mat image_points2Mat = Mat(1, image_points2.size(), CV_32FC2);
        for (int j = 0 ; j < tempImagePoint.size(); j++)
        {
            image_points2Mat.at<Vec2f>(0, j) = Vec2f(image_points2[j].x, image_points2[j].y);
            tempImagePointMat.at<Vec2f>(0, j) = Vec2f(tempImagePoint[j].x, tempImagePoint[j].y);
        }
        err = norm(image_points2Mat, tempImagePointMat, NORM_L2);
        total_err += err /=  point_counts[i];
        std::cout << "第" << i + 1 << "幅图像的平均误差:" << err << "像素" << endl;
        cout << "第" << i + 1 << "幅图像的平均误差:" << err << "像素" << endl;
    }
    std::cout << "总体平均误差:" << total_err / image_count << "像素" << endl;
    cout << "总体平均误差:" << total_err / image_count << "像素" << endl << endl;
    std::cout << "评价完成!" << endl;
    //保存定标结果
    std::cout << "开始保存定标结果………………" << endl;
    Mat rotation_matrix = Mat(3, 3, CV_32FC1, Scalar::all(0)); /* 保存每幅图像的旋转矩阵 */
    cout << "相机内参数矩阵:" << endl;
    cout << cameraMatrix << endl << endl;
    cout << "畸变系数:\n";
    cout << distCoeffs << endl << endl << endl;
    for (int i = 0; i < image_count; i++)
    {
        cout << "第" << i + 1 << "幅图像的旋转向量:" << endl;
        cout << rvecsMat[i] << endl;
        /* 将旋转向量转换为相对应的旋转矩阵 */
        Rodrigues(rvecsMat[i], rotation_matrix);
        cout << "第" << i + 1 << "幅图像的旋转矩阵:" << endl;
        cout << rotation_matrix << endl;
        cout << "第" << i + 1 << "幅图像的平移向量:" << endl;
        cout << tvecsMat[i] << endl << endl;
    }
    std::cout << "完成保存" << endl;
    cout << endl;
    /************************************************************************
    显示定标结果
    *************************************************************************/
    Mat mapx = Mat(image_size, CV_32FC1);
    Mat mapy = Mat(image_size, CV_32FC1);
    Mat R = Mat::eye(3, 3, CV_32F);
    std::cout << "保存矫正图像" << endl;
    string imageFileName;
    std::stringstream StrStm;
    for (int i = 0 ; i < image_count ; i++)
    {
        std::cout << "Frame #" << i + 1 << "..." << endl;
        initUndistortRectifyMap(cameraMatrix, distCoeffs, R, cameraMatrix, image_size, CV_32FC1, mapx, mapy);
        StrStm.clear();
        cout << images[i] << endl;
        Mat imageSource = imread(images[i]);
        Mat newimage = imageSource.clone();
        //另一种不需要转换矩阵的方式
        //undistort(imageSource,newimage,cameraMatrix,distCoeffs);
        remap(imageSource, newimage, mapx, mapy, INTER_LINEAR);
        StrStm.clear();
        StrStm << i + 1;
        StrStm >> imageFileName;
        imageFileName += "_d.jpg";
        imwrite(imageFileName, newimage);
    }
    std::cout << "保存结束" << endl;
}

文章来源:https://blog.csdn.net/weixin_44248637/article/details/135621832
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。