相机的基本原理介绍见
张正友标定法的推导介绍见
张正友标定法-完整学习笔记-从原理到实战
相机的内参矩阵表示的是将相机坐标系中的空间点变换到像素坐标系中:
相机的外参表示的是世界坐标系到相机坐标下的变换:
其中, w c T _{w}^{c}T wcT表示的是相机的外参。在OpenCV使用棋盘格标定时,相机通常是固定的,棋盘格在相机视野中移动获取不同位置的图像。此时,世界坐标系在棋盘格上,不同图像之间相机的内参相同外参不同,同一张图像中不同的角点相机外参是相同的,相机张正友标定法的原理介绍可参考。
考虑畸变。
径向畸变和切向畸变的纠正公式表示为:
在标定时,可以假设世界坐标系在标定板上,相机在移动,(实际上通常相机是固定的,标定板是移动的)。因此标定板上面角点在世界坐标系中的点的 Z w Z_w Zw坐标可当作0。因此,我们只需要得到 X w , Y w X_w,Y_w Xw,Yw的坐标即可进行标定。 X w X_w Xw, Y w Y_w Yw的值可以简单的传(0,0),(0,1),(1,0),这样得到标定结果的尺度是标定板棋盘格的行列数,若知道标定板棋盘格每一格的宽度,可传入(0,0),(0,30mm)…,得到的标定结果单位是 m m mm mm。参考
#! python3
# -*- encoding: utf-8 -*-
'''
@File : calibrate.py
@Time : 2022/02/21 23:36:20
@Author : xxx
@Version : 1.0
@Contact : xxx
@License : (C)Copyright 2020-2021, xxx
@Desc :
'''
import numpy as np
import cv2 as cv
import glob
# 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,5,0)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].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.
images = glob.glob('imgs/*.jpg')
for idx,fname in enumerate(images):
img = cv.imread(fname)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv.findChessboardCorners(gray, (7,6), None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv.drawChessboardCorners(img, (7,6), corners2, ret)
cv.imwrite(f'img_{idx}.png', img)
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
img = cv.imread('imgs/left12.jpg')
h, w = img.shape[:2]
newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
print(f"len rvecs: {len(rvecs)}, len tvecs: {len(tvecs)}")
print(f"内参:{mtx}, \n 畸变: {dist}\n 外参旋转: {rvecs}\n外参平移:{tvecs}")
# undistort
dst = cv.undistort(img, mtx, dist, None, newcameramtx)
# crop the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv.imwrite('calibresult0.png', dst)
# undistort
mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
dst = cv.remap(img, mapx, mapy, cv.INTER_LINEAR)
# crop the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv.imwrite('calibresult1.png', dst)
mean_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv.norm(imgpoints[i], imgpoints2, cv.NORM_L2)/len(imgpoints2)
mean_error += error
print( "total error: {}".format(mean_error/len(objpoints)) )
代码来自于OpenCV Tutorial,数据可见OpenCV 仓库,若需要自己标定,可在这里下载9x9标定纸。
Ref:
1.https://docs.opencv.org/4.x/d4/d94/tutorial_camera_calibration.html