for i in range(10): cluster_i_path = os.path.join(root_path, f'cluster_{i}') if not os.path.exists(cluster_i_path): os.mkdir(cluster_i_path) for j, label in enumerate(labels): if label == i: old_path = os.path.join(path, f'Al{j + 10000}.png') new_path = os.path.join(cluster_i_path, f'al{j + 10000}.png') os.rename(old_path, new_path),Al这类我有300张图片,应该怎么才能把三百张全部聚类完
时间: 2024-02-27 11:56:56 浏览: 103
python中 if __name__ == “__main__”的作用
你可以将上述代码封装成一个函数,然后将这个函数放入一个循环中,这个循环可以遍历不同的聚类数目,从而将所有的图片进行聚类。以下是一个示例代码:
```python
import os
from sklearn.cluster import AgglomerativeClustering
from skimage import io
import numpy as np
def cluster_images(path, n_clusters):
# 读取图片并提取特征
features = []
for i in range(1, 301):
img_path = os.path.join(path, f"Al{i}.png")
img = io.imread(img_path)
feature = np.mean(img, axis=(0, 1)) # 以像素的RGB值的平均值作为特征
features.append(feature)
# 聚类
clustering = AgglomerativeClustering(n_clusters=n_clusters)
labels = clustering.fit_predict(features)
# 将图片移动到对应的聚类文件夹
for i in range(n_clusters):
cluster_i_path = os.path.join(path, f"cluster_{i}")
if not os.path.exists(cluster_i_path):
os.mkdir(cluster_i_path)
for j, label in enumerate(labels):
if label == i:
old_path = os.path.join(path, f"Al{j + 1}.png")
new_path = os.path.join(cluster_i_path, f"Al{j + 1}.png")
os.rename(old_path, new_path)
# 遍历不同的聚类数目
for n_clusters in range(2, 11):
cluster_images("path/to/images", n_clusters)
```
上述代码中,`cluster_images`函数接受一个图片路径和聚类数目作为输入,然后将图片聚类并移动到对应的聚类文件夹中。最后,遍历不同的聚类数目并调用`cluster_images`函数即可将所有的图片进行聚类。
阅读全文