opencv GMM-高斯混合算法分割图像

#include 
#include 
using namespace cv;
using namespace std;
using namespace ml;

int main()
{
	Mat src = imread("D:/source/images/dlrb.png");
	if (src.empty())
	{
		printf("read image error\n");
		system("pause");
		return -1;
	}
	imshow("src", src);

	Scalar colorTab[] = {
		Scalar(0, 0, 255),
		Scalar(0, 255, 0),
		Scalar(255, 0, 0),
		Scalar(0, 255, 255),
		Scalar(255, 0, 255)
	};

	int numCluster = 3;
	int width = src.cols;
	int height = src.rows;
	int dims = src.channels();
	int nsamples = width * height;
	Mat points(nsamples, dims, CV_64FC1);
	Mat labels;
	Mat result = Mat::zeros(src.size(), CV_8UC3);

	// 图像RGB像素数据装换为样本数据
	int index = 0;
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			index = row * width + col;
			Vec3b rgb = src.at(row, col);
			points.at(index, 0) = static_cast(rgb[0]);
			points.at(index, 1) = static_cast(rgb[1]);
			points.at(index, 2) = static_cast(rgb[2]);
		}
	}

	// EM Cluster Train
	Ptr em_model = EM::create();
	em_model->setClustersNumber(numCluster);
	em_model->setCovarianceMatrixType(EM::COV_MAT_SPHERICAL);
	em_model->setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 100, 0.1));
	em_model->trainEM(points, noArray(), labels, noArray());

	// 对每个像素标记颜色显示
	Mat sample(dims, 1, CV_64FC1);
	int time = getTickCount();
	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;
			/*int label = labels.at(index, 0);
			Scalar c = colorTab[label];
			result.at(row, col)[0] = c[0];
			result.at(row, col)[1] = c[0];
			result.at(row, col)[1] = c[0];*/

			b = src.at(row, col)[0];
			g = src.at(row, col)[0];
			r = src.at(row, col)[0];

			sample.at(0) = b;
			sample.at(1) = g;
			sample.at(2) = r;

			// 训练处这个点属于哪个分类
			int response = cvRound(em_model->predict2(sample, noArray())[1]);
			Scalar c = colorTab[response];
			result.at(row, col)[0] = c[0];
			result.at(row, col)[1] = c[1];
			result.at(row, col)[2] = c[2];
		}
	}
	printf("execution time: %.2f\n", (getTickCount() - time) / getTickFrequency() * 1000);
	imshow("result", result);

	waitKey(0);
	return 0;
}

opencv GMM-高斯混合算法分割图像_第1张图片
opencv GMM-高斯混合算法分割图像_第2张图片

你可能感兴趣的:(机器视觉,【OpenCV】整理记录)