在Opencv中,有关于KNN函数的类,具体定义如下:
class CvKNearest : public CvStatModel //继承自ML库中的统计模型基类
{
public:
CvKNearest();//无参构造函数
virtual ~CvKNearest(); //虚函数定义
CvKNearest( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx=0, bool _is_regression=false, int max_k=32 );//有参构造函数
virtual bool train( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx=0, bool is_regression=false,
int _max_k=32, bool _update_base=false );
virtual float find_nearest( const CvMat* _samples, int k, CvMat* results,
const float** neighbors=0, CvMat* neighbor_responses=0, CvMat* dist=0 ) const;
virtual void clear();
int get_max_k() const;
int get_var_count() const;
int get_sample_count() const;
bool is_regression() const;
protected:
...
};
——————————————————————————————————————————————————————————
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <opencv2/ml/ml.hpp>
#include <iostream>
#include <vector>
#include <math.h>
#include <string.h>
#include <fstream>
using namespace std;
using namespace cv;
int main()
{
CvKNearest knn;
float ar[3][3] = {{0,1,1},{2,3,4},{3,4,5}}; //训练数据
Mat traindata, respons;
traindata = Mat(3,3,CV_32F,ar);
float results[3] = {3,2,1};
respons = Mat(1,3,CV_32F,results);<span style="white-space:pre"> </span>//对训练的数据进行分类标定,类别为3,2,1
knn.train(traindata ,respons,Mat(),false,5);
float ar2[1][3] = {2,1,3}; //待预测的数据
Mat test = Mat(1,3,CV_32F,ar2);
float a = knn.find_nearest(test,1); //根据训练好的KNN 进行预测数据的类别
cout<<"类别为:"<<a<<endl;<span style="white-space:pre"> //返回类别值
waitKey();
return 0;
}
后期会做图片特征值的KNN训练,敬请期待。