python实现K-means图像聚类

1.K-means 聚类算法简介

K-means 聚类是一种常用的无监督学习算法,用于将数据点划分为K个簇(Clusters),每个簇代表数据中的一组相似点。该算法通过最小化簇内点到簇中心(Centroid)的平方距离来实现聚类。K-means 特别适合图像分类,因为它能够将图像的像素分割成不同的区域或颜色簇。

K-means 算法步骤
  1. 初始化

    • 随机选择K个数据点作为初始的簇中心。
  2. 分配簇

    • 对于数据集中的每一个点,计算其与K个簇中心的距离,并将该点分配到最近的簇中心。
  3. 更新簇中心

    • 重新计算每个簇的中心,即计算簇内所有点的均值作为新的簇中心。
  4. 重复

    • 不断重复步骤2和步骤3,直到簇中心不再变化或达到最大迭代次数。
  5. 输出结果

    • 最终,所有数据点将被分配到K个簇中,且每个簇都有一个中心点。

2.K-means 聚类在图像分类中的应用

在图像处理中,K-means 聚类可以用于图像的颜色量化(Color Quantization)。即通过将图像中的像素点聚类为K个

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是Python实现K-Means聚类的代码示例: ```python import numpy as np from matplotlib import pyplot as plt # 生成数据点 X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]]) # 设定初始聚类中心 centroids = np.array([[1, 0.6], [1.5, 1.8], [5, 8]]) # 定义距离函数 def euclidean_distance(x1, x2): return np.sqrt(np.sum((x1 - x2) ** 2)) # 定义K-Means函数 def k_means(X, k=3, max_iters=100): # 随机初始化聚类中心 idx = np.random.choice(len(X), k, replace=False) centroids = X[idx] # 迭代更新聚类中心 for i in range(max_iters): # 分配数据点到最近的聚类中心 clusters = [[] for _ in range(k)] for x in X: distances = [euclidean_distance(x, c) for c in centroids] cluster_idx = np.argmin(distances) clusters[cluster_idx].append(x) # 计算新的聚类中心 new_centroids = [] for c in clusters: mean = np.mean(c, axis=0) new_centroids.append(mean) new_centroids = np.array(new_centroids) # 判断是否收敛 if np.all(centroids == new_centroids): break centroids = new_centroids return centroids, clusters # 调用K-Means函数 centroids, clusters = k_means(X, k=3) # 可视化聚类结果 colors = ['r', 'g', 'b'] for i, c in enumerate(clusters): for x in c: plt.scatter(x[0], x[1], color=colors[i]) plt.scatter(centroids[:,0], centroids[:,1], marker='*', s=200, color='black') plt.show() ``` 运行上述代码,可以得到类似于以下图像聚类结果: ![K-Means聚类结果](https://img-blog.csdn.net/20180721090548206?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JqMjM4NzA1MjYwNjg=//font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲人编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值