利用opencv3.4.1进行正态贝叶斯分类

 当样本的特征向量满足多维正态分布时,对于分类任务,可以使用正态贝叶斯分类方法,进行训练。使用OpenCV3.4.1中的ML模块,具体实现demo如下:

#include"pch.h"
#include
#include

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

int main()
{
	const int Kwidth = 512;
	const int Kheight = 512;

	//用于显示分类结果的图像
	Mat image = Mat::zeros(Kheight, Kwidth, CV_8UC3);

	//组织分类标签
	int labels[30];
	for (int i = 0; i < 10; i++)
		labels[i] = 1;
	for (int i = 10; i < 20; i++)
		labels[i] = 2;
	for (int i = 20; i < 30; i++)
		labels[i] = 3;
	Mat labelsMat(30, 1, CV_32SC1, labels);


	//组织训练数据,三类数据,每个数据点为二维特征向量
	float trainDataArray[30][2];
	RNG rng;
	for (int i = 0; i < 10; i++)
	{
		trainDataArray[i][0] = 250 + static_cast(rng.gaussian(30));
		trainDataArray[i][1] = 250 + static_cast(rng.gaussian(30));
	}
	for (int i = 10; i < 20; i++)
	{
		trainDataArray[i][0] = 150 + static_cast(rng.gaussian(30));
		trainDataArray[i][1] = 150 + static_cast(rng.gaussian(30));
	}
	for (int i = 20; i < 30; i++)
	{
		trainDataArray[i][0] = 320 + static_cast(rng.gaussian(30));
		trainDataArray[i][1] = 150 + static_cast(rng.gaussian(30));
	}
	Mat trainingDataMat(30, 2, CV_32FC1, trainDataArray);

	// 创建贝叶斯分类器
	Ptr model = NormalBayesClassifier::create();

	// 设置训练数据
	Ptr tData = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);

	//训练分类器
	model->train(tData);

	//对图像内所有512*512个背景点进行预测,不同的预测结果,图像背景区域显示不同的颜色
	Vec3b red(0,0,255), green(0, 255, 0), blue(255, 0, 0);
	for (int i = 0; i < image.rows; ++i)
		for (int j = 0; j < image.cols; ++j)
		{
			Mat sampleMat = (Mat_(1, 2) << j, i);  //生成测试数据
			float response = model->predict(sampleMat);  //进行预测,返回1或-1
			if (response == 1) 
				image.at(i, j) = red;
			else if (response == 2)
				image.at(i, j) = green;
			else
				image.at(i, j) = blue;
		}

	//把训练样本点,显示在图相框内
	for (int i = 0; i < trainingDataMat.rows; i++)
	{
		const float * v = trainingDataMat.ptr(i);
		Point pt = Point((int)v[0], (int)v[1]);
		if (labels[i] == 1) //不同的圆点,标记不同的颜色
			circle(image, pt, 5, Scalar::all(0), -1, 8);
		else if (labels[i] == 2)
			circle(image, pt, 5, Scalar::all(128), -1, 8);
		else 
			circle(image, pt, 5, Scalar::all(255), -1, 8);
	}

	//显示分类结果图像
	imshow("贝叶斯分类器示例", image);
	waitKey(0);

	return 0;
}

运行如上程序,结果如下:

利用opencv3.4.1进行正态贝叶斯分类_第1张图片

 

你可能感兴趣的:(数据挖掘&机器学习)