图像畸变校正常用于计算机视觉、摄影测量学和机器人导航等领域,能够修正因镜头光学特性或传感器排列问题导致的图像失真。下面我将介绍几种常用的图像畸变校正算法,并提供Python实现和测试用例。
常用算法及Python实现
1. 径向畸变校正
径向畸变是最常见的畸变类型,表现为图像中心区域正常,边缘区域出现拉伸或压缩。校正公式如下:
import numpy as np
import cv2
from matplotlib import pyplot as plt
def correct_radial_distortion(image, k1, k2, k3=0):
"""
校正图像的径向畸变
参数:
image: 输入的畸变图像
k1, k2, k3: 径向畸变系数
返回:
corrected_image: 校正后的图像
"""
h, w = image.shape[:2]
# 创建网格坐标
x, y = np.meshgrid(np.arange(w), np.arange(h))
x_c, y_c = w / 2, h / 2 # 图像中心
# 计算离中心的距离
r = np.sqrt((x - x_c)**2 + (y - y_c)**2)
# 径向畸变校正公式
x_distorted = (x - x_c) * (1 + k1 * r**2 + k2 * r**4 + k3 * r**6) + x_c
y_distorted = (y - y_c) * (1 + k1 * r**2 + k2 * r**4 + k3 * r**6) + y_c
# 使用双线性插值进行重采样
corrected_image = np.zeros_like(image)
# 处理整数坐标
x_distorted_int = np.clip(x_distorted.astype(int), 0, w - 1)
y_distorted_int = np.clip(y_distorted.astype(int), 0, h - 1)
# 应用校正
if len(image.shape) == 3: # 彩色图像
corrected_image[y, x] = image[y_distorted_int, x_distorted_int]
else: # 灰度图像
corrected_image[y, x] = image[y_distorted_int, x_distorted_int]
return corrected_image
# 测试用例
def test_radial_distortion():
# 创建测试图像(棋盘格)
test_image = np.zeros((400, 400), dtype=np.uint8)
for i in range(8):
for j in range(8):
if (i + j) % 2 == 0:
test_image[i*50:(i+1)*50, j*50:(j+1)*50] = 255
# 引入径向畸变(k1=0.00005, k2=0.0000002)
distorted_image = correct_radial_distortion(test_image, 0.00005, 0.0000002)
# 校正径向畸变
corrected_image = correct_radial_distortion(distorted_image, -0.00005, -0.0000002)
# 显示结果
plt.figure(figsize=(15, 5))
plt.subplot(131), plt.imshow(test_image, cmap='gray')
plt.title('原始图像'), plt.axis('off')
plt.subplot(132), plt.imshow(distorted_image, cmap='gray')
plt.title('畸变图像'), plt.axis('off')
plt.subplot(133), plt.imshow(corrected_image, cmap='gray')
plt.title('校正图像'), plt.axis('off')
plt.show()
# 运行测试
test_radial_distortion()
2. 切向畸变校正
切向畸变是由于镜头与图像传感器不平行引起的,表现为图像局部区域的倾斜。校正公式如下:
def correct_tangential_distortion(image, p1, p2):
"""
校正图像的切向畸变
参数:
image: 输入的畸变图像
p1, p2: 切向畸变系数
返回:
corrected_image: 校正后的图像
"""
h, w = image.shape[:2]
# 创建网格坐标
x, y = np.meshgrid(np.arange(w), np.arange(h))
x_c, y_c = w / 2, h / 2 # 图像中心
# 计算离中心的距离
r = np.sqrt((x - x_c)**2 + (y - y_c)**2)
# 切向畸变校正公式
x_distorted = (x - x_c) + (2 * p1 * (x - x_c) * (y - y_c) + p2 * (r**2 + 2 * (x - x_c)**2)) + x_c
y_distorted = (y - y_c) + (p1 * (r**2 + 2 * (y - y_c)**2) + 2 * p2 * (x - x_c) * (y - y_c)) + y_c
# 使用双线性插值进行重采样
corrected_image = np.zeros_like(image)
# 处理整数坐标
x_distorted_int = np.clip(x_distorted.astype(int), 0, w - 1)
y_distorted_int = np.clip(y_distorted.astype(int), 0, h - 1)
# 应用校正
if len(image.shape) == 3: # 彩色图像
corrected_image[y, x] = image[y_distorted_int, x_distorted_int]
else: # 灰度图像
corrected_image[y, x] = image[y_distorted_int, x_distorted_int]
return corrected_image
# 测试用例
def test_tangential_distortion():
# 创建测试图像(棋盘格)
test_image = np.zeros((400, 400), dtype=np.uint8)
for i in range(8):
for j in range(8):
if (i + j) % 2 == 0:
test_image[i*50:(i+1)*50, j*50:(j+1)*50] = 255
# 引入切向畸变(p1=0.001, p2=0.0008)
distorted_image = correct_tangential_distortion(test_image, 0.001, 0.0008)
# 校正切向畸变
corrected_image = correct_tangential_distortion(distorted_image, -0.001, -0.0008)
# 显示结果
plt.figure(figsize=(15, 5))
plt.subplot(131), plt.imshow(test_image, cmap='gray')
plt.title('原始图像'), plt.axis('off')
plt.subplot(132), plt.imshow(distorted_image, cmap='gray')
plt.title('畸变图像'), plt.axis('off')
plt.subplot(133), plt.imshow(corrected_image, cmap='gray')
plt.title('校正图像'), plt.axis('off')
plt.show()
# 运行测试
test_tangential_distortion()
3. 使用OpenCV进行相机标定与畸变校正
实际应用中,通常使用OpenCV提供的相机标定功能来自动计算畸变系数:
def camera_calibration_and_undistortion():
"""
使用OpenCV进行相机标定和图像畸变校正
"""
# 准备对象点,如 (0,0,0), (1,0,0), (2,0,0) ..., (7,5,0)
objp = np.zeros((6*8, 3), np.float32)
objp[:, :2] = np.mgrid[0:8, 0:6].T.reshape(-1, 2)
# 存储对象点和图像点的数组
objpoints = [] # 3D点在现实世界中的坐标
imgpoints = [] # 2D点在图像平面中的坐标
# 生成模拟标定图像(通常需要使用多幅图像)
images = []
for i in range(5):
img = np.zeros((480, 640), dtype=np.uint8)
# 生成模拟的棋盘格角点
corners = np.zeros((48, 2), dtype=np.float32)
for j in range(48):
x = 50 + (j % 8) * 60 + np.random.randint(-5, 6) # 添加随机畸变
y = 50 + (j // 8) * 60 + np.random.randint(-5, 6)
corners[j] = [x, y]
imgpoints.append(corners)
objpoints.append(objp)
# 在图像上绘制角点
for corner in corners:
cv2.circle(img, (int(corner[0]), int(corner[1])), 5, 255, -1)
images.append(img)
# 相机标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, images[0].shape[::-1], None, None)
# 生成测试图像
test_img = np.zeros((480, 640), dtype=np.uint8)
for i in range(8):
for j in range(6):
cv2.circle(test_img, (100 + i * 60, 100 + j * 60), 10, 255, -1)
# 畸变校正
h, w = test_img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
undistorted_img = cv2.undistort(test_img, mtx, dist, None, newcameramtx)
# 显示结果
plt.figure(figsize=(10, 5))
plt.subplot(121), plt.imshow(test_img, cmap='gray')
plt.title('畸变图像'), plt.axis('off')
plt.subplot(122), plt.imshow(undistorted_img, cmap='gray')
plt.title('校正图像'), plt.axis('off')
plt.show()
# 返回标定结果
return mtx, dist
# 运行相机标定和畸变校正
camera_matrix, distortion_coeffs = camera_calibration_and_undistortion()
print("相机内参矩阵:\n", camera_matrix)
print("畸变系数:\n", distortion_coeffs)
算法解释
-
径向畸变校正:
- 径向畸变是最常见的畸变类型,表现为图像中心区域正常,边缘区域出现拉伸或压缩。
- 校正公式基于多项式模型,通过径向畸变系数(k1, k2, k3)来调整像素位置。
-
切向畸变校正:
- 切向畸变是由于镜头与图像传感器不平行引起的,表现为图像局部区域的倾斜。
- 校正公式使用切向畸变系数(p1, p2)来调整像素位置。
-
相机标定与OpenCV实现:
- 实际应用中,通常使用已知的标定板(如棋盘格)来计算相机的内参矩阵和畸变系数。
- OpenCV提供了完整的相机标定和畸变校正功能,能够自动计算所有参数并进行图像校正。
以上代码实现了常见的图像畸变校正算法,并提供了测试用例来验证算法的有效性。在实际应用中,你可能需要根据具体的相机型号和场景来调整参数。