KMeans聚类图像分割

2022-05-28 17:04:18 浏览数 (1)

代码语言:javascript复制
import numpy as np
from time import time
from skimage.io import imread
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
from sklearn.datasets import load_sample_image
from sklearn.metrics import pairwise_distances_argmin
def recreate_image(codebook,labels,w,h):
#定义图像压缩函数
    d=codebook.shape[1]
    image=np.zeros((w,h,d))
    label_idx=0
    for i in range(w):
        for j in range(h):
            image[i][j]=codebook[labels[label_idx]]
            label_idx =1
    return image
n_colors=64
img=imread('C:/Users/xpp/Desktop/Lena.png')#原始图像
img=np.array(img,dtype=np.float64)/255
w,h,d=original_shape=tuple(img.shape)
assert d==3
image_array=np.reshape(img,(w*h,d))
plt.figure(1)
plt.clf()
ax=plt.axes([0,0,1,1])
plt.axis('off')
plt.title('Original image (96,615 colors)')
plt.imshow(img)
plt.figure(2,figsize=(10,10))
plt.clf()
i=1
for k in [64,32,16,4]:
    t0=time()
    plt.subplot(2,2,i)
    plt.axis('off')
    image_array_sample=shuffle(image_array, random_state=0)[:1000]
    kmeans=KMeans(n_clusters=k,random_state=0).fit(image_array_sample)#kmeans
    print("done in %0.3fs." %(time()-t0))
    print("Predicting color indices on the full image (k-means)")
    t0 = time()
    labels=kmeans.predict(image_array)#预测所有点的标签
    print("done in %0.3fs." %(time()-t0))
    plt.title('Quantized image (' str(k) ' colors, K-Means)')
    plt.imshow(recreate_image(kmeans.cluster_centers_,labels,w,h))
    i =1
plt.show()
plt.figure(3,figsize=(10,10))
plt.clf()
i=1
for k in [64,32,16,4]:
    t0=time()
    plt.subplot(2,2,i)
    plt.axis('off')
    codebook_random=shuffle(image_array,random_state=0)[:k 1]
    print("Predicting color indices on the full image (random)")
    t0=time()
    labels_random=pairwise_distances_argmin(codebook_random,image_array,axis=0)#计算距离
    print("done in %0.3fs." % (time()-t0))
    plt.title('Quantized image (' str(k) ' colors, Random)')
    plt.imshow(recreate_image(codebook_random,labels_random,w,h))
    i =1
plt.show()

done in 0.472s. Predicting color indices on the full image (k-means) done in 0.320s. done in 0.372s. Predicting color indices on the full image (k-means) done in 0.183s. done in 0.378s. Predicting color indices on the full image (k-means) done in 0.118s. done in 0.102s. Predicting color indices on the full image (k-means) done in 0.039s.

Predicting color indices on the full image (random) done in 0.453s. Predicting color indices on the full image (random) done in 0.276s. Predicting color indices on the full image (random) done in 0.116s. Predicting color indices on the full image (random) done in 0.045s.

算法:KMeans聚类图像分割是将像素矢量量化,将显示图像所需的颜色数量从250种减少到4种,同时保持整体外观质量。

0 人点赞