OpenCV 3 KNN implementation

Piotr Maciejewski picture Piotr Maciejewski · Jan 20, 2015 · Viewed 11.3k times · Source

As you may know, many things changed in OpenCV 3. In previous verion of OpenCV I used to do it that way:

Mat trainData(classes * samples, ImageSize, CV_32FC1);
Mat trainClasses(classes * samples, 1, CV_32FC1);
KNNLearning(&trainData, &trainClasses); //learning function
KNearest knearest(trainData, trainClasses); //creating

//loading input image
Mat input = imread("input.jpg");

//digital recognition
learningTest(input, knearest);//test

Also I found an example how to figured it out, but I still have errors in create function:

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);

Can you please provide me with information, how to rewrite the actual code of KNearest to openCV 3 properly?

Answer

DanBC picture DanBC · Jun 22, 2015

The API has changed once again since @aperture-laboratories answer. I hope they keep up with the documentation when they release new features or changes in the future.

A working example is as follows

using namespace cv::ml;

//Be sure to change number_of_... to fit your data!
Mat matTrainFeatures(0,number_of_train_elements,CV_32F);
Mat matSample(0,number_of_sample_elements,CV_32F);

Mat matTrainLabels(0,number_of_train_elements,CV_32F);
Mat matSampleLabels(0,number_of_sample_elements,CV_32F);

Mat matResults(0,0,CV_32F);

//etcetera code for loading data into Mat variables suppressed

Ptr<TrainData> trainingData;
Ptr<KNearest> kclassifier=KNearest::create();

trainingData=TrainData::create(matTrainFeatures,
                        SampleTypes::ROW_SAMPLE,matTrainLabels);



kclassifier->setIsClassifier(true);
kclassifier->setAlgorithmType(KNearest::Types::BRUTE_FORCE);
kclassifier->setDefaultK(1);

kclassifier->train(trainingData);
kclassifier->findNearest(matSample,kclassifier->getDefaultK(),matResults);

//Just checking the settings
cout<<"Training data: "<<endl
    <<"getNSamples\t"<<trainingData->getNSamples()<<endl
    <<"getSamples\n"<<trainingData->getSamples()<<endl
    <<endl;

cout<<"Classifier :"<<endl
    <<"kclassifier->getDefaultK(): "<<kclassifier->getDefaultK()<<endl
    <<"kclassifier->getIsClassifier()   : "<<kclassifier->getIsClassifier()<<endl   
    <<"kclassifier->getAlgorithmType(): "<<kclassifier->getAlgorithmType()<<endl
    <<endl;

//confirming sample order
cout<<"matSample: "<<endl
    <<matSample<<endl
    <<endl;

//displaying the results
cout<<"matResults: "<<endl
    <<matResults<<endl
    <<endl;

//etcetera ending for main function