聚类:K-means进行图像压缩

from numpy.core.fromnumeric import reshape
from skimage import io
from sklearn import cluster 
from sklearn.cluster import KMeans
import numpy as np

#第一步读取图像
image = io.imread("ladybug.png")
# io.imshow(image)
# io.show()

#第二步取出长和宽
rows = image.shape[0]
cols = image.shape[1]
# print("rows:"+int(rows))

#第三步选取reshape,选取kmeans进行训练(fit)
#reshape成为一个二维样本 ,3为三个通道
image = image.reshape(image.shape[0]*image.shape[1],3)    
kmeans = KMeans(n_clusters=128,n_init=10,max_iter=200)     #分为128个簇,使用cpu数量,最大迭代次数
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
kmeans.fit(image)       #进行训练

#第四步将labels图像转为灰度图
clusters = np.asarray(kmeans.cluster_centers_,dtype=np.uint8)
labels = np.asarray(kmeans.labels_,dtype=np.uint8)
labels = labels.reshape(rows,cols)   #转化为灰度图
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
print(clusters.shape)
np.save("codebook_test.npy",clusters)
io.imsave("compressed_test.jpg",labels)


image1 = io.imread("compressed_test.jpg")
io.imshow(image1)
io.show()
print("**********************************")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值