机器学习---opencv实现简单的KNN算法

注意:我的OpenCV的版本是3.0.0,可能是版本的原因吧,从网上找的测试程序一直出错。一个简单的Demo例子。

#include
#include   
#include   
#include     
#include
#include "ml.hpp"
#include "highgui.h"
#include 
#include 

using namespace cv;
using namespace std;
using namespace cv::ml;

int main()
{
	float labels[10] = { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 };
	Mat labelsMat(10, 1, CV_32FC1, labels);
	cout << labelsMat << endl;
	cout << labelsMat.size() << endl;
	float trainingData[10][2];
	int k = 5;
	srand(time(0));
	for (int i = 0; i<5; i++){
		trainingData[i][0] = rand() % 255 + 1;
		trainingData[i][1] = rand() % 255 + 1;
		trainingData[i + 5][0] = rand() % 255 + 255;
		trainingData[i + 5][1] = rand() % 255 + 255;
	}
	Mat trainingDataMat(10, 2, CV_32FC1, trainingData);
	cout << trainingDataMat << endl;

	KNearest::Params params;
	params.defaultK = 5;
	params.isclassifier = true;

	Ptr knn;
	knn = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);
	Ptr knn1;
	knn1 = StatModel::train(knn, params);
	
	int width = 512, height = 512;
	Mat image = Mat::zeros(height, width, CV_8UC3);
	Mat testlabelMat1 = Mat::zeros(1,height*width, CV_8UC3);
	Vec3b green(0, 255, 0), blue(255, 0, 0);

	for (int i = 0; i < image.rows; ++i)
	{
		for (int j = 0; j < image.cols; ++j)
		{
			const Mat sampleMat = (Mat_(1, 2) << i, j);

			float r = knn1->predict(sampleMat);
			if (r != 0){
				image.at(j, i) = green;
			}
			else
				image.at(j, i) = blue;
		}
	}
	for (int i = 0; i<5; i++){
		circle(image, Point(trainingData[i][0], trainingData[i][1]),
			5, Scalar(0, 0, 0), -1, 8);
		circle(image, Point(trainingData[i + 5][0], trainingData[i + 5][1]),
			5, Scalar(255, 255, 255), -1, 8);
	}
	imshow("KNN Simple Example", image); 
	waitKey(10000);
	
	waitKey(0);

Demo 的结果:

机器学习---opencv实现简单的KNN算法_第1张图片机器学习---opencv实现简单的KNN算法_第2张图片

你可能感兴趣的:(机器学习)