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

前言

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

代码

python 代码

普通相机

代码需要自行修改的地方

  1. 棋盘格长、宽内角点数目
  2. 棋盘格图片文件夹路径
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)  # 平移向量  # 外参数

鱼眼相机

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++ 代码

普通相机

#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;
}

校正

  • 定获得了相机内参与畸变系数,我们可以对畸变图片就行校正。关于校正代码,下一篇博客再分享。
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Python进行相机单目内参标定的示例代码: ```python import numpy as np import cv2 # 读取棋盘图像 image = cv2.imread('chessboard.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 设置棋盘尺寸 pattern_size = (9, 6) # 棋盘每行、每列的角点数 # 查找棋盘角点 found, corners = cv2.findChessboardCorners(gray, pattern_size, None) if found: # 提取亚像素角点 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) corners = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) # 绘制角点 cv2.drawChessboardCorners(image, pattern_size, corners, found) # 执行相机标定 object_points = np.zeros((np.prod(pattern_size), 3), dtype=np.float32) object_points[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2) image_points = corners.reshape(-1, 2) _, camera_matrix, dist_coeffs, _, _ = cv2.calibrateCamera([object_points], [image_points], gray.shape[::-1], None, None) # 打印标定结果 print("相机矩阵:") print(camera_matrix) print("\n畸变系数:") print(dist_coeffs) # 矫正图像 undistorted_image = cv2.undistort(image, camera_matrix, dist_coeffs) # 显示原始图像和矫正后的图像 cv2.imshow('Original Image', image) cv2.imshow('Undistorted Image', undistorted_image) cv2.waitKey(0) cv2.destroyAllWindows() else: print("未找到棋盘角点") ``` 请确保已经安装了OpenCV库,并将棋盘图像命名为'chessboard.jpg'并放置在与代码文件相同的目录中。运行代码后,将显示原始图像和矫正后的图像,并打印相机矩阵和畸变系数。 请注意,此代码仅适用于具有棋盘模式的相机标定。如果您使用其他标定模式,可能需要调整代码以适应不同的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

读书猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值