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

Genet ·
更新时间:2024-11-13
· 774 次阅读

#include #include 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(row, col); points.at(index, 0) = static_cast(bgr[0]); points.at(index, 1) = static_cast(bgr[1]); points.at(index, 2) = static_cast(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(index, 0); dst.at(row, col)[0] = colorTab[label][0]; dst.at(row, col)[1] = colorTab[label][1]; dst.at(row, col)[2] = colorTab[label][2]; } } for (int i = 0; i < centers.rows; i++) { int x = centers.at(i, 0); int y = centers.at(i, 1); cout << "聚类中心为center: " << "c.x" << x << ",c.y: " << y << endl; } imshow("K-means_dst", dst); waitKey(0); return 0; }

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


作者:丶小早



学习 k-means 机器学习 opencv

需要 登录 后方可回复, 如果你还没有账号请 注册新账号