1、首先需要使用Add Images提取棋盘格照片,导出相机参数。
2、使用Matlab代码矫正所有的畸变图片
3、矫正效果
这里需要注意两个点。径向畸变参数和相机内参矩阵。
这里的四个参数对应内参矩阵中各自参数的位置。
完整的代码如下:
% 设置文件夹路径
inputFolder = '自己的路径'; % 替换为实际的图片文件夹路径
outputFolder = '自己的路径'; % 替换为实际的输出文件夹路径
% 执行批量图像畸变校正
batchUndistortImages(inputFolder, outputFolder, cameraParams);
disp('批量矫正完成!');
function batchUndistortImages(inputFolder, outputFolder, cameraParams)
% 批量校正文件夹下的图像,并保存到另一个文件夹中。
% inputFolder: 包含输入图像的文件夹。
% outputFolder: 保存校正后图像的文件夹。
% cameraParams: 相机参数对象,包括内参矩阵和径向畸变参数。
% 获取输入文件夹中所有图像文件的列表
imageFiles = dir(fullfile(inputFolder, '*.jpg')); % 如果需要,可以更改文件扩展名
% 循环处理每个图像文件
for i = 1:numel(imageFiles)
% 读取图像
img = imread(fullfile(inputFolder, imageFiles(i).name));
% 图像矫正
undistorted_img = undistortImage(img, cameraParams.IntrinsicMatrix, cameraParams.RadialDistortion);
% 保存矫正后的图像到输出文件夹
[~, filename, ext] = fileparts(imageFiles(i).name);
outputFilename = fullfile(outputFolder, [filename '_undistorted' ext]);
imwrite(undistorted_img, outputFilename);
end
end
function undistorted_img = undistortImage(img, K, D)
% Corrects an image for lens distortion.
% K: 内参矩阵,用来归一化坐标的,给定的
% D: 径向畸变参数,给定的
[height, width, ~] = size(img);
%[height, width] = size(img);
%height = 1518;
%width = 2012;
fx = K(1,1);
fy = K(2,2);
cx = K(3,1);
cy = K(3,2);
% 创建一个与输入图像大小相同的空白图像
undistorted_img = uint8(zeros(height, width));
% 依次找到去畸变后的图像坐标(y,x)对应的畸变坐标
for y = 1:height
for x = 1:width
% 第一步,通过内参矩阵归一化畸变图像的坐标
x1 = (x-cx)/fx;
y1 = (y-cy)/fy;
% 第二步,通过径向畸变模型得到归一化的畸变坐标
r2 = x1^2 + y1^2;
x2 = x1 * (1 + D(1) * r2 + D(2) * r2^2);
y2 = y1 * (1 + D(1) * r2 + D(2) * r2^2);
% 第三步,坐标映射回去,去归一化,得到畸变坐标。
u = fx * x2 + cx; % 列
v = fy * y2 + cy; % 行
% 双线性插值,获取去畸变后的图像像素值
if u>=1 && v>=1 && u<=width && v<=height
x0 = floor(u);
y0 = floor(v);
dx = u - x0;
dy = v - y0;
% 双线性插值
undistorted_img(y,x) = (1-dx)*(1-dy)*img(y0,x0) + dx*(1-dy)*img(y0,x0+1) + (1-dx)*dy*img(y0+1,x0) + dx*dy*img(y0+1,x0+1);
end
end
end
end