原本表示一种颜色需要 RGB 三种颜色, 每种颜色 8 比特,故需要 24 比特。
通过聚类算法,选取颜色空间的 8 个聚类中心,将图片上每种颜色分配到 1 个类别,那么表示一种颜色只需要 3 比特,直接压缩到 1/8。
代码
读取图片
import cv2
import numpy as np
from scipy.cluster.vq import kmeans2
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
img = cv2.imread('home.jpg')
# img.shape (720, 1280, 3)
img_reshape = img.reshape((-1,3))
# img_reshape.shape (921600, 3)
压缩
用 3 比特来表示一种颜色
n_cluster = 8 # 8=2^3
centers, labels = kmeans2(img_reshape.astype(np.float), n_cluster, minit='points')
compressed_img = np.asarray(labels)
解压
recovered_img = []
for i in compressed_img:
recovered_img.append(centers[i])
recovered_img = np.asarray(recovered_img).reshape(img.shape)
结果展示
plt.figure(figsize=(40,10))
plt.subplot(1,2,1)
plt.imshow(img[:,:,::-1])
plt.subplot(1,2,2)
plt.imshow(recovered_img.astype(np.int)[:,:,::-1])