【反畸变操作】-【摄像机投影仪三维形貌测量(附C++代码)】-【5】

本科马上就要结束,忙于旅游和写论文。昨晚毕设之后静下心来,学习点自己喜欢的东西,前提是要把博客更完。这篇文章讲图像的反畸变操作。

我们知道相机拍摄的图像是含有畸变的,但是如果我们想要消除畸变就必须先知道相机的畸变参数,这从相机标定中可以得出。反畸变又称图像矫正,opencv自带函数initUndistortRectifyMap(),但是我还是建议大家手写一下这个函数,下面的代码是我借鉴网上一位大佬的代码,很久了已经忘记在哪看的了就先不表明来源了,抱歉。

#include"myUndistortPoints.h"
#include
#include

using namespace std;

/*反畸变畸变函数
@src:原图像角点集合
@dst:保存理想图像角点集合
@cameraMatrix:相机内参
@distortionCoeff:畸变参数矩阵
*/
int myUndistortPoints(const vector & src, vector & dst,
	const cv::Mat & cameraMatrix, const cv::Mat & distortionCoeff)
{
	dst.clear();
	double fx = cameraMatrix.at(0, 0);
	double fy = cameraMatrix.at(1, 1);
	double ux = cameraMatrix.at(0, 2);
	double uy = cameraMatrix.at(1, 2);

	double k1 = distortionCoeff.at(0, 0);
	double k2 = distortionCoeff.at(0, 1);
	double p1 = distortionCoeff.at(0, 2);
	double p2 = distortionCoeff.at(0, 3);
	double k3 = distortionCoeff.at(0, 4);
	double k4 = 0;
	double k5 = 0;
	double k6 = 0;

	for (unsigned int i = 0; i < src.size(); i++)
	{
		const cv::Point2d & p = src[i];
		//首先进行坐标转换;
		double xDistortion = (p.x - ux) / fx;
		double yDistortion = (p.y - uy) / fy;

		double xCorrected, yCorrected;

		double x0 = xDistortion;
		double y0 = yDistortion;

		//这里使用迭代的方式进行求解,因为根据2中的公式直接求解是困难的,所以通过设定初值进行迭代,这也是OpenCV的求解策略;
		for (int j = 0; j < 20; j++)
		{
			double r2 = xDistortion * xDistortion + yDistortion * yDistortion;

			double distRadialA = 1 / (1. + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2);
			double distRadialB = 1. + k4 * r2 + k5 * r2 * r2 + k6 * r2 * r2 * r2;

			double deltaX = 2. * p1 * xDistortion * yDistortion + p2 * (r2 + 2. * xDistortion * xDistortion);
			double deltaY = p1 * (r2 + 2. * yDistortion * yDistortion) + 2. * p2 * xDistortion * yDistortion;

			xCorrected = (x0 - deltaX)* distRadialA * distRadialB;
			yCorrected = (y0 - deltaY)* distRadialA * distRadialB;

			xDistortion = xCorrected;
			yDistortion = yCorrected;
		}

		//进行坐标变换;
		xCorrected = xCorrected * fx + ux;
		yCorrected = yCorrected * fy + uy;

		dst.push_back(cv::Point2d(xCorrected, yCorrected));
	}
	return 0;
}

 

你可能感兴趣的:(三维重建)