【Opencv】opencv中实践机器学习KNN算法

6 篇文章 0 订阅
5 篇文章 0 订阅

在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训练,敬请期待。


                
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值