单目畸变校正 python
时间: 2025-04-24 17:08:28 浏览: 15
### 单目相机畸变校正的实现
对于单目相机畸变校正,在 Python 中使用 OpenCV 库是一个常见且高效的方法。通过读取一系列棋盘格图像来获取角点位置,进而计算相机矩阵和畸变系数。
#### 准备工作
为了完成这一过程,首先需要准备一组包含不同角度拍摄的棋盘格图案的照片。这些照片用于提取特征点并估计相机内部参数以及镜头畸变情况。
```python
import cv2
import numpy as np
import glob
# 设置查找亚像素角点的参数
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# 棋盘格尺寸(宽度-高度)
chessboard_size = (9, 6)
# 创建世界坐标系中的对象点数组,例如 (0,0,0), (1,0,0), (2,0,0) ....,(8,5,0)
objp = np.zeros((np.prod(chessboard_size), 3), np.float32)
objp[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)
# 存储所有图像的对象点和图像点向量
objpoints = [] # 在真实空间中的3D点
imgpoints = [] # 在图像平面内的2D点
images = glob.glob('calibration_images/*.jpg')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 查找棋盘格角落
ret, corners = cv2.findChessboardCorners(gray, chessboard_size, None)
if ret == True:
objpoints.append(objp)
# 提取更精确的位置
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
# 绘制并显示拐角
cv2.drawChessboardCorners(img, chessboard_size, corners2, ret)
cv2.imshow('Image', img)
cv2.waitKey(500)
cv2.destroyAllWindows()
```
上述代码片段展示了如何加载多张图片,并从中检测出棋盘格模式以收集必要的数据点[^2]。
#### 计算相机矩阵与畸变系数
一旦获得了足够的匹配对之后,则可以通过 `cv2.calibrateCamera` 方法来进行实际的标定操作:
```python
ret, camera_matrix, distortion_coefficients, rvecs, tvecs = \
cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
```
这里返回的结果包括重投影误差(ret),相机内参(camera_matrix),径向切向失真(distortion_coefficients)以及其他旋转和平移矢量(rvecs,tvecs)。
#### 对新图像应用矫正
最后一步是对新的输入图像执行去畸变处理:
```python
def undistort_image(image_path):
img = cv2.imread(image_path)
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(
camera_matrix,
distortion_coefficients,
(w,h),
1,
(w,h))
dst = cv2.undistort(img, camera_matrix, distortion_coefficients, None, newcameramtx)
# 裁剪图像
x,y,w,h = roi
dst = dst[y:y+h,x:x+w]
return dst
corrected_img = undistort_image('test_image.jpg')
cv2.imwrite('output_undistorted.png', corrected_img)
```
该函数接收一张原始未修正过的测试图作为输入,输出经过去除桶形或枕形变形后的版本保存至文件系统中。
阅读全文
相关推荐


















