基于贾志刚老师的OPENCV图像分割实战的代码,下面的代码可以跑通,环境需要自己提前搭建好。
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
using namespace cv::ml;
int main(int argv, char* argc)
{
Mat src = imread("50.bmp");
//定义5种颜色 最大分类不超过5
Scalar colorTab[] = {
Scalar(0, 0, 255),
Scalar(0, 255, 0),
Scalar(255, 0, 0),
Scalar(0, 255, 255),
Scalar(255, 0, 255),
};
int width = src.cols;
int height = src.rows;
int dims = src.channels();
int nsamples = width * height;
//创建sampleCount行2列的mat
Mat points(nsamples, dims, CV_64FC1);
Mat labels;
Mat result = Mat::zeros(src.size(), CV_8UC3);
//定义分类 即函数K值 多少个分类点
int num_cluster = 5;
// 图像RGB像素数据转换为样本数据
int index = 0;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
index = row * width + col;
Vec3b bgr = src.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]);
}
}
// EM Cluster Train
Ptr<EM> em_model = EM::create();
//分区个数
em_model->setClustersNumber(num_cluster);
//设置协方差矩阵类型
em_model->setCovarianceMatrixType(EM::COV_MAT_SPHERICAL);
//设置收敛条件
em_model->setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 100, 0.1));
//根据样本训练 将概率分区存储到lables EM
em_model->trainEM(points, noArray(), labels, noArray());
// 对每个像素标记颜色与显示
Mat sample(1, dims, CV_64FC1);
int r = 0, g = 0, b = 0;
//将每个像素放到样本中
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
index = row * width + col;
//获取各个通道的颜色
b = src.at<Vec3b>(row, col)[0];
g = src.at<Vec3b>(row, col)[1];
r = src.at<Vec3b>(row, col)[2];
//将像素放到样本数据中
sample.at<double>(0, 0) = static_cast<double>(b);
sample.at<double>(0, 1) = static_cast<double>(g);
sample.at<double>(0, 2) = static_cast<double>(r);
//四舍五入
int response = cvRound(em_model->predict2(sample, noArray())[1]);
Scalar c = colorTab[response];
result.at<Vec3b>(row, col)[0] = c[0];
result.at<Vec3b>(row, col)[1] = c[1];
result.at<Vec3b>(row, col)[2] = c[2];
}
}
imshow("GMM-EM DEMO", result);
waitKey(0);
return 0;
}