import os import numpy as np from PIL import Image from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input from sklearn.cluster import KMeans # 加载 ResNet50 模型 model = ResNet50(weights='imagenet', include_top=False) # 加载并预处理图片,提取特征向量 features = [] for filename in os.listdir('D:/wjd/2'): if filename.endswith('.png'): img = Image.open(os.path.join('D:/wjd/2', filename)) img = img.convert('RGB') # 将 RGBA 转换为 RGB img = img.resize((224, 224)) x = np.array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) feature = model.predict(x) feature = np.squeeze(feature) features.append(feature) # 将特征向量进行聚类,自动确定聚类的数量 kmeans = KMeans(n_clusters=None, max_iter=1000, n_init=50).fit(features) n_clusters = len(set(kmeans.labels_)) # 将每张图片分配到对应的聚类中 for i, label in enumerate(kmeans.labels_): filename = os.listdir('D:/wjd/2')[i] print('{} belongs to cluster {}'.format(filename, label)),可以将代码中的聚类方法换成 DBSCAN,其他保持不变
时间: 2024-03-03 22:50:16 浏览: 149
可以将代码中的聚类方法从KMeans换成DBSCAN,代码如下:
```
import os
import numpy as np
from PIL import Image
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from sklearn.cluster import DBSCAN
# 加载 ResNet50 模型
model = ResNet50(weights='imagenet', include_top=False)
# 加载并预处理图片,提取特征向量
features = []
for filename in os.listdir('D:/wjd/2'):
if filename.endswith('.png'):
img = Image.open(os.path.join('D:/wjd/2', filename))
img = img.convert('RGB') # 将 RGBA 转换为 RGB
img = img.resize((224, 224))
x = np.array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
feature = model.predict(x)
feature = np.squeeze(feature)
features.append(feature)
# 将特征向量进行聚类,自动确定聚类的数量
dbscan = DBSCAN(eps=0.5, min_samples=2).fit(features)
n_clusters = len(set(dbscan.labels_))
# 将每张图片分配到对应的聚类中
for i, label in enumerate(dbscan.labels_):
filename = os.listdir('D:/wjd/2')[i]
print('{} belongs to cluster {}'.format(filename, label))
```
阅读全文