赞
踩
基于高斯函数的算法,通过混合单个或多个高斯函数,计算对应像素中概率,哪个分类的概率最高的,则属于哪个类别
GMM方法跟K - Means相比较,属于软分类
实现方法 - 期望最大化(E - M)
停止条件 - 收敛,或规定的循环次数
- #include<opencv2\core\core.hpp>
- #include<opencv2\highgui\highgui.hpp>
- #include<opencv2\imgproc\imgproc.hpp>
- #include<opencv2\opencv.hpp>
- #include<iostream>
-
- using namespace std;
- using namespace cv;
- using namespace cv::ml;
-
- int main()
- {
- Mat img = Mat::zeros(500, 500, CV_8UC3);
- RNG rng;
-
- Scalar colorTab[] = {
- Scalar(0, 0, 255), // 红
- Scalar(0, 255, 0), // 绿
- Scalar(255, 0, 0), // 蓝
- Scalar(0, 255, 255), // 黄
- Scalar(255, 0, 255) // 品红
- };
-
- int numCluster = rng.uniform(2, 5);
- int numSample = rng.uniform(5, 1000);
- Mat points(numSample, 2, CV_32FC1); //两列,单通道,与KMeans不同
-
- Mat labels;
-
- //生成随机数
- for (int k = 0; k < numCluster; k++)
- {
- Point center;
- center.x = rng.uniform(0, img.cols);
- center.y = rng.uniform(0, img.rows);
- Mat pointChunk = points.rowRange(k*numSample / numCluster,
- k != numCluster - 1 ? (k + 1)*numSample / numCluster : numSample);
- rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
- }
- randShuffle(points, 1, &rng);
-
- Ptr<cv::ml::EM> em_model = cv::ml::EM::create();// 生成 EM 期望最大化
- em_model->setClustersNumber(numCluster); // 设置分类数
- em_model->setCovarianceMatrixType(cv::ml::EM::COV_MAT_SPHERICAL); // 协方差矩阵类型
- em_model->setTermCriteria(TermCriteria(TermCriteria::EPS +
- TermCriteria::COUNT, 100, 0.1)); // 迭代条件,EM训练比KMeans耗时,可能会不收敛,所以迭代次数设大点
- em_model->trainEM(points, noArray(), labels, noArray());
- // EM训练,获得分类结果,参数labels与KMeans的labels参数意思一样
- /*
- bool trainEM(InputArray samples, //输入的样本,一个单通道的矩阵。从这个样本中,进行高斯混和模型估计
- OutputArray logLikelihoods=noArray(),//可选项,输出一个矩阵,里面包含每个样本的似然对数值
- OutputArray labels=noArray(), // 可选项,输出每个样本对应的标注
- OutputArray probs=noArray() //可选项,输出一个矩阵,里面包含每个隐性变量的后验概率
- );
- */
- Mat sample(1, 2, CV_32FC1);
- for (int row = 0; row < img.rows; row++)
- {
- for (int col = 0; col < img.cols; col++)
- {
- sample.at<float>(0) = (float)col;
- sample.at<float>(1) = (float)row;
- Vec2d predict = em_model->predict2(sample, noArray());// 预言
- int response = cvRound(predict[1]);// response 就是给出的当前的分类
- circle(img, Point(col, row), 1, colorTab[response]*0.75, -1);// 以EM预言的分类结果,将img当前点用不同颜色绘制出来
- /*
- Vec2d predict2(InputArray sample,//待测样本
- OutputArray probs //返回一个Vec2d类型的数,包括两个元素的double向量,
- //第一个元素为样本的似然对数值,第二个元素为最大可能混和分量的索引值。
- )
- */
- }
- }
-
- for (int i = 0; i < numSample; i++)//绘制出样本中的数据点属于哪种分类
- {
- Point p(cvRound(points.at<float>(i, 0)), cvRound(points.at<float>(i, 1)));
- circle(img, p, 1, colorTab[labels.at<int>(i)], -1);// 用不同颜色在img上绘制上面随机产生的分类点
- }
-
- imshow("GMM-EM", img);
- waitKey(0);
- return 0;
- }
-
- /*
-
- 准备数据,建立一个width*height的样本,将numSample样本在points中填满,
- 使用一维的存取BGR通道,points是(size(numSample,dims),CV_64FC1);
- 每一行的points存取img中的一个位置的BGR像素,points填满后。
- Ptr<EM> em_model = EM::create();设置分类数目,矩阵类型,迭代算法的终止条件
- 调用trainEM进行训练,将结果放置在labels中,根据labels给图像进行分类标记
-
- 预言:设置一样sample存储每一个像素位置的三个通道的值
- 将sample放入predict2函数中进行预言,将预言结果在图像上标记出来
-
- */
-
- #include<opencv2\core\core.hpp>
- #include<opencv2\highgui\highgui.hpp>
- #include<opencv2\imgproc\imgproc.hpp>
- #include<opencv2\opencv.hpp>
- #include<iostream>
-
- using namespace std;
- using namespace cv;
- using namespace cv::ml;
-
- int main()
- {
- Mat srcImg = imread("toux.jpg");
- if (!srcImg.data)
- {
- printf("could not load image...\n");
- return -1;
- }
- imshow("input image", srcImg);
-
- Scalar colors[] = {
- Scalar(255, 0, 0),
- Scalar(0, 255, 0),
- Scalar(0, 0, 255),
- Scalar(255, 255, 0)
- };
- int width = srcImg.cols;
- int height = srcImg.rows;
- int dims = srcImg.channels();
- int numCluster = 3;
- int numSample = width*height;
-
- Mat points(numSample, dims, CV_64FC1);
- Mat labels;
-
- // 图像RGB像素数据转换为样本数据
- int index = 0;
- for (int row = 0; row < height; row++) // 这里的步骤与KMeans是一样的
- {
- for (int col = 0; col < width; col++)
- {
- index = row*width + col;
- Vec3b bgr = srcImg.at<Vec3b>(row, col);
- points.at<double>(index, 0) = static_cast<int>(bgr[0]);
- points.at<double>(index, 1) = static_cast<int>(bgr[1]);
- points.at<double>(index, 2) = static_cast<int>(bgr[2]);
- }
- }
-
- double time0 = getTickCount();
- //EM Cluster Train
-
- Ptr<EM> em_model = EM::create(); // 生成 EM 期望最大化,其图像分割的方式是基于机器学习的方式
- em_model->setClustersNumber(numCluster); // 设置分类数
- em_model->setCovarianceMatrixType(EM::COV_MAT_SPHERICAL); // 协方差矩阵类型
- em_model->setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 100, 0.1)); // 迭代条件,EM训练比KMeans耗时,可能会不收敛,所以迭代次数设大点
- em_model->trainEM(points, noArray(), labels, noArray()); // EM训练,获得分类结果,参数labels与KMeans的labels参数意思一样,速度比KMeans要慢很多
- cout << "train time=" << (getTickCount() - time0) / getTickFrequency() << endl; // train time=10425.8 训练所需的时间很长
-
- // 对每个像素标记颜色与显示
- // 对每个像素标记颜色与显示
- Mat result_nopredict = Mat::zeros(srcImg.size(), CV_8UC3);
- Mat result_predict = Mat::zeros(srcImg.size(), CV_8UC3);
- Mat sample(dims, 1, CV_64FC1); // 也只能用 CV_64F
- time0 = getTickCount();
- int r = 0, g = 0, b = 0;
- for (int row = 0; row < height; row++)
- {
- for (int col = 0; col < width; col++)
- {
- // 获取训练的分类结果,放到 result_nopredict 中
- index = row*width + col;
- int label = labels.at<int>(index, 0);
- Scalar c = colors[label];
- result_nopredict.at<Vec3b>(row, col)[0] = c[0];
- result_nopredict.at<Vec3b>(row, col)[1] = c[1];
- result_nopredict.at<Vec3b>(row, col)[2] = c[2];
-
- // 通过预言获得分类结果,因为EM训练用的是src的颜色数据,所以用src的颜色数据做预言,得到的结果与 result_nopredict 是一模一样的
- b = srcImg.at<Vec3b>(row, col)[0];
- g = srcImg.at<Vec3b>(row, col)[1];
- r = srcImg.at<Vec3b>(row, col)[2];
- sample.at<double>(0) = b;
- sample.at<double>(1) = g;
- sample.at<double>(2) = r;
- Vec2d predict = em_model->predict2(sample, noArray()); // 预言,预言的时间是很短的
- int response = cvRound(predict[1]); // response 就是目标颜色数据在EM训练中预言的分类
- c = colors[response];
- result_predict.at<Vec3b>(row, col)[0] = c[0];
- result_predict.at<Vec3b>(row, col)[1] = c[1];
- result_predict.at<Vec3b>(row, col)[2] = c[2];
-
- }
- }
- printf("execution time(ms) : %.2f\n", (getTickCount() - time0) / getTickFrequency()); // execution time(ms) : 1600.31
- imshow("EM-Segmentation nopredict", result_nopredict); // 从效果看,KMeans更好些
- imshow("EM-Segmentation predict", result_predict);
-
- waitKey(0);
- return 0;
- }
参考:https://blog.csdn.net/huanghuangjin/article/details/81452229
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。