(五)OpenCV图像分割_02_K-means分割图像_机器学习

本文介绍了如何使用OpenCV库中的K-means算法进行图像分割。通过实例展示了K-means在图像处理中的应用,详细阐述了算法的步骤和实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
	Mat src,dst;
	src = imread("../path.jpg");
	if (src.empty())
	{
		cout << "could not load image1..." << endl;
		return -1;
	}

	namedWindow("src", WINDOW_AUTOSIZE);
	imshow("src", src);

	//为最大的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 sampleCount = width * height;//采样数
	int clusterCount = 5;//最大聚类数目

	Mat points(sampleCount, dims, CV_32F, Scalar(10));//存放样本点,是sampleCount行dims通道的行向量
	Mat centers(clusterCount, 1, points.type());用来存储聚类后的中心点

	Mat labels;

	// 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<float>(index, 0) = static_cast<int>(bgr[0]);
			points.at<float>(index, 1) = static_cast<int>(bgr[1]);
			points.at<float>(index, 2) = static_cast<int>(bgr[2]);
		}
	}

	//K-Means
	TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1);
	kmeans(points, clusterCount, labels, criteria, 3, KMEANS_PP_CENTERS, centers);

	// 显示图像分割结果
	dst = Mat::zeros(src.size(), src.type());
	for (int row = 0; row < height; row++) 
	{
		for (int col = 0; col < width; col++)
		{
			index = row * width + col;
			int label = labels.at<int>(index, 0);
			dst.at<Vec3b>(row, col)[0] = colorTab[label][0];
			dst.at<Vec3b>(row, col)[1] = colorTab[label][1];
			dst.at<Vec3b>(row, col)[2] = colorTab[label][2];
		}
	}

	for (int i = 0; i < centers.rows; i++) 
	{
		int x = centers.at<float>(i, 0);
		int y = centers.at<float>(i, 1);
		cout << "聚类中心为center: " << "c.x" << x << ",c.y: " << y << endl;
	}

	imshow("K-means_dst", dst);
	waitKey(0);
	return 0;
}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值