With ret, corners = cv2.findChessboardCorners(img, (5, 4),cv2.CALIB_CB_ASYMMETRIC_GRID)
, you are using the default array (5, 4)
.
But if you look at the printed chessboard, the pattern sheet is (7, 9)
and 20 mm x 20 mm.
Then using the Official Calibration tutorial , the following code is created: / p>
Code
import numpy as np
import cv2 as cv
import glob
# Dimensões do Tabuleiro de Xadrez
cbcol = 7
cbrow = 9
cbw = 20
# Critério
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, cbw, 0.001)
# preparar os pontos do objeto, como (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((cbrow * cbcol, 3), np.float32)
objp[:, :2] = np.mgrid[0:cbcol, 0:cbrow].T.reshape(-1, 2)
# Vetores para armazenar os pontos de objeto e pontos de imagem de todas as imagens.
objpoints = [] # ponto 3d no espaço do mundo real
imgpoints = [] # ponto 2d no plano da imagem.
images = glob.glob('C:\Users\Desktop\teste\calib\*.jpg')
i=0
for fname in images:
print(fname)
img = cv.imread(fname)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Encontra os cantos do tabuleiro de xadrez
ret, corners = cv.findChessboardCorners(gray, (cbcol,cbrow), None)
# Se encontrado, adiciona os pontos de objeto e pontos de imagem (após refiná-los)
print(ret)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Desenha e mostra os cantos
cv.drawChessboardCorners(img, (cbcol, cbrow), corners2, ret)
cv.imwrite('C:\Users\Desktop\teste\calib\resultado\' + str(i) + '.jpg', img)
cv.imshow('img', img)
cv.waitKey(500)
i += 1
cv.destroyAllWindows()
Results
Rememberingthattheofficialtutorialasksforatleast10photosto performareliablecalibration.Or this issue may occur.
Calibrate Camera
After finding the points, the calibration can be performed:
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
Create new camera array
h, w = img.shape[:2]
newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
Undistorted image
There are two methods of doing this, the first one uses the function of OpenCV undistort()
and the second the function OpenCV remap()
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('calibresult.png', dst)
remap ()
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('calibresult.png', dst)