您的位置:首页 > 运维架构

opencv之生成BOW特征

2017-04-11 10:43 211 查看
最近正在学习opencv,看了两天的书了,刚好想要实现bow特征提取。

在官方文档上找到,地址点击打开链接

分两个步骤:

第一步,使用BOWKMeansTrainer
生成码书

第二步,对图像产生和码书对应的直方图(即bow特征)

// opencvTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<opencv2/features2d/features2d.hpp>
#include<opencv2/nonfree/nonfree.hpp>
#include<vector>
#include<fstream>

using namespace cv;
using namespace std;
const int  clusterNum = 10;
int main()
{
initModule_nonfree();

//get all image keypoints and discriptors
SiftFeatureDetector sift;
SiftDescriptorExtractor extractor;

vector<KeyPoint> p1, p2, p3;
Mat dp1, dp2, dp3;
Mat pic1 = imread("1.jpg",0);
Mat pic2 = imread("2.jpg",0);
Mat pic3 = imread("3.jpg",0);
if ( pic1.empty()||pic2.empty() || pic3.empty())
{
if (pic1.empty())
cout << "pic1 open failed" << endl;
if (pic2.empty())
cout << "pic2 open failed" << endl;
if (pic3.empty())
cout << "pic3 open failed" << endl;
return -1;
}
//get all picture's keypoints and descriptors
sift.detect(pic1, p1);
extractor.compute(pic1, p1, dp1);
sift.detect(pic2, p2);
extractor.compute(pic2, p2, dp2);
sift.detect(pic3, p3);
extractor.compute(pic3, p3, dp3);

//create the BOWKMeansTrainer object
BOWKMeansTrainer bow = BOWKMeansTrainer(clusterNum, TermCriteria(CV_TERMCRIT_ITER, 15, 0.1));

//add the descriptors to trainset

bow.add(dp1);
bow.add(dp2);
bow.add(dp3);
cout << "the count of the descriptors :" << bow.descripotorsCount() << endl;

// get the vocabulary
Mat vocabulary = bow.cluster();
cout << vocabulary << endl;
//create the bowExtractor
//Ptr<FeatureDetector>detector = FeatureDetector::create("SIFT");
Ptr<DescriptorExtractor> descriptorExtractor = DescriptorExtractor::create("SIFT");
Ptr<DescriptorMatcher> descriptorMatcher = DescriptorMatcher::create("BruteForce");
BOWImgDescriptorExtractor bowex = BOWImgDescriptorExtractor(descriptorExtractor, descriptorMatcher);
Mat bowfeatures;
bowex.setVocabulary(vocabulary);
bowex.compute(pic1, p1, bowfeatures);

cout << bowfeatures << endl;

return 0;

}



文章由liuzw1995 原创,转载请注明出处。  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv bow bag of features