python-opencv圆形标定板实现相机标定,并进行畸变矫正和重投影误差计算代码
时间: 2024-02-04 10:02:15 浏览: 356
以下是使用Python和OpenCV进行圆形标定板的相机标定、畸变矫正和重投影误差计算的完整代码:
```
import numpy as np
import cv2
import glob
# 定义圆形标定板的行数和列数
rows = 7
cols = 10
# 定义每个圆的直径和间距
circle_diameter = 20 # 每个圆的直径
circle_spacing = 10 # 圆之间的间距
# 获取标定板图像的路径
images = glob.glob('path/to/images/*.jpg')
# 初始化标定板角点的空列表
obj_points = []
img_points = []
# 设置标定板上的点的坐标
objp = np.zeros((rows * cols, 3), np.float32)
objp[:, :2] = np.mgrid[0:rows, 0:cols].T.reshape(-1, 2)
objp = objp * (circle_diameter + circle_spacing)
# 针对每个标定板图像进行处理
for fname in images:
# 读取图像
img = cv2.imread(fname)
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 查找圆形标定板角点
ret, corners = cv2.findCirclesGrid(gray, (cols, rows), None)
# 如果找到了角点,则将其添加到角点列表中
if ret == True:
obj_points.append(objp)
img_points.append(corners)
# 在图像上显示角点
cv2.drawChessboardCorners(img, (cols, rows), corners, ret)
# 显示图像
cv2.imshow('img', img)
cv2.waitKey(500)
# 关闭窗口
cv2.destroyAllWindows()
# 进行相机标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None)
# 打印结果
print("Camera matrix:\n", mtx)
print("Distortion coefficients:\n", dist)
# 进行畸变矫正
for fname in images:
# 读取图像
img = cv2.imread(fname)
# 进行畸变矫正
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
# 显示结果
cv2.imshow('dst', dst)
cv2.waitKey(500)
# 关闭窗口
cv2.destroyAllWindows()
# 计算重投影误差
mean_error = 0
for i in range(len(obj_points)):
img_points2, _ = cv2.projectPoints(obj_points[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(img_points[i], img_points2, cv2.NORM_L2) / len(img_points2)
mean_error += error
print("Total error: ", mean_error / len(obj_points))
```
以上代码实现了圆形标定板的相机标定、畸变矫正和重投影误差计算,并在每个步骤中显示了结果。具体实现还需要根据实际情况进行修改和调试。
阅读全文