1. 程式人生 > >Opencv學習筆記 ---opencv生成攝像頭標定棋盤

Opencv學習筆記 ---opencv生成攝像頭標定棋盤

由於3D重建跟雙目視覺的需要,
對標定棋盤圖的生成C++程式碼如下(只需修改棋盤的角點數x、y即可改變棋盤大小):

Opencv 1.x版本:

#include <cv.h>  
#include <highgui.h>  

void main()
{
	int y = 6;			//所生成的棋盤格的角點個數y
	int x = 4;			//所生成的棋盤格的角點個數x 
	IplImage *img;
	int cube = 150;        //棋盤格大小,畫素為單位 
	int dy = y + 1;       //棋盤格數目dy
	int dx = x + 1; 	  //棋盤格數目dx
	img = cvCreateImage(cvSize(dy * cube,dx * cube), IPL_DEPTH_8U, 1);
	//初始化影象
	for (int i = 0; i< dx; i++)
		for (int j = 0; j< dy; j++)
		{
			for (int m = i*cube; m<(i + 1)*cube; m++)
				for (int n = j*cube; n<(j + 1)*cube; n++)
					((uchar *)(img->imageData + m * img->widthStep))[n] = 255;
			//*(img->imageData+m*img->widthStep+n)=255;  
		}
	//繪畫棋盤格
	int flag = 0;
	for (int i = 0; i< dx; i++)
	for (int j = 0; j< dy; j++)
	{
		flag = (i + j) % 2;
		if (flag == 0)
		{
			for (int m = i*cube; m<(i + 1)*cube; m++)
			for (int n = j*cube; n<(j + 1)*cube; n++)
				((uchar *)(img->imageData + m * img->widthStep))[n] = 0;
			//*(img->imageData+m*img->widthStep+n)=255;  
		}
	}
	//生成標定圖
	//cvSaveImage("ChessBoard.bmp", img);
	cvNamedWindow("ChessBoard", 1);
	cvShowImage("ChessBoard", img);
	cvWaitKey(0);

	cvReleaseImage(&img);
	cvDestroyWindow("ChessBoard");
}

Opencv 2.x版本:(可以根據需要自己調節角點個數)
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
using namespace cv;
using namespace std;

int main(int argc,char* argv[])
{
	//A4紙大小  cols*rows = 630*891
	Mat img(630, 891, CV_8UC1, Scalar::all(0));
	int channel = img.channels();
	int cube = 90;

	for (int j = 0; j<img.rows; j++)
	{
		uchar* data = img.ptr<uchar>(j);
		for (int i = 0; i<img.cols*channel; i += channel)
		{
			if ((i / channel / cube + j / cube) % 2)
			{
				data[i / channel*channel + 0] = 255;
				data[i / channel*channel + 1] = 255;
				data[i / channel*channel + 2] = 255;
			}
		}
	}
	imshow("img", img);
	imwrite("board.jpg", img);
	waitKey(0);
	return 0;
}