K-means小应用---图像压缩

图像在相邻区域的颜色相近,我们可以用一种颜色来代替区域中的其它相近颜色。利用K-means算法可以对图像的进行分簇,然后将各簇内的颜色都用中心点的颜色代替。

python代码

'''
@dev: python3:3.7.3 scipy:1.3.0
@Date: 2019-12-13 18:59:14
@Descripttion: 利用K-means进行图像压缩
'''
from scipy.cluster.vq import kmeans, vq
import numpy as np
from PIL import Image

k_list = [2, 8, 32, 64, 128, 256]

data = Image.open(r'.\example.jpg')
# kmeans只支持float或double
data = np.array(data, dtype='float')
(height, width, channel) = data.shape

data = np.reshape(data, (height * width, channel))
for k in k_list:
    print('k值:%d...' % k)
    (centroids, distortion) = kmeans(data,
                                     k)  # 返回聚类中心和损失:样本点和对应centroids之间差值的平方和
    (code, distortion) = vq(data, centroids)  # 迭代, 获取最终的分簇
    print('distortion: %.6f' % distortion.sum())
    # 染色
    img_arr = centroids[code, :]
    # 将数组转化为对应图像
    img_arr = img_arr.reshape(height, width, channel).astype('uint8')
    im = Image.fromarray(img_arr).convert('RGB')
    im.save(r'.\res-%d.jpg' % k)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值