How to use bag of words to predict an image?

asked 2012-12-03 19:24:41 -0500

ipunished gravatar image

Hello,

Can anyone please tell me how to use the bag of words function in opencv? I want to use it on a folder of images; to train it such that if I use a sample image from that folder it should be able to recognize it.

While reading the only example online of this I was able to make a library / vocabulary. The code I used for that is below:

Ptr<FeatureDetector> features = FeatureDetector::create("SIFT");
Ptr<DescriptorExtractor> descriptors = DescriptorExtractor::create("SIFT");
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("FlannBased");

//defining terms for bowkmeans trainer
TermCriteria tc(MAX_ITER + EPS, 10, 0.001);
int dictionarySize = 1000;
int retries = 1;
int flags = KMEANS_PP_CENTERS;
BOWKMeansTrainer bowTrainer(dictionarySize, tc, retries, flags);

BOWImgDescriptorExtractor bowDE(descriptors, matcher);

//training data now
Mat features;
Mat img = imread("c:\\1.jpg", 0);
Mat img2 = imread("c:\\2.jpg", 0);
vector<KeyPoint> keypoints, keypoints2;
features->detect(img, keypoints);
features->detect(img2,keypoints2);
descriptor->compute(img, keypoints, features);
Mat features2;
descripto->compute(img2, keypoints2, features2);
bowTrainer.add(features);
bowTrainer.add(features2);

Mat dictionary = bowTrainer.cluster();
bowDE.setVocabulary(dictionary);

Now I believe this would create the dictionary. So is the system now trained? or will I have to use one of the machine learning functions to train it? If so can some one please give me a brief example of it?

Thank you

edit retag flag offensive close merge delete

Comments

checkout this link

lama123 gravatar imagelama123 ( 2016-05-27 01:04:24 -0500 )edit