kmeans图片聚类算法python
时间: 2023-10-09 17:10:37 浏览: 115
kmeans.zip_Python 画图_k-means图片python_kmeans聚类作图_聚类 Python
k-means图片聚类算法是一种常用的无监督学习算法,用于将一组图片聚类成k个簇。下面给出了一个基于Python的k-means图片聚类算法的实现:
```python
import os
import numpy as np
from sklearn.cluster import KMeans
import cv2
from imutils import build_montages
import matplotlib.image as imgplt
# 读取所有图片
image_path = []
all_images = []
images = os.listdir('./images')
for image_name in images:
image_path.append('./images/' + image_name)
for path in image_path:
image = imgplt.imread(path)
image = image.reshape(-1, )
all_images.append(image)
# 使用KMeans算法进行聚类
clt = KMeans(n_clusters=2)
clt.fit(all_images)
# 获取每个簇的标签
labelIDs = np.unique(clt.labels_)
# 随机选择每个簇中的一些图片进行展示
for labelID in labelIDs:
idxs = np.where(clt.labels_ == labelID)[0]
idxs = np.random.choice(idxs, size=min(25, len(idxs)), replace=False)
show_box = []
for i in idxs:
image = cv2.imread(image_path[i])
image = cv2.resize(image, (96, 96))
show_box.append(image)
montage = build_montages(show_box, (96, 96), (5, 5))[0]
title = "Type {}".format(labelID)
cv2.imshow(title, montage)
cv2.waitKey(0)
```
这个代码使用了`sklearn.cluster.KMeans`类来进行图片聚类,并使用了OpenCV库来处理图片。首先,将所有图片读取并转换为一维数组的形式,然后使用KMeans算法将图片聚类成k个簇。最后,随机选择每个簇中的一些图片进行展示。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [利用Python K-means实现简单图像聚类](https://blog.csdn.net/qq_40714949/article/details/120854418)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python使用k-means算法代码案例-K-means聚类算法及python代码实现](https://blog.csdn.net/weixin_37988176/article/details/109394754)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文