之前介绍了镜头畸变,本文记录校正畸变的模型和方法。
一些针孔摄像机会对图像产生严重的畸变,主要有两种畸变: 径向畸变和切向畸变。


\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}
camera \; matrix = \left [ \begin{matrix} f_x & 0 & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{matrix} \right ]

可以直接下载图像,命名为
undistort.png
示例代码(需要安装 mtutils)
pip install mtutils
核心步骤使用 OpenCV 库实现
import numpy as np
import cv2 as cv
import mtutils as mt
# 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 = mt.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)
mt.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)
mt.PIS([another, 'origin'], [img, 'marked'], [dst, 'undistort'], row_num=1)
pass