【传感器标定】相机内参标定(c++、python代码)

2024-02-05 15:20:01 浏览数 (1)

前言

  • 文章主要给出利用棋盘格标定的代码, python 与 c 标定代码都会给出。
  • 普通相机与鱼眼相机标定代码细微之处有所不同,普通相机与鱼眼相机标定代码本文都会还会。

代码

python 代码

普通相机

代码需要自行修改的地方

  1. 棋盘格长、宽内角点数目
  2. 棋盘格图片文件夹路径
代码语言:javascript复制
import cv2
import numpy as np
import glob

# 找棋盘格角点
# 设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)  # 阈值
# 棋盘格模板规格 内角点数目
w = 11
h = 8
# 世界坐标系中的棋盘格点,例如(0,0,0), (1,0,0), (2,0,0) ....,(8,5,0),去掉Z坐标,记为二维矩阵
objp = np.zeros((w * h, 3), np.float32)
objp[:, :2] = np.mgrid[0:w, 0:h].T.reshape(-1, 2)
objp = objp * 35  # 35mm

# 储存棋盘格角点的世界坐标和图像坐标对
objpoints = []  # 在世界坐标系中的三维点
imgpoints = []  # 在图像平面的二维点
# 加载文件夹下所有的jpg图像
images = glob.glob('F:/aproject/camera_car/head_camera/useful/*.jpg')  # 拍摄的十几张棋盘图片所在目录

i = 0
for fname in images:
    img = cv2.imread(fname)
    # 获取画面中心点
    # 获取图像的长宽
    h1, w1 = img.shape[0], img.shape[1]
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    u, v = img.shape[:2]
    # 找到棋盘格角点
    ret, corners = cv2.findChessboardCorners(gray, (w, h), None)
    # 如果找到足够点对,将其存储起来
    if ret == True:
        print("i:", i)
        i = i   1
        # 在原角点的基础上寻找亚像素角点
        cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        # 追加进入世界三维点和平面二维点中
        objpoints.append(objp)
        imgpoints.append(corners)
        # 将角点在图像上显示
        cv2.drawChessboardCorners(img, (w, h), corners, ret)
        cv2.namedWindow('findCorners', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('findCorners', 640, 480)
        cv2.imshow('findCorners', img)
        cv2.waitKey(100)
    else:
        print("标定失败", fname)
cv2.destroyAllWindows()
print('正在计算')
# 标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

print("ret标定误差:", ret)  # 标定误差 0.1-0.5
print("mtx内参数矩阵:n", mtx.reshape(-1).tolist())  # 内参数矩阵
print("dist畸变值:n", dist.reshape(-1).tolist())  # 畸变系数   distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
print("rvecs旋转(向量)外参:n", rvecs)  # 旋转向量  # 外参数
print("tvecs平移(向量)外参:n", tvecs)  # 平移向量  # 外参数
鱼眼相机
代码语言:javascript复制
import numpy as np
import cv2
import glob

# Define the chess board rows and columns
CHECKERBOARD = (11, 8)
subpix_criteria = (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC   cv2.fisheye.CALIB_CHECK_COND   cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)
objp[0, :, :2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
objpoints = []  # 3d point in real world space
imgpoints = []  # 2d points in image plane.
counter = 0
images = glob.glob('F:\useful_image\*.jpg')  # 拍摄的十几张棋盘图片所在目录
i = 0

for path in images:
    # Load the image and convert it to gray scale
    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD,
                                             cv2.CALIB_CB_ADAPTIVE_THRESH   cv2.CALIB_CB_FAST_CHECK   cv2.CALIB_CB_NORMALIZE_IMAGE)
    # Make sure the chess board pattern was found in the image
    if ret:
        i  = 1
        print(i, path)
        objpoints.append(objp)
        cv2.cornerSubPix(gray, corners, (3, 3), (-1, -1), subpix_criteria)
        imgpoints.append(corners)
        cv2.drawChessboardCorners(img, (11, 8), corners, ret)
        cv2.namedWindow('findCorners', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('findCorners', 640, 480)
        cv2.imshow('findCorners', img)
        cv2.waitKey(200)
    else:
        print("!!!!!", path)
    counter  = 1
N_imm = counter  # number of calibration images
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_imm)]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_imm)]
rms, _, _, _, _ = cv2.fisheye.calibrate(objpoints, imgpoints, gray.shape[::-1], K, D, rvecs, tvecs, calibration_flags,
                                        (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6))
print(K.reshape(-1).tolist(), "n", D.reshape(-1).tolist(), "n", rms)

c 代码

普通相机
代码语言:javascript复制
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main()
{
    // 1. 准备标定棋盘图像
    int boardWidth = 11;  // 棋盘格横向内角点数量
    int boardHeight = 8; // 棋盘格纵向内角点数量
    float squareSize = 1.f; // 棋盘格格子的大小,单位为米,随便设置,不影响相机内参计算
    Size boardSize(boardWidth, boardHeight);

    vector<vector<Point3f>> objectPoints;
    vector<vector<Point2f>> imagePoints;
    vector<Point2f> corners;

    // 2. 拍摄棋盘图像
    Mat image, gray;
    namedWindow("image", WINDOW_NORMAL);
    vector<String> fileNames;
    glob("image3/*.jpg", fileNames);

    for (size_t i = 0; i < fileNames.size(); i  )
    {
        image = imread(fileNames[i], IMREAD_COLOR);
        cvtColor(image, gray, COLOR_BGR2GRAY);

        // 3. 读入图像数据,并提取角点
        bool found = findChessboardCorners(image, boardSize, corners, CALIB_CB_ADAPTIVE_THRESH   CALIB_CB_NORMALIZE_IMAGE   CALIB_CB_FAST_CHECK);
        if (found)
        {
            cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), TermCriteria(TermCriteria::EPS   TermCriteria::COUNT, 30, 0.1));
            drawChessboardCorners(image, boardSize, corners, found);
            imshow("image", image);
            waitKey();

            vector<Point3f> objectCorners;
            for (int j = 0; j < boardHeight; j  )
            {
                for (int k = 0; k < boardWidth; k  )
                {
                    objectCorners.push_back(Point3f(k * squareSize, j * squareSize, 0));
                }
            }
            objectPoints.push_back(objectCorners);
            imagePoints.push_back(corners);
        }
    }

    // 4. 标定相机
    Mat cameraMatrix, distCoeffs;
    vector<Mat> rvecs, tvecs;
    calibrateCamera(objectPoints, imagePoints, image.size(), cameraMatrix, distCoeffs, rvecs, tvecs);

    cout << "Camera matrix:" << endl << cameraMatrix << endl;
    cout << "Distortion coefficients:" << endl << distCoeffs << endl;

    return 0;
}

校正

  • 标定获得了相机内参与畸变系数,我们可以对畸变图片就行校正。关于校正代码,下一篇博客再分享。

0 人点赞