在进行摄像头校正过程中,踌躇了许久,现在写出来方便其他人。
1、首先利用matlab的摄像头校正工具箱,下载地址:http://www.vision.caltech.edu/bouguetj/calib_doc/index.html#examples
不得不说matlab非常强大。下载解压之后放到matlab目录下,如:D:\Program Files\MATLAB\R2009b
matlab的运行目录在此下在运行窗口运行calib_gui命令,出现gui窗口
之后的步骤参考http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/example.html第一个例子和http://blog.csdn.net/sunanger_wang/article/details/7744025
matlab得到所需参数之后opencv将参数存入xml文件,参考http://blog.csdn.net/ilyhlf5201314/article/details/14533013。剩余校正过程参考学习opencv的第十一章11.1例子。
自己的粘下:
#include "stdafx.h"
#include "opencv2/opencv.hpp"
#include "highgui.h"
#include "stdio.h"
#include "cxcore.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CvCapture* capture = cvCreateCameraCapture(0);
if (!capture)
{
fprintf(stderr,"Could not initialize captureing...\n");
return -1;
}
IplImage* Img = cvQueryFrame(capture);
if (!Img)
{
fprintf(stderr, "Could not catch image from capture...\n");
return 0;
}
cvShowImage("UN", Img);
//IplImage* col = 0;
//col = cvCreateImage(cvGetSize(Img), Img->depth, Img->nChannels);
//cvCopy(Img, col, NULL);
CvMat* intrinsic_matrix = cvCreateMat(3, 3, CV_32FC1);
CvMat* distortion_coeffs = cvCreateMat(5, 1, CV_32FC1);
CV_MAT_ELEM(*intrinsic_matrix,float,0,0) = 1.0f;
CV_MAT_ELEM(*intrinsic_matrix, float, 1, 1) = 1.0f;
float a[3][3]= { 1555.84462, 0, 566.84605, 0, 1661.99293, 666.76700, 0, 0, 1 };
float b[5][1] = { -0.19855, 0.05405, 0.00026, 0.00082, 0.00000};
cvInitMatHeader(intrinsic_matrix, 3, 3, CV_32FC1, a);
cvInitMatHeader(distortion_coeffs, 5, 1, CV_32FC1, b);
cvSave("Intrinsics.xml", intrinsic_matrix);
cvSave("Distortion.xml", distortion_coeffs);
CvMat* intrinsic = (CvMat*)cvLoad("Intrinsics.xml");
CvMat* distortion = (CvMat*)cvLoad("Distortion.xml");
IplImage* mapx = cvCreateImage(cvGetSize(Img),IPL_DEPTH_32F,1);//The x coordinate of the image
IplImage* mapy = cvCreateImage(cvGetSize(Img), IPL_DEPTH_32F, 1);//The y coordinate of the image
cvInitUndistortMap(intrinsic, distortion, mapx, mapy);//caculat the distorted and undistorted images
//run the camera to the screen,now show the raw and the undistorted image
while (Img)
{
IplImage *t = cvCloneImage(Img);
cvShowImage("Calibration", t);//show the raw image
cvRemap(t, Img, mapx, mapy);//undistort image
cvReleaseImage(&t);
cvShowImage("Undistorted", Img);//show the corrected image
int c = cvWaitKey(15);
if (c=='p')
{
c = 0;
while (c!='p'&&c!=27)
{
c = cvWaitKey(200);
}
}
if (c==27)
break;
Img = cvQueryFrame(capture);
}
cvDestroyAllWindows();
return 0;
}