本文最后更新于:2024年5月16日 下午

之前介绍了镜头畸变,本文记录校正畸变的模型和方法。

背景

  • 对于常见的镜头径向畸变和切向畸变,在硬件已经无法继续优化时,需要后处理进行校正

模型

一些针孔摄像机会对图像产生严重的畸变,主要有两种畸变: 径向畸变和切向畸变。

径向畸变

  • 径向畸变导致直线看起来弯曲。点距图像中心越远,径向畸变越大。例如,下图显示了一个棋盘的两个边缘用红线标记的图像。但是,你可以看到棋盘的边界不是一条直线,与红线不匹配。所有预期的直线都凸出。

  • 径向畸变可以表示为以下模型
$$ \begin{array}{c} x_{distorted} = x( 1 + k_1 r^2 + k_2 r^4 + k_3 r^6) \\ y_{distorted} = y( 1 + k_1 r^2 + k_2 r^4 + k_3 r^6) \end{array} $$

切向畸变

  • 类似地,切向畸变发生是因为摄像透镜没有与成像平面完全平行。因此,图像中的某些区域看起来可能比预期的要近。切向扭曲的数量可表示如下:
$$ \begin{array}{c} x_{distorted} = x + [ 2p_1xy + p_2(r^2+2x^2)] \\ y_{distorted} = y + [ p_1(r^2+ 2y^2)+ 2p_2xy] \end{array} $$

叠加畸变

利用上面两组式子就可对畸变进行较好的修正。同时对径向、切向畸变消除就是将两组式子合并。

自变量为理想坐标,等式左边的结果为畸变坐标,反过来该公式不成立。

$$ \begin{aligned} x_{\text {distorted }} & =x\left(1+k_{1} r^{2}+k_{2} r^{4}+k_{3} r^{6}\right)+2 p_{1} x y+p_{2}\left(r^{2}+2 x^{2}\right) \\ y_{\text {distorted }} & =y\left(1+k_{1} r^{2}+k_{2} r^{4}+k_{3} r^{6}\right)+p_{1}\left(r^{2}+2 y^{2}\right)+2 p_{2} x y\end{aligned} $$

畸变系数

  • 简而言之,我们需要找到五个参数,即畸变系数:

$$
Distortion ; coefficients=(k_1 \hspace{10pt} k_2 \hspace{10pt} p_1 \hspace{10pt} p_2 \hspace{10pt} k_3)
$$

相机参数

  • 除了畸变模型参数之外,还需要一些其他的信息,比如相机的内部参数外部参数

内参

  • 摄像机的固有参数是特定的。它们包括像焦距 $(f_x,f_y)$和光学中心 $(c_x,c_y)$ 这样的信息。所述焦距和光学中心可用于创建摄像机矩阵,该矩阵可用于消除由于特定摄像机的镜头而产生的畸变。相机矩阵对于特定的相机来说是独一无二的,所以一旦计算出来,就可以在同一个相机拍摄的其他图像上重复使用。它表示为一个 $3 \times 3$ 的矩阵:
$$ camera \; matrix = \left [ \begin{matrix} f_x & 0 & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{matrix} \right ] $$

外参

  • 外部参数对应于将 3D 点的坐标转换为坐标系的旋转和平移向量。

  • 为了找到这些参数,我们必须提供一些定义良好的示例图像(例如棋盘)。如果已经知道相对位置的特定点(例如棋盘上的方角),并且知道这些点在真实空间中的坐标,也知道图像中的坐标,在这种情况下就可以求出畸变系数。

    为了获得更好的结果,至少需要10组对应点的数据。

cv2.calibrateCamera

