如何获得用于校准相机的相机矩阵

时间:2019-09-16 10:28:07

标签: python opencv

我正在使用acA4112-30uc-Basler ace相机。我正在尝试消除失真,但是要做到这一点,我必须获取“ mtx”参数,我不知道该如何获取。

1 个答案:

答案 0 :(得分:1)

使用OPENCV进行摄像机校准的理论在这里:OPENCV_DOC

首先,您需要修理相机。然后打印棋盘chessboardtoprint

部分A:拍摄图像并进行计算

打印后,将其放在书上。然后使用此代码通过相机拍摄一些图像:

import numpy as np
import cv2

objp = np.zeros((6 * 7, 3), np.float32)
objp[ : , : 2] = np.mgrid[0 : 7, 0 : 6].T.reshape(-1, 2)
objpoints = []
imgpoints = []

criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

cam = cv2.VideoCapture(0)
(w, h) = (int(cam.get(4)), int(cam.get(3)))

while(True):
    _ , frame = cam.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)

    if ret == True:
        objpoints.append(objp)
        corners = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        imgpoints.append(corners)

        cv2.drawChessboardCorners(frame, (7, 6), corners, ret)
        cv2.imshow('Find Chessboard', frame)
        cv2.waitKey(0)
    cv2.imshow('Find Chessboard', frame)
    print "Number of chess boards find:", len(imgpoints)        
    if cv2.waitKey(1) == 27:
        break

ret, oldMtx, coef, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints,
                                                      gray.shape[: : -1], None, None)
newMtx, roi = cv2.getOptimalNewCameraMatrix(oldMtx, coef, (w, h), 1, (w, h))

print "Original Camera Matrix:\n", oldMtx
print "Optimal Camera Matrix:\n", newMtx

np.save("Original camera matrix", oldMtx)
np.save("Distortion coefficients", coef)
np.save("Optimal camera matrix", newMtx)

cam.release()
cv2.destroyAllWindows()

在此代码中,您打开照相机并将印刷的棋chess放置在许多位置,以便对检测棋board进行编码以进行矩阵计算。每次时间码检测棋盘显示图像并打印检测到的图像数量。在显示一些图像后,您可以按Esc键完成计算。

部分B:使用矩阵校正摄像头输出

您可以使用以下代码进行测试:

import numpy as np
import cv2

oldMtx = np.load("Original camera matrix.npy")
coef = np.load("Distortion coefficients.npy")
newMtx = np.load("Optimal camera matrix.npy")

cam = cv2.VideoCapture(0)
(w, h) = (int(cam.get(4)), int(cam.get(3)))

while(True):
    _ , frame = cam.read()

    undis = cv2.undistort(frame, oldMtx, coef, newMtx)

    cv2.imshow("Original vs Undistortion", np.hstack([frame, undis]))
    key = cv2.waitKey(1)
    if key == 27:
        break
cam.release()
cv2.destroyAllWindows()

祝你好运!