新建data与data-jb文件夹,并将畸变待校正的图像放入到data中,运行以下代码即可进行图像的畸变校正,并输出畸变校正后的图像,保存到data-jb中。
##以下代码用于根据相机内参与畸变参数,对输入图像进行畸变校正,以输出畸变校正后的图像 import cv2 as cv import numpy as np import os import glob # 假设您已经从之前的标定过程中获得了以下参数,代入得到的参数 camera_matrix = np.array([[643.24580489, 0.0, 318.64488952], [0.0, 643.92943431, 236.75374833], [0.0, 0.0, 1.0]], dtype=np.float32) dist_coefs = np.array([-0.29706837, -0.22038399, 0.00303177, 0.00368427, 1.36565465], dtype=np.float32) # 指定要校正的图像文件夹路径 input_folder = 'C:/Users/zhao/Desktop/test/data'##输入路径 output_folder = 'C:/Users/zhao/Desktop/test/data-jb'##输出路径 # 确保输出文件夹存在 if not os.path.exists(output_folder): os.makedirs(output_folder) # 读取文件夹中的所有图像文件 image_files = glob.glob(os.path.join(input_folder, '*.jpg')) # 假设图像是JPEG格式 # 遍历所有图像文件 for image_file in image_files: # 读取图像 img = cv.imread(image_file) if img is None: print(f"Failed to load {image_file}") continue h, w = img.shape[:2] # 获取新的相机矩阵和ROI newcameramtx, roi = cv.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h)) # 对图像进行畸变校正 dst = cv.undistort(img, camera_matrix, dist_coefs, None, newcameramtx) # 裁剪图像 x, y, w, h = roi dst = dst[y:y+h, x:x+w] # 构建输出文件路径 file_name = os.path.basename(image_file) output_file = os.path.join(output_folder, file_name) # 保存校正后的图像 cv.imwrite(output_file, dst) print(f"Undistorted image written to: {output_file}") print('Done')