1. 程式人生 > >opencv3中ORB演算法描述與匹配

opencv3中ORB演算法描述與匹配

#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>

using namespace cv;
using namespace std;

int main()
{
	Mat srcImage = imread("NIBook.jpg");
	imshow("【原圖】", srcImage);

	//對BGR空間的影象直接進行計算很費時間,所以,需要轉換為灰度圖
	Mat srcGrayImage;
	cvtColor(srcImage, srcGrayImage, CV_BGR2GRAY);

	//首先對兩幅影象進行特徵點的檢測和描述子的計算
	vector<KeyPoint> keyPoint1;
	ORB orb(400);
	orb.detect(srcGrayImage, keyPoint1);
	Mat descriImage1;
	orb.compute(srcGrayImage, keyPoint1, descriImage1);

	/****************************************************************/
	flann::Index flannIndex(descriImage1, flann::LshIndexParams(12, 20, 2), cvflann::FLANN_DIST_HAMMING);
	/****************************************************************/

	VideoCapture capture;
	capture.open(0);
	capture.set(CV_CAP_PROP_FRAME_WIDTH, 360);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT, 900);

	Mat frameImage, frameGrayImage;
	while (waitKey(1) != 27)
	{
		capture >> frameImage;

		//為了提高計算效率,將影象轉換為灰度影象
		cvtColor(frameImage, frameGrayImage, CV_BGR2GRAY);

		//計算特徵點和描述子
		vector<KeyPoint> keyPoints2;
		orb.detect(frameGrayImage, keyPoints2);
		Mat descriImage2;
		orb.compute(frameGrayImage, keyPoints2, descriImage2);

		/***************************************************************************************/
		Mat matchIndex(descriImage2.rows, 2, CV_32SC1);
		Mat matchDistance(descriImage2.rows, 2, CV_32SC1);
		flannIndex.knnSearch(descriImage2, matchIndex, matchDistance, 2, flann::SearchParams());
		/***************************************************************************************/

		//採集優秀的匹配點
		vector<DMatch> goodMatches;
		for (int i = 0; i < matchDistance.rows; i++)
		{
			//........................................................................
			if (matchDistance.at<float>(i, 0) < 0.6 * matchDistance.at<float>(i, 1))
			{
				DMatch midDMatch(i, matchIndex.at<int>(i, 0), matchDistance.at<float>(i, 0));
				goodMatches.push_back(midDMatch);
			}
		}

		Mat dstImage;
		drawMatches(frameImage, keyPoints2, srcImage, keyPoint1, goodMatches, dstImage);

		imshow("【結果圖】", dstImage);
	}

	return 0;
}