Python K-means實(shí)現(xiàn)簡(jiǎn)單圖像聚類的示例代碼
這里直接給出第一個(gè)版本的直接實(shí)現(xiàn):
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) 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)
主要需要注意的問題是對(duì)K-Means原理的理解。K-means做的是對(duì)向量的聚類,也就是說,假設(shè)要處理的是224×224×3的RGB圖像,那么就得先將其轉(zhuǎn)為1維的向量。在上面的做法里,我們是直接對(duì)其展平:
image = image.reshape(-1, )
那么這么做的缺陷也是十分明顯的。例如,對(duì)于兩張一模一樣的圖像,我們將前者向左平移一個(gè)像素。這么做下來后兩張圖像在感官上幾乎沒有任何區(qū)別,但由于整體平移會(huì)導(dǎo)致兩者的圖像矩陣逐像素比較的結(jié)果差異巨大。以橘子汽車聚類為例,實(shí)驗(yàn)結(jié)果如下:
可以看到結(jié)果是比較差的。因此,我們進(jìn)行改進(jìn),利用ResNet-50進(jìn)行圖像特征的提取(embedding),在特征的基礎(chǔ)上聚類而非直接在像素上聚類,代碼如下:
import os import numpy as np from sklearn.cluster import KMeans import cv2 from imutils import build_montages import torch.nn as nn import torchvision.models as models from PIL import Image from torchvision import transforms class Net(nn.Module): def __init__(self): super(Net, self).__init__() resnet50 = models.resnet50(pretrained=True) self.resnet = nn.Sequential(resnet50.conv1, resnet50.bn1, resnet50.relu, resnet50.maxpool, resnet50.layer1, resnet50.layer2, resnet50.layer3, resnet50.layer4) def forward(self, x): x = self.resnet(x) return x net = Net().eval() 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 = Image.open(path).convert('RGB') image = transforms.Resize([224,244])(image) image = transforms.ToTensor()(image) image = image.unsqueeze(0) image = net(image) image = image.reshape(-1, ) all_images.append(image.detach().numpy()) 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)
可以發(fā)現(xiàn)結(jié)果明顯改善:
到此這篇關(guān)于Python K-means實(shí)現(xiàn)簡(jiǎn)單圖像聚類的示例代碼的文章就介紹到這了,更多相關(guān)Python K-means圖像聚類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Tensorflow加載預(yù)訓(xùn)練模型和保存模型的實(shí)例
今天小編就為大家分享一篇Tensorflow加載預(yù)訓(xùn)練模型和保存模型的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07python利用多線程+隊(duì)列技術(shù)爬取中介網(wǎng)互聯(lián)網(wǎng)網(wǎng)站排行榜
這篇文章主要介紹了python利用多線程+隊(duì)列技術(shù)爬取中介網(wǎng)互聯(lián)網(wǎng)網(wǎng)站排行榜,文章基于python的相關(guān)內(nèi)容展開詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05python針對(duì)Oracle常見查詢操作實(shí)例分析
這篇文章主要介紹了python針對(duì)Oracle常見查詢操作,結(jié)合實(shí)例形式分析了python針對(duì)Oracle常見的子查詢、多表查詢等相關(guān)原理、操作技巧與使用注意事項(xiàng),需要的朋友可以參考下2020-04-04對(duì)Python信號(hào)處理模塊signal詳解
今天小編就為大家分享一篇對(duì)Python信號(hào)處理模塊signal詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python 函數(shù)list&read&seek詳解
這篇文章主要介紹了Python 函數(shù)list&read&seek詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08python版本的仿windows計(jì)劃任務(wù)工具
這篇文章主要介紹了python版本的仿windows計(jì)劃任務(wù)工具,計(jì)劃任務(wù)工具根據(jù)自己設(shè)定的具體時(shí)間,頻率,命令等屬性來規(guī)定所要執(zhí)行的計(jì)劃,當(dāng)然功能不是很全大家可以補(bǔ)充2018-04-04淺談Tensorflow由于版本問題出現(xiàn)的幾種錯(cuò)誤及解決方法
今天小編就為大家分享一篇淺談Tensorflow由于版本問題出現(xiàn)的幾種錯(cuò)誤及解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06