利用opencv3.4.1进行随机森林的分类

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

	//组织分类标签,三类,每类50个样本
	int labels[150];
	for (int i = 0; i < 50; i++)
		labels[i] = 1;
	for (int i = 50; i < 100; i++)
		labels[i] = 2;
	for (int i = 100; i < 150; i++)
		labels[i] = 3;
	Mat labelsMat(150, 1, CV_32SC1, labels);  //矩阵化,150*1的矩阵

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

	// 设置训练数据,把特征数据和标签数据放在一起
	Ptr tData = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);

	//创建分类器,并设置训练参数
	Ptr rtrees = RTrees::create();
	rtrees->setMaxDepth(10);
	rtrees->setMinSampleCount(10);
	rtrees->setRegressionAccuracy(0);
	rtrees->setUseSurrogates(false);
	rtrees->setMaxCategories(15);
	rtrees->setPriors(Mat());
	rtrees->setCalculateVarImportance(true);
	rtrees->setActiveVarCount(4);
	rtrees->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER + (0.01f > 0 ? TermCriteria::EPS : 0), 100, 0.01f));
	//开始训练模型
	rtrees->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 = rtrees->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张图片

 

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