03-去畸变(矫正)¶
remap¶
- 读取相机矩阵、畸变系数
// 读取相机矩阵、畸变系数
cv::FileStorage fs("./calibration_in_params.yml", FileStorage::READ);
int image_width{0}, image_height{0};
fs["image_width"] >> image_width;
fs["image_height"] >> image_height;
Size image_size = Size(image_width, image_height);
Mat intrinsic_matrix, distortion_coeffs;
fs["cameraMatrix"] >> intrinsic_matrix;
fs["distCoeffs"] >> distortion_coeffs;
fs.release();
std::cout << intrinsic_matrix << std::endl;
std::cout << distortion_coeffs << std::endl;
std::cout << image_size << std::endl;
- 初始化去畸变纠正变换Map
// 初始化去畸变纠正变换Map
Mat map1, map2;
initUndistortRectifyMap(intrinsic_matrix, distortion_coeffs, Mat(),
intrinsic_matrix, image_size, CV_16SC2, map1, map2);
- 显示原图和去畸变后的图
cv::VideoCapture capture(0);
if (!capture.isOpened()) {
cout << "\nCouldn't open the camera\n";
return -1;
}
// 显示原图和去畸变后的图
while (true) {
Mat image, image0;
capture >> image0;
if (image0.empty()) {
break;
}
// 执行映射转换
remap(image0, image, map1, map2,
cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar());
imshow("original", image0);
imshow("undistorted", image);
if ((waitKey(30) & 255) == 27) {
break;
}
}
undistort¶
有时,我们只需要对一张图像进行去畸变,则可以使用更简洁的cv::undistort()
函数,可以更方便的计算映射关系病将之应用于单个图像。
void undistort(
InputArray src, // 输入图像
OutputArray dst, // 校正后的图像
InputArray cameraMatrix,// 标定矩阵
InputArray distCoeffs, // 畸变系数
InputArray newCameraMatrix = noArray() // 额外的偏移缩放矩阵
);
范例:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
// 读取相机矩阵、畸变系数
cv::FileStorage fs("./calibration_in_params.yml", FileStorage::READ);
int image_width{0}, image_height{0};
fs["image_width"] >> image_width;
fs["image_height"] >> image_height;
Size image_size = Size(image_width, image_height);
Mat intrinsic_matrix, distortion_coeffs;
fs["cameraMatrix"] >> intrinsic_matrix;
fs["distCoeffs"] >> distortion_coeffs;
fs.release();
std::cout << intrinsic_matrix << std::endl;
std::cout << distortion_coeffs << std::endl;
std::cout << image_size << std::endl;
const Mat &image0 = imread("./calib_chess_img/image_0.jpg", IMREAD_COLOR);
Mat image;
undistort(image0, image, intrinsic_matrix, distortion_coeffs);
imshow("original", image0);
imshow("undistorted", image);
waitKey();
return 0;
}