OpenCV#11 Kmeans聚类的使用

程序运行逻辑

在进行聚类前,首先使用

Blur(src, src, new Size(15, 15));

对图形进行了均值滤波

[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:54432bf3-6c74-4dde-9a83-0395b7f8ccc5

[En]

[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:d865d400-ba92-4906-ba65-780451729a21

1、var columnVector = src.Reshape(cn: 3, rows: src.Rows * src.Cols);

将图形转变为3通道的单列矩阵

2、columnVector.ConvertTo(samples, MatType.CV_32FC3);

将矩阵转变成浮点矩阵

3、调用kmean函数,并查看不同参数k:2,4,5,8的效果

Cv2.Kmeans(
data: samples,
k: clustersCount,
bestLabels: bestLabels,
criteria:
new TermCriteria(type: CriteriaType.Eps | CriteriaType.MaxIter, maxCount: 10, epsilon: 1.0),
attempts: 3,
flags: KMeansFlags.PpCenters,
centers: centers);

4、读取生成矩阵bestLabel,并重写成和原图同类型矩阵

var clusteredImage = new Mat(src.Rows, src.Cols, src.Type());
                for (var size = 0; size < src.Cols * src.Rows; size++)
                {
                    var clusterIndex = bestLabels.At<int>(0, size);
                    var newPixel = new Vec3b
                    {
                        Item0 = (byte)(centers.At<float>(clusterIndex, 0)), // B
                        Item1 = (byte)(centers.At<float>(clusterIndex, 1)), // G
                        Item2 = (byte)(centers.At<float>(clusterIndex, 2)) // R
                    };
                    clusteredImage.Set(size / src.Cols, size % src.Cols, newPixel);
                }</float></float></float></int>

5、图形显示。

Original: https://blog.csdn.net/zzlwl/article/details/123138649
Author: 健忘的松鼠
Title: OpenCV#11 Kmeans聚类的使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/560794/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球