import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from skimage.io import imread
from sklearn.utils import shuffle
from skimage import img_as_float
from time import time
img=imread("C:/Users/xpp/Desktop/Lena.png")
plt.figure(1),plt.clf()
ax=plt.axes([0,0,1,1])
plt.axis('off'),plt.title('Original image (%d colors)' %(len(np.unique(img)))),plt.imshow(img)
n_colors=64
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))
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
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)
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,nRandom)')
plt.imshow(recreate_image(codebook_random,labels_random,w,h))
i+=1
plt.show()
done in 0.522s. Predicting color indices on the full image (k-means) done in 0.298s. done in 0.284s. Predicting color indices on the full image (k-means) done in 0.171s. done in 0.207s. Predicting color indices on the full image (k-means) done in 0.096s. done in 0.124s. Predicting color indices on the full image (k-means) done in 0.043s.
Predicting color indices on the full image (random) done in 0.460s. Predicting color indices on the full image (random) done in 0.241s. Predicting color indices on the full image (random) done in 0.122s. Predicting color indices on the full image (random) done in 0.044s.
算法:像素矢量量化是保持整体外观质量并将显示图像所需的颜色数量从250种减少到4种。
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!