现在的位置: 首页 > 综合 > 正文

opencv做的ORB实现的目标匹配

2018年02月20日 ⁄ 综合 ⁄ 共 2471字 ⁄ 字号 评论关闭
//加了透射变换 ,滤除错误匹配点
#include <stdio.h>
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include <fstream>
#include <string>
using namespace cv;
using namespace std;
//透射变换
bool refineMatchesWithHomography
(
 const std::vector<cv::KeyPoint>& queryKeypoints,
 const std::vector<cv::KeyPoint>& trainKeypoints, 
 float reprojectionThreshold,
 std::vector<cv::DMatch>& matches,
 cv::Mat& homography
 )
{
 const int minNumberMatchesAllowed = 5;
 if (matches.size() < minNumberMatchesAllowed)
  return false;
 // Prepare data for cv::findHomography
 std::vector<cv::Point2f> srcPoints(matches.size());
 std::vector<cv::Point2f> dstPoints(matches.size());
 for (size_t i = 0; i < matches.size(); i++)
 {
  srcPoints[i] = trainKeypoints[matches[i].trainIdx].pt;
  dstPoints[i] = queryKeypoints[matches[i].queryIdx].pt;
 }
 // Find homography matrix and get inliers mask
 std::vector<unsigned char> inliersMask(srcPoints.size());
 homography = cv::findHomography(srcPoints, 
  dstPoints, 
  CV_FM_RANSAC, 
  reprojectionThreshold, 
  inliersMask);
 std::vector<cv::DMatch> inliers;
 for (size_t i=0; i<inliersMask.size(); i++)
 {
  if (inliersMask[i])
   inliers.push_back(matches[i]);
 }
 matches.swap(inliers);
 return matches.size() > minNumberMatchesAllowed;
}
//main函数
int main(int argc, char* argv[])
{
	// Process command line arguments
         argv[1]="src_image//p001//frame0001Person02.png";           //the first image
	argv[2]="src_image//p001//frame0006Person02.png";           //the second image 
	string im1_name = argv[1];              // 第一幅图像路径
	string im2_name = argv[2];              // 第二幅图像路径
	Mat img_1=imread(im1_name);
	Mat img_2=imread(im2_name);
	IplImage* img1=cvLoadImage( im1_name.c_str(), -1 );
	IplImage* img2=cvLoadImage( im2_name.c_str(), -1 );
	if (!img_1.data || !img_2.data ||!img1 ||!img2)
	{
		cout<<"one of images was empty!"<<endl;
		return 0;
	}
	
	ORB orb_1(500,1.2f,8,31,0,2,ORB::HARRIS_SCORE,31);
	ORB orb_2(500,1.2f,8,31,0,2,ORB::HARRIS_SCORE,31);
	vector<KeyPoint> keypoint_1;
	vector<KeyPoint> keypoint_2;
	Mat descroptor_1;
	Mat descroptor_2; 
	orb_1(img_1,Mat(),keypoint_1,descroptor_1,false);
	orb_1(img_2,Mat(),keypoint_2,descroptor_2,false);

	Mat outimg;     //用于显示结果
	vector<DMatch>matches,Goodmatches; //存储配对记录
	BFMatcher bfmatcher(NORM_HAMMING,true);
	bfmatcher.match(descroptor_1,descroptor_2,matches);
	Mat H;
	if(! refineMatchesWithHomography(keypoint_1,keypoint_2,3,matches,H) )
		printf("refineMatchesWithHomography failed!\n");	
        	drawMatches( img_1, keypoint_1,img_2, keypoint_2, matches, outimg);
	imshow("matching result", outimg);//显示匹配结果
	printf("total matches: %d\n",Goodmatches.size());
	imwrite("RESULT.jpg",outimg);  //保存匹配结果
	cvWaitKey();
	return 0; 
}

抱歉!评论已关闭.