分享

如何利用K-Means将文件夹中图像进行分类?

 小白学视觉 2021-02-22

重磅干货,第一时间送达

K-Means聚类是最常用的无监督机器学习算法之一。顾名思义,它可用于创建数据集群,从本质上将它们隔离。

现在,我们将做一个简单的示例,将文件夹中的图像进行分离,该文件夹既有猫也有狗的图像。并且将创建两个单独的文件夹(群集),我们将介绍如何自动确定K的最佳值。

猫和狗的图像数据集

首先,我们将从导入所需的库开始。

import numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import silhouette_scoreimport cv2import os, glob, shutil
然后我们会从文件夹中的图像读取所有的图像并对其进行处理,以提取特征提取。我们将图像大小调整为224x224,以匹配模型输入层的大小以进行特征提取。
input_dir = 'pets'glob_dir = input_dir + '/*.jpg'images = [cv2.resize(cv2.imread(file), (224, 224)) for file in glob.glob(glob_dir)]paths = [file for file in glob.glob(glob_dir)]images = np.array(np.float32(images).reshape(len(images), -1)/255)

现在,我们将在MobileNetV2(传输学习)的帮助下进行特征提取。当然我们可以使用ResNet50,InceptionV3等,但是MobileNetV2速度很快,而且资源也不是很多。

model = tf.keras.applications.MobileNetV2(include_top=False,weights=’imagenet’, input_shape=(224, 224, 3))predictions = model.predict(images.reshape(-1, 224, 224, 3))pred_images = predictions.reshape(images.shape[0], -1)

现在,我们已经实现了提取功能,现在可以使用KMeans进行聚类了。

k = 2kmodel = KMeans(n_clusters = k, n_jobs=-1, random_state=728)kmodel.fit(pred_images)kpredictions = kmodel.predict(pred_images)shutil.rmtree(‘output’)for i in range(k): os.makedirs(“output\cluster” + str(i))for i in range(len(paths)): shutil.copy2(paths[i], “output\cluster”+str(kpredictions[i]))

输出结果如下:

小狗:

猫:

另外我们如何确定数据集的K值?我们可以使用轮廓法或肘部法确定它。我们将在这里使用轮廓法,当然这两种方法都可获得最可靠的结果,所以能直接确定K。

当我们将马的图像添加到原始数据集中时,我们来确定K的值。

sil = []kl = []kmax = 10for k in range(2, kmax+1): kmeans2 = KMeans(n_clusters = k).fit(pred_images) labels = kmeans2.labels_ sil.append(silhouette_score(pred_images, labels, metric = ‘euclidean’)) kl.append(k)
现在,我们将绘制图像:
plt.plot(kl, sil)plt.ylabel(‘Silhoutte Score’)plt.ylabel(‘K’)plt.show()

如我们所见,K的最佳值为3,我们还成功创建了第三个集群:

结论

如我们所见,K-Means聚类是用于图像分离的出色算法。在某些时候,我们使用的方法可能无法提供准确的结果,我们可以尝试使用其他卷积神经网络对其进行修复,或者尝试将图像从BGR转换为RGB,然后进行处理。

下载1:OpenCV-Contrib扩展模块中文版教程

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多