基于Kmeans的图像压缩

写在前面: 

 先给大家看一波图片压缩的效果图,下面是我本人的微信二维码进行图像压缩前后的图像

KMeans算法压缩方式,就是将原来很多的颜色用少量的颜色去表示,这样就可以减小图片大小了。

各位小伙伴系不系很激动啦!那么接下来赶紧看一下上面的效果是如何实现吧。

代码:

#导包
from skimage import io
from sklearn.cluster import KMeans
import numpy as np

#读取图片 
image = io.imread("face.jpg")

#显示图片
io.imshow(image)

#获取图片压缩前的信息
print ('image的类型:', type(image))  #numpy.ndarray类型
print ('image的尺寸:', image.shape)  #显示尺寸
print ('image的宽度:', image.shape[0])  #图片宽度
print ('image的高度:', image.shape[1])  #图片高度
print ('image的通道数:', image.shape[2])  #图片通道数
print ('image的总像素个数:', image.size)   #显示总像素个数
print ('image的最大像素值:', image.max())  #最大像素值
print ('image的最小像素值:', image.min())  #最小像素值
print ('image的像素平均值:', image.mean()) #像素平均值

#rows*cols*channel = 482*500*3 
rows = image.shape[0]
cols = image.shape[1]
channel = image.shape[2]

#样本数*channel = 241000*3
#每个样本在不同通道都有存在1个点,即此时每个样本对应于3个点
image = image.reshape(image.shape[0] * image.shape[1], channel)

#样本数*channel = 241000*1
#使用Kmeans算法将3通道变为1通道(将原来很多的颜色用少量的颜色来表示),即此时每个样本只存在1个点
#n_clusters:K值,把集合分成K个簇;n_init:指定CPU个数;max_iter:最大的迭代次数
kmeans = KMeans(n_clusters=128, n_init=10, max_iter=200)  
kmeans.fit(image)

clusters = np.asarray(kmeans.cluster_centers_, dtype=np.uint8)
#labels_:每个点的标签
labels = np.asarray(kmeans.labels_, dtype=np.uint8) 
#rows*cols*channel = 482*500*1
labels = labels.reshape(rows, cols)

np.save('codebook_test.npy', clusters)
#保存压缩后的图片
io.imsave('compressed_test.jpg', labels)

运行结果:

使用K-means算法前:

#读取压缩后的图片
newimage = io.imread("compressed_test.jpg")

#获取图片压缩后的信息
print ('newimage的类型:', type(newimage))  #numpy.ndarray类型
print ('newimage的尺寸:', newimage.shape)  #显示尺寸
print ('newimage的宽度:', newimage.shape[0])  #图片宽度
print ('newimage的高度:', newimage.shape[1])  #图片高度
#print ('newimage的通道数:', newimage.shape[2])  #图片通道数
print ('newimage的总像素个数:', newimage.size)   #显示总像素个数
print ('newimage的最大像素值:', newimage.max())  #最大像素值
print ('newimage的最小像素值:', newimage.min())  #最小像素值
print ('newimage的像素平均值:', newimage.mean()) #像素平均值

#显示压缩后的图片
io.imshow(newimage)

使用K-means算法后:

扫描二维码关注公众号,回复: 3243454 查看本文章

温馨提示:大家练习的时候可以选择占用空间比较小的图片,不然图片过大可能运行时间就很长啦!慢慢等吧,哈哈!

更多AI资源请关注公众号:大胡子的AI

欢迎各位AI爱好者加入群聊交流学习:882345565(内有大量免费资源哦!)

版权声明:本文为博主原创文章,未经博主允许不得转载。如要转载请与本人联系。

猜你喜欢

转载自blog.csdn.net/weixin_39549734/article/details/81229426