聚类算法实现图像压缩

原本表示一种颜色需要 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])

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值