Objective:
- Achieve camera calibration, camera internal parameters and distortion rotation parameters
- Attempt to correct image distortion caused by the camera
Code:
import cv2 as cv
import numpy as np
import glob
import os
# loop interrupt
criteria=(cv.TERM_CRITERIA_EPS+cv.TERM_CRITERIA_MAX_ITER,30.0.001)
Number of cross points of calibration plate
row=6
column=4
objp=np.zeros((row*column,3),np.float32)
objp[:,:2]=np.mgrid[0:row,0:column].T.reshape(-1.2)
objpoints=[] # Actual space 3D points
imgpoints=[] # 2D points in the image
# Batch read images
images=glob.glob('D:\\python\\photos\\chess\\*.jpg')
for fname in images:
img=cv.imread(fname)
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
Find the calibration board corner
ret,corners=cv.findChessboardCorners(gray,(row,column),None)
if ret==True:
objpoints.append(objp)
corners2=cv.cornerSubPix(gray, corners, (11.11), (-1, -1), criteria)
imgpoints.append(corners2)
# Calibration camera
ret,Matrix,dist,rvecs,tvecs=cv.calibrateCamera(objpoints,imgpoints,gray.shape[::-1].None.None)
datadir="D:\\python\\photos\\chess\\"
path=os.path.join(datadir)
img_list=os.listdir(path)
for i in img_list:
img=cv.imread(os.path.join(path,i))
h,w=img.shape[:2]
newMatrix, roi = cv.getOptimalNewCameraMatrix(Matrix, dist, (w,h), 1, (w,h)) # Correct image
dst = cv.undistort(img, Matrix, dist, None, newMatrix)
cv.imwrite('D:\\python\\practice\\photos\\calibrated\\'+i,dst)
# Calculate the reprojection error
tot_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv.projectPoints(objpoints[i], rvecs[i], tvecs[i], Matrix, dist)
error = cv.norm(imgpoints[i],imgpoints2, cv.NORM_L2)/len(imgpoints2)
tot_error += error
# output parameter
print('ret:\n',ret)
print('mtx:\n',Matrix)
print('dist:\n',dist)
print('rvecs:\n',rvecs)
print('tvecs:\n',tvecs)
print ("total error: ", tot_error/len(objpoints))
Copy the code
Welcome to pay attention to the public number: algorithm engineer learning log