1. 程式人生 > >opencv 3.0 影象去畸變 undistortion

opencv 3.0 影象去畸變 undistortion

主要用到的是 initUndistortRectifyMap這個函式

在opencv中這個函式是用於 去除鏡頭畸變的影象拉伸

為了快速演算法:使用了座標查詢變和雙線性差值的方法

先上結果圖

原圖


去畸變至全圖



去畸變並保留最大圖


#include "opencv.hpp"

using namespace std;
using namespace cv;

void ReadIntrinsics(Mat &cameraMatrix, Mat &distCoeffs, Size &imageSize, char *IntrinsicsPath)
{
	bool FSflag = false;
	FileStorage readfs;

	FSflag = readfs.open(IntrinsicsPath, FileStorage::READ);
	if (FSflag == false) cout << "Cannot open the file" << endl;
	readfs["Camera_Matrix"] >> cameraMatrix;
	readfs["Distortion_Coefficients"] >> distCoeffs;
	readfs["image_Width"] >> imageSize.width;
	readfs["image_Height"] >> imageSize.height;

	cout << cameraMatrix << endl << distCoeffs << endl << imageSize << endl;

	readfs.release();
}

void Undistort_img(Mat map1, Mat map2, char *path)
{
	Mat img1, img2;
	img1 = imread(path);
	if (img1.empty()) cout << "Cannot open the image" << endl;
	remap(img1, img2, map1, map2, INTER_LINEAR);
// 	imwrite(path, img2);
	imshow("src img", img1);
	imshow("dst img", img2);
	waitKey();
}

void main()
{
	Mat	cameraMatrix, distCoeffs, map1, map2;
	Size imageSize;
	char * IntrinsicsPath = "Intrinsics.yml";
	ReadIntrinsics(cameraMatrix, distCoeffs, imageSize, IntrinsicsPath);

	// 去畸變並保留最大圖
	initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
		getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
		imageSize, CV_16SC2, map1, map2);

	Undistort_img(map1, map2, "E:/VS13/undistort/undistort/1.bmp");

	// 去畸變至全圖
	initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), Mat(),
		imageSize, CV_16SC2, map1, map2);

    Undistort_img(map1, map2, "E:/VS13/undistort/undistort/1.bmp");
}