OpenCV 库有相机畸变矫正的函数,官方文档

  • 函数用法:

    1
    2
    cv2.calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs[, rvecs[, tvecs[, flags[, criteria]]]]
    -> retval, cameraMatrix, distCoeffs, rvecs, tvecs
  • 输入参数说明:

    • objectPoints:真实世界中标定板上点的坐标,期望是一个 (n, 3) 形状的 Numpy 数组,其中 n 是标定板上点的总数。
    • imagePoints:图像中标定板上点的坐标,期望是一个 (n, 2) 形状的 Numpy 数组。
    • imageSize:图像的大小,一个 (height, width) 形状的元组。
    • camera_matrix:相机的内参矩阵,一个 (3, 3) 形状的 Numpy 数组。如果设置为 None,则默认相机的内参矩阵则迭代计算初始值为单位矩阵。
    • dist_coeffs:畸变系数,一个 (5,) 形状的 Numpy 数组 (k1, k2, p1, p2, k3)。如果设置为 None,则默认迭代计算初始值为0。
    • flags:标定过程中的 flags,通常设置为 cv2.CALIB_USE_INTRINSIC_GUESS,表示使用初始的内参矩阵猜测值。
  • 输出参数说明:

    • retval:是一个 double 值,官方文档没有介绍,有一种说法是重投影误差的某种统计量(存疑)。
    • camera_matrix:这是相机内参矩阵,包含了相机的焦距(fx 和 fy)和主点(cx 和 cy)。内参矩阵是相机投影模型的数学表示,它定义了相机如何将三维空间中的点投影到二维图像平面上。
    • dist_coeffs:这是畸变系数,它是一个包含畸变参数的向量,包括畸变系数(k1, k2, p1, p2, k3)。这些系数可以用来校正镜头畸变,使得图像的边缘更加直线。
    • rvecs(旋转向量)和 tvecs(平移向量):这些参数表示相机在世界坐标系中的旋转和平移。rvecs 是一个包含旋转角度的向量,而 tvecs 是一个包含平移向量的向量。这些参数允许你了解相机在标定过程中相对于世界坐标系的位置和方向变化。

计算过程

  1. 初始化内参矩阵和畸变系数:如果 camera_matrixdist_coeffs 没有被指定,cv2.calibrateCamera 会使用单位矩阵和全零数组作为初始猜测值。
  2. 最小化重投影误差:函数会尝试找到最优化的内参矩阵和畸变系数,使得所有图像中标定板上点的重投影误差之和最小。这通常通过非线性优化算法(如 Levenberg-Marquardt 算法)来实现。
  3. 计算校正后的图像大小:根据优化后的内参矩阵,计算出校正后的图像大小,这有助于后续的图像裁剪。
  4. 返回结果:函数返回优化后的内参矩阵、畸变系数、旋转向量(表示相机在世界坐标系中的旋转)和平移向量(表示相机在世界坐标系中的平移)。

完成标定后,你可以使用 cv2.undistort 函数和计算出的内参矩阵及畸变系数来对图像进行畸变校正。校正后的图像会尽可能地减少由于镜头畸变导致的图像扭曲。

Python 实现

  • 测试图像:

可以直接下载图像,命名为 undistort.png

  • 示例代码(需要安装 vvdutils)

    1
    pip install vvdutils
  • 核心步骤使用 OpenCV 库实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import numpy as np
import cv2 as cv
import vvdutils as vv

# termination criteria
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,6,0)
W_num = 7
H_num = 7

objp = np.zeros((W_num*H_num,3), np.float32)
objp[:,:2] = np.mgrid[0:W_num,0:H_num].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.

img = vv.cv_rgb_imread('undistort.png', 1)

another = img.copy()
# Find the chess board corners
ret, corners = cv.findChessboardCorners(img, (W_num,H_num), None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(img,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners2)
# Draw and display the corners
cv.drawChessboardCorners(img, (W_num, H_num), corners2, ret)
vv.PIS(img)

ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, img.shape[::-1], None, None)
h, w = img.shape[:2]

newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
dst = cv.undistort(another, mtx, dist, None, newcameramtx)
# 也可以进行点映射
# dst=cv.undistortPoints(src, cameraMatrix, distCoeffs[, dst[, R[, P]]])

# build map matrix
map1, map2 = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, img.shape[::-1], cv.CV_32FC1)
frame2 = cv.remap(another2, map1, map2, cv.INTER_LINEAR)

vv.PIS([another, 'origin'], [img, 'marked'], [dst, 'undistort'], row_num=1)
pass
  • 配置好图像,运行程序可以看到标记的图和校正结果

  • 使用映射矩阵直接映射得到矫正图像结果,速度可以快十几倍

