Ask Your Question

How to use KNearest and ANN in OpenCV 3.0

asked 2015-01-14 11:32:39 -0500

user_OpenCV gravatar image

Hi, I have a problem. Don't know how to use KNearest Neighbour or ANN in OpenCV 3.0. I don't even know if any of mentioned class/method can be used in ver 3.0. I could't find any example of using neighter KNeares nor ANN. I would be appreciative for any help. I need it to recognize letters on license plate.

edit retag flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted

answered 2015-01-14 14:55:02 -0500

berak gravatar image

updated 2015-01-14 15:08:26 -0500

can't help you with ann, but here's KNearest:

Ptr<ml::KNearest>  knn(ml::KNearest::create());
Mat_<float> trainFeatures(6,4);
trainFeatures << 2,2,2,2,

Mat_<int> trainLabels(1,6);
trainLabels << 2,3,4,5,6,7;

knn->train(trainFeatures, ml::ROW_SAMPLE, trainLabels);

Mat_<float> testFeature(1,4);
testFeature<< 3,3,3,3;

int K=1;
Mat response,dist;
knn->findNearest(testFeature, K, noArray(), response, dist);
cerr << response << endl;
cerr << dist<< endl;

// K=1 

// K=4:
[3, 2, 4, 5]
[0, 4, 4, 16]
edit flag offensive delete link more


Thank you, the method is working properly. But I have a question, how to use this method when I want to train (use knn->train) the classifier and save learning vector find by this method. I want implemented 2 programs. The first program have learn KNN (used knn->train). The second program have find labels for my data (used knn->findNearest). Is it possible, or for each calling of the program I have to train a classifier again?

user_OpenCV gravatar imageuser_OpenCV ( 2015-01-17 06:28:21 -0500 )edit

sure possible. just use knn->save("my.yml") and knn->load("my.yml")

berak gravatar imageberak ( 2015-01-17 06:33:14 -0500 )edit

in my program, code above doesn't work. i need parameter in create func. Can you help?

pmdev gravatar imagepmdev ( 2015-01-18 15:10:00 -0500 )edit

In Android version"filename") isn't work, apk crash...

DanielQ gravatar imageDanielQ ( 2015-08-05 07:10:23 -0500 )edit

@DanielQ, are you sure, that's opencv3 running there ? (there is indeed no implemetation for in 2.4)

(and then - the 3.0 java version won't be able to load() the data, either way - seems you just can't use it on android)

berak gravatar imageberak ( 2015-08-05 07:22:21 -0500 )edit

@berak, I check file and actually isn't there save function, but when I write knn. CTRL+Space I have prompt with save function... But it isn't work

DanielQ gravatar imageDanielQ ( 2015-08-05 09:01:23 -0500 )edit

answered 2015-01-14 13:10:21 -0500

Doombot gravatar image

updated 2015-01-14 14:21:50 -0500

+++ OK, it appears that I misunderstood the OP's question and answered something that is true but not right on topic... So understand this is an answer about feature detectors, not on machine learning as the OP intended! Thanks for people in comments for pointing out ;) +++

Since OpenCV 3.0 "official release" is not out yet, the doc isn't that much available, so asking questions is a thing to do (well, it is what I have done).

Here is an example of knn match, which I think is another name for KNearest neighbours.

            // Number of neighbours
            int k = 2; 
            // Vector of DMatch containing the filtered results, only the best matches
            vector<DMatch> good_matches;
            // Vector containing a vector of DMatch (which contain the "k" nearest matches)
            vector<vector< DMatch >> matches;
            // Declaration of the matcher "3.0 style"
            Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");

            // Computation of the "k" nearest matches
            matcher -> knnMatch( objectDescriptors, sceneDescriptors, matches, k );

            /// Ratio test from Lowe-SIFT. It helps select the most relevant matches by doing a
            // ratio between each best and second best matches 

            if (matches[0].size() > 1)

                for (int i = 0; i < matches.size(); ++i)
                    const double ratio = 0.8; // As in Lowe's paper; can be tuned
                    if (matches[i][0].distance < ratio * matches[i][1].distance)

So at the end, you have a vector of DMatch indicating which matches are relevant according to a criterion, here, Lowe's ratio test. You may then use other techniques to continue your detection.

It assumes that prior to its execution, you have computed, for example, BRISK keypoint-descriptors for an object (model) and a scene (the picture on which you try to find the object). If you need more info on keypoint-descriptors, there are wide range of question on this site. If it is still obscure after, ask another question and people will gladly provide help :)

edit flag offensive delete link more


I'm not sure how to use it to recognize character(digit and letter). Maybe I didn't explain my problem as as should to. I need a way how to use module Machine Learning in OpenCV 3.0 (example: ANN_MLP or KNearest) learnt on the basis of vector of learning data. Unfortunately it has to be implemented in OpenCV 3.0.

user_OpenCV gravatar imageuser_OpenCV ( 2015-01-14 13:41:43 -0500 )edit

^^ would have been a nice answer about feature-detection, but imho, the KNearest from the ml module was meant here...

berak gravatar imageberak ( 2015-01-14 13:42:06 -0500 )edit

Yeah, I understand that is not what @user_OpenCV was looking for. in the end. I will add a warning but I guess I should let the answer here if anyone needs it. Hope someone else will profit from it? Or maybe I should only delete it...

Doombot gravatar imageDoombot ( 2015-01-14 14:18:11 -0500 )edit

answered 2015-01-18 15:08:00 -0500

pmdev gravatar image

updated 2015-01-19 17:16:33 -0500

I am trying to create empty KNearest like berak, but I still have an error! What is the parametr of func KNearest::creat?

I've found solution like below, but it still doesn't compile

Ptr<KNearest> knearestKdt = KNearest::create(ml::KNearest::Params(10, true, INT_MAX, ml::KNearest::KDTREE));
knearestKdt->train(trainData, ml::ROW_SAMPLE, trainLabels);
knearestKdt->findNearest(testData, 4, bestLabels);
edit flag offensive delete link more



the 'Params' one here ?

berak gravatar imageberak ( 2015-01-18 15:18:29 -0500 )edit

need a help with this Param. Please show me how to use this Param in create func.

pmdev gravatar imagepmdev ( 2015-01-18 17:08:20 -0500 )edit

please don't write an answer, when you got another question, put that into a comment instead

berak gravatar imageberak ( 2015-01-20 14:46:21 -0500 )edit

Hi, I got this error when running code showing upper. Can any body help me to solve it??


Naser gravatar imageNaser ( 2017-07-09 15:16:26 -0500 )edit

@Naser, please do not post ananswer, if you have a comment or question.. we also do not like screenshots.

berak gravatar imageberak ( 2017-07-09 21:32:45 -0500 )edit

Question Tools



Asked: 2015-01-14 11:32:39 -0500

Seen: 8,726 times

Last updated: Jan 19 '15