import cv2
import numpy as np
import glob
import matplotlib.pyplot as plt
cv2.__version__
#参考链接
#https://docs.opencv.org/3.4/dc/dbb/tutorial_py_calibration.html
#相关参数
#设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # 阈值
#棋盘格每行每列方块角点个数
w = 9
h = 6
#棋盘格方块边长(mm)
side = 10
#世界坐标下的棋盘格角点坐标如(0,0,0), (1,0,0), (2,0,0) ....,(8,5,0),去掉Z坐标,记为二维矩阵
objp = np.zeros((w*h,3), np.float32)
objp[:,:2] = np.mgrid[0:w,0:h].T.reshape(-1,2)
objp = objp*side # 边长side(mm)
#保存图片中的角点
world_points = [] #世界坐标系
img_points = [] #相平面坐标系
#拍摄的棋盘格图像文件列表
images = glob.glob('./imgs/*.jpg')
print("Image Files:",images)
#读取所有图片,检测角点,拿到世界坐标和相平面坐标
i=0
for fname in images:
img = cv2.imread(fname)
# 获取画面中心点
#获取图像的长宽
h1, w1 = img.shape[0], img.shape[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
u, v = img.shape[:2]
# 找到棋盘格角点
ret, corners = cv2.findChessboardCorners(gray, (w,h),None)
# 如果找到足够点对,将其存储起来
if ret == True:
print("i:", i)
i = i+1
# 在原角点的基础上寻找亚像素角点
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
#追加进入世界三维点和平面二维点中
world_points.append(objp)
img_points.append(corners)
# 将角点在图像上显示
cv2.drawChessboardCorners(img, (w,h), corners, ret)
cv2.namedWindow('findCorners', cv2.WINDOW_NORMAL)
cv2.resizeWindow('findCorners', 640, 480)
cv2.imshow('findCorners',img)
cv2.waitKey(1000)
cv2.destroyAllWindows()
#进行标定
ret, mtx, dist, rvecs, tvecs = \
cv2.calibrateCamera(world_points, img_points, gray.shape[::-1], None, None)
print("Error:", ret)
print("Instrinsic Matrix:\n",mtx) # 内参数矩阵
print("Distortion Coeff:\n", dist ) # 畸变系数 distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
print("Rotation Vectors:\n",rvecs) # 旋转向量 # 外参数
print("Translation Vectors:\n",tvecs ) # 平移向量 # 外参数
#使用去畸变参数
img = cv2.imread('./imgs/6.jpg')
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (u, v), 0, (u, v))
# 纠正畸变
dst1 = cv2.undistort(img, mtx, dist, None, newcameramtx)
mapx,mapy=cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w1,h1),5)
dst2=cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)
# 裁剪图像,输出纠正畸变以后的图片
x, y, w1, h1 = roi
dst1 = dst1[y:y + h1, x:x + w1]
plt.figure(1, figsize=(8,6), dpi=100)
plt.imshow(img)
plt.figure(1, figsize=(8,6), dpi=100)
plt.imshow(dst1)
plt.figure(1, figsize=(8,6), dpi=100)
plt.imshow(dst2)