封装 distortion_calibration

上述功能已经封装到 vvdutilsdistortion_calibration 函数中

参数说明
  • 函数输入:

    • 标定板图像文件夹路径(图像尺寸要相同)
    • 标定板横向、纵向点个数
  • 输出结果字典:

    • 相机内参 mtx

    • 畸变系数(f1, f2, p1, p2, f3) dist

    • 图像宽度 W

    • 图像高度 H

      过程中输出不可用图像信息

      打印结果信息

      输出每张有效图像的重投影误差,如果误差超过0.1则打印图像路径

示例代码
1
2
3
4
5
import vvdutils as vv

if __name__ == '__main__':
image_dir_path = 'datasets/images/'
result = vv.distortion_calibration(image_dir_path, 11, 8, show=False)

封装 distortion_calibration_to_map

如果需要转换矩阵,可以用 distortion_calibration的结果调用 distortion_calibration_to_map 接口生成:

1
2
3
4
5
6
import vvdutils as vv

if __name__ == '__main__':
image_dir_path = 'datasets/images/'
result = vv.distortion_calibration(image_dir_path, 11, 8, show=False)
result = vv.distortion_calibration_to_map(**result)

封装 undistort_with_map_result

之后可以使用 undistort_with_map_result 通过输入 图像 和 result 完成图像去畸变

1
2
3
4
5
6
7
8
9
import vvdutils as vv

if __name__ == '__main__':
image_dir_path = 'datasets/images/'
result = vv.distortion_calibration(image_dir_path, 11, 8, show=False)
result = vv.distortion_calibration_to_map(**result)

img = vv.cv_rgb_imread('demo.jpg')
dst = vv.undistort_with_map_result(img, result)

C++ 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<stdio.h>
#include<opencv2/opencv.hpp>
#include<vector>

using namespace std;
using namespace cv;


int main()
{

Mat srcImage = imread("undistort.png");
Mat another, another2;
srcImage.copyTo(another);
srcImage.copyTo(another2);

int W_num(7), H_num(7);

int width = srcImage.cols;
int height = srcImage.rows;

Mat corners;
findChessboardCorners(srcImage, Size(W_num, H_num), corners);
int corner_num = corners.rows;

vector<vector<Point2f>> imagePoints;
vector<Point2f> image_points;
for (int index(0); index < corner_num; index++) {
float x = corners.at<float>(index, 0);
float y = corners.at<float>(index, 1);

image_points.push_back(Point2f(x, y));
}

cv::TermCriteria criteria = cv::TermCriteria(
cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS,
30,
0.001);
Mat image_gray;
cv::cvtColor(srcImage, image_gray, cv::COLOR_BGR2GRAY);
cornerSubPix(image_gray, image_points, Size(30, 30), Size(-1, -1), criteria);

imagePoints.push_back(image_points);

vector<vector<Point3f>> objectPoints;
vector<Point3f> objpoints;
for (int index1(0); index1 < W_num; index1++)
{
for (int index2(0); index2 < H_num; index2++)
{
int index = index1 * H_num + index2;
objpoints.push_back(Point3f(index2, index1, 0));
}
}
objectPoints.push_back(objpoints);

Size imageSize;
imageSize = srcImage.size();
Mat cameraMatrix, distCoeffs;
vector<Mat> rvecs, tvecs;

calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs);

Mat newcameramatrix = getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize);

Mat dst;
undistort(another, dst, cameraMatrix, distCoeffs, newcameramatrix);

Mat map1, map2, R;
initUndistortRectifyMap(cameraMatrix, distCoeffs, R, newcameramatrix, imageSize, CV_32FC1, map1, map2);

Mat frame2;
remap(another2, frame2, map1, map2, INTER_LINEAR);

return 0;
}
  • image watch 中显示的矫正结果

参考资料



文章链接:
https://www.zywvvd.com/notes/study/camera-imaging/distort-corr/distort-corr/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

镜头畸变校正
https://www.zywvvd.com/notes/study/camera-imaging/distort-corr/distort-corr/
作者
Yiwei Zhang
发布于
2022年11月15日
许可协议