图像在相邻区域的颜色相近,我们可以用一种颜色来代替区域中的其它相近颜色。利用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)