本文通过摄像头参数(fx,fy,cx,cy,k1,k2,p1,p2,p3(标定得到))去矫正摄像头拍出来的图像畸变
详细代码在底部
首先
这里我们先介绍两个函数:他们都可以用来矫正畸变,但是一个是输入是Mat型,一个输入是IplImage* 型
本文用Mat格式读取图像,故采用第一个函数。
undistort() //用于Mat图像
cvUndistort() //用于 IplImage* 图像
其次
标定一下摄像头,得到参数矩阵。(我用matlab标定工具箱搞出来的~)
Matlab2019 标定工具箱结果
再次
这里通过paramtersInit()将参数转换为系数阵
然后传入到undistort里面去,这就结束了~
效果
畸变矫正前/后
代码
```
#include <iostream>
#include<opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
Mat matrix;
Mat coeff;
Mat new_matrix;
double fx = 682.421509, fy = 682.421509, cx = 633.947449, cy = 404.559906;
double k1k2Distortion[2] = {-0.15656,-0.00404};
double p1p2p3Distortion[3] = {-0.00078,-0.00048,0.00000};
using namespace cv;
using namespace std;
void paramtersInit();//将参数转换为系数阵
int main()
{
cv::Mat srcMat, dstMat;
paramtersInit();
srcMat = imread("img.jpg");
undistort(srcMat, dstMat, matrix, coeff, new_matrix);
imwrite("undistortImg.png", dstMat);
imshow("front", srcMat);
imshow("after",dstMat);
waitKey(0);
system("pause");
return 0;
}
void paramtersInit()
{
matrix = Mat(3, 3, CV_64F);
matrix.at<double>(0, 0) = fx;
matrix.at<double>(0, 1) = 0;
matrix.at<double>(0, 2) = cx;
matrix.at<double>(1, 0) = 0;
matrix.at<double>(1, 1) = fy;
matrix.at<double>(1, 2) = cy;
matrix.at<double>(2, 0) = 0;
matrix.at<double>(2, 1) = 0;
matrix.at<double>(2, 2) = 1;
coeff = Mat(1, 4, CV_64F);
coeff.at<double>(0, 0) = k1k2Distortion[0];
coeff.at<double>(0, 1) = k1k2Distortion[1];
coeff.at<double>(0, 2) = p1p2p3Distortion[0];
coeff.at<double>(0, 3) = p1p2p3Distortion[1];
}
```












网友评论