10 OpenCV 机器学习和深度学习

首页



OpenCV 4 中有两个相关的模块,一个是 Machine Learning (ml) 和 Deep Neural Networks (dnn). ml中集成了大量传统机器学习的算法,开发者可以对其中的算法进行标准化的使用和访问, 不过也有一些机器学习算法没有集中在ml中,因为这些算法在OpenCV的ml尚未设计之前就已经存在于OpenCV中,后面可能也会被移进ml中. dnn中集成了深度神经网络相关的算法.




K均值

K均值(Kmeans)是最简单的聚类方法之一,是一种无监督学习. 其原理是通过指定种类数目对数据进行聚类.

/**
 * @author IYATT-yx
 * @date 2021-2-10
 * @brief K均值分类点集
 */
#include "opencv2/opencv.hpp"
#include 
#include 

int main()
{
     
	// 生成背景图
	cv::Mat img(500, 500, CV_8UC3, cv::Scalar(255, 255, 255));

	// 置随机数种子
	cv::RNG rng(static_cast<unsigned>(time(NULL)));

	// 设置三种颜色
	cv::Scalar color[3] =
	{
     
		cv::Scalar(0,0,255),
		cv::Scalar(255, 0, 0),
		cv::Scalar(255, 0, 255)
	};

	// 设置三个点集, 每个点集中点的数目随机
	int points1 = rng.uniform(20, 250);
	int points2 = rng.uniform(20, 250);
	int points3 = rng.uniform(20, 250);
	int pointsNum = points1 + points2 + points3;
	cv::Mat points(pointsNum, 1, CV_32FC2);

	int i = 0;
	for (; i < points1; ++i)
	{
     
		cv::Point2f pts;
		pts.x = static_cast<float>(rng.uniform(100, 200));
		pts.y = static_cast<float>(rng.uniform(100, 200));
		points.at<cv::Point2f>(i, 0) = pts;
	}
	for (; i < points1 + points2; ++i)
	{
     
		cv::Point2f pts;
		pts.x = static_cast<float>(rng.uniform(150, 300));
		pts.y = static_cast<float>(rng.uniform(200, 255));
		points.at<cv::Point2f>(i, 0) = pts;
	}
	for (; i < points1 + points2 + points3; ++i)
	{
     
		cv::Point2f pts;
		pts.x = static_cast<float>(rng.uniform(100, 230));
		pts.y = static_cast<float>(rng.uniform(180, 350));
		points.at<cv::Point2f>(i, 0) = pts;
	}

	// K均值
	cv::Mat labels, centers;
	cv::kmeans(points, 3, labels, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 10, 0.1),
				3, cv::KMEANS_PP_CENTERS, centers);

	// 根据分类为每个点设置不同的颜色
	img = cv::Scalar::all(125);
	for (int j = 0; j < pointsNum; ++j)
	{
     
		int index = labels.at<int>(j);
		cv::Point point = points.at<cv::Point2f>(j);
		cv::circle(img, point, 2, color[index], -1, 4);
	}

	// 以每个聚类的中心为圆心绘制圆并标出圆心坐标
	for (int j = 0; j < centers.rows; ++j)
	{
     
		int x = static_cast<int>(centers.at<float>(j ,0));
		int y = static_cast<int>(centers.at<float>(j, 1));
		cv::circle(img, cv::Point(x, y), 50, color[j], 1, cv::LINE_AA);
		cv::putText(img, "center: (" + std::to_string(x) + "," + std::to_string(y) + ")", cv::Point(x, y), cv::FONT_HERSHEY_SCRIPT_SIMPLEX,
					1, cv::Scalar(0, 0, 255));
	}

	cv::imshow("K近邻点集分类结果", img);
	cv::waitKey(0);
}

10 OpenCV 机器学习和深度学习_第1张图片

你可能感兴趣的:(10 OpenCV 机器学习和深度学习)