利用OpenCv2实现k-means

2023-08-24  本文已影响0人  大龙10

1、基本思想

2、最终的k个聚类具有以下特点

3、算法描述

  假设要把样本集分为k个类别

4、图像分割

5、利用opencv2实现k-means

cv2.kmeans(data, K, bestLabels, criteria, attempts, flags)

6、Python程序

import cv2
import matplotlib.pyplot as plt
import numpy as np
 
 
def seg_kmeans_gray():
    #读取图片
    img = cv2.imread('d:\\pic.jpg', cv2.IMREAD_GRAYSCALE)
 
    # 展平
    img_flat = img.reshape((img.shape[0] * img.shape[1], 1))
    img_flat = np.float32(img_flat)
 
    # 迭代参数
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TermCriteria_MAX_ITER, 20, 0.5)
    flags = cv2.KMEANS_RANDOM_CENTERS
 
    # 进行聚类
    compactness, labels, centers = cv2.kmeans(img_flat, 3, None, criteria, 10, flags)
 
    # 显示结果
    img_output = labels.reshape((img.shape[0], img.shape[1]))
    plt.subplot(121), plt.imshow(img, 'gray'), plt.title('input')
    plt.subplot(122), plt.imshow(img_output, 'gray'), plt.title('kmeans')
    plt.show()
 
 
if __name__ == '__main__':
    seg_kmeans_gray()

k=3, 分割的图形

7、资料

「wangqianqianya」博客:
https://blog.csdn.net/wangqianqianya/article/details/87886013
上一篇下一篇

猜你喜欢

热点阅读