【Python】基于动态规划和K聚类的彩色图片压缩算法

description

引言

当想要压缩一张彩色图像时,彩色图像通常由数百万个颜色值组成,每个颜色值都由红、绿、蓝三个分量组成。因此,如果我们直接对图像的每个像素进行编码,会导致非常大的数据量。为了减少数据量,我们可以尝试减少颜色的数量,从而降低存储需求。

1.主要原理

(一)颜色聚类(Color Clustering):

首先,使用 KMeans 聚类算法将图像中的颜色值聚类为较少数量的颜色簇。聚类的数量由 n_clusters 参数指定。每个像素被归类到与其最接近的聚类中心所代表的颜色簇。颜色聚类的过程大致如下:

  1. 图像转换: 首先,彩色图像被转换为一个包含所有像素颜色值的数据集。每个像素的颜色通常由红、绿、蓝三个分量组成,因此数据集中的每个样本都是一个三维向量,表示一个像素的颜色。
  2. 选择聚类数量: 在应用 KMeans 算法之前,需要确定聚类的数量。这个数量通常由用户指定,通过参数 n_clusters 控制。
  3. 应用 KMeans 算法: 将 KMeans 算法应用于颜色数据集,将颜色值聚类为指定数量的簇。每个簇的质心代表了该簇的平均颜色。
  4. 像素映射: 每个像素的颜色被映射到最接近的簇的质心所代表的颜色。这样,整个图像被转换为由较少数量的颜色值表示的压缩图像。

通过颜色聚类,彩色图像的颜色数量得以减少,从而实现了数据的压缩。压缩后的图像仍然能够保持视觉上的相似性,同时大大降低了存储空间的需求。

(二)动态规划量化(Dynamic Programming Quantization):

接下来,通过动态规划量化算法对颜色进行压缩。这个算法会进一步减少颜色的数量,并尽可能保持图像的质量。参数 max_colors 指定了压缩后图像中的最大颜色数量。算法会尽量选择与原始图像相似的颜色进行保留,以最大程度地保持图像的质量。而在这部分动态规划量化过程大致如下:

  1. 初始化: 首先,初始化状态数组,表示不同颜色数量下的最优颜色组合。通常,初始状态可以是一个空数组或者包含少量颜色的数组。
  2. 状态转移: 根据动态规划的思想,从初始状态开始逐步扩展,计算每个状态下的最优颜色组合。这个过程通常涉及到对每种可能的颜色组合进行评估,并根据优化准则选择最优的组合。
  3. 选择最优解: 最终,选择最优的颜色组合作为压缩后的图像的颜色集合。这个颜色集合将用于替换原始图像中的颜色,从而实现图像的压缩。
  4. 压缩数据保存: 压缩后的图像数据以及相关信息(如原始图像的尺寸、选择的颜色集合等)被保存为 NumPy 数组,并通过 np.savez_compressed() 函数保存到指定路径。

通过动态规划量化,我们能够选择一组颜色,使得压缩后的图像在尽可能减少颜色数量的情况下,仍然能够保持与原始图像相似的视觉效果。这样就实现了对图像数据的进一步压缩。

(三)压缩数据保存:

压缩后的图像数据以及相关信息(如原始图像的尺寸、聚类数、最大颜色数、聚类中心颜色等)被保存为 NumPy 数组,并通过 np.savez_compressed() 函数保存到指定路径。

(四)解压缩过程:

解压缩过程与压缩过程相反。首先加载压缩后的图像数据,然后根据聚类中心颜色替换像素颜色,最后将重构后的图像数据重塑为原始形状,并恢复图像的原始尺寸。

2.彩色图像压缩类

(一)类结构介绍

将上面所述的一个彩色图像的压缩功能整合为一个名为’ColorfulImageCompressor’的类,在这个类中有四个函数,它们的函数名称、接受参数以及介绍如下:

ColorfulImageCompressor类

  • __init__(self, n_clusters, max_colors, resize_factor=0.5): 初始化彩色图像压缩器对象。
  • compress(self, image_path, compressed_file_path): 压缩彩色图像并保存到指定路径。
  • decompress(self, compressed_file_path): 解压缩彩色图像并返回解压缩后的图像对象。
  • _dynamic_programming_quantization(self, image_array): 动态规划量化,将彩色图像颜色量化为指定数量的颜色。

(二)初始化参数

在创建一个彩色图像压缩类的时候需要传入以下三个参数,进行参数的初始化。

  • n_clusters:聚类数,用于 KMeans 算法,指定图像中的颜色数量。
  • max_colors:最大颜色数,用于动态规划量化,指定压缩后图像中的最大颜色数量。
  • resize_factor:缩放因子,用于调整图像尺寸,默认为 0.5,表示将图像尺寸缩小到原始的一半。

(三)函数介绍

(1)compress(self, image_path, compressed_file_path)
  1. 介绍:
    该函数的作用是压缩彩色图像并保存到指定路径。

  2. 参数:
    image_path:原始图像文件路径。
    compressed_file_path:压缩后的图像文件路径。

  3. 函数体:

    def compress(self, image_path, compressed_file_path):
        """
        压缩彩色图像并保存到指定路径。

        参数:
        - image_path:原始图像文件路径。
        - compressed_file_path:压缩后的图像文件路径。
        """
        # 打开图像并转换为 RGB 模式
        image = Image.open(image_path)
        image = image.convert('RGB')

        # 根据缩放因子调整图像大小
        new_size = (int(image.width * self.resize_factor), int(image.height * self.resize_factor))
        image = image.resize(new_size)

        # 将图像转换为 NumPy 数组并重塑为二维数组
        np_image = np.array(image)
        original_shape = np_image.shape
        np_image = np_image.reshape(-1, 3)

        # 使用动态规划量化对图像进行压缩
        compressed_data = self._dynamic_programming_quantization(np_image)

        # 保存压缩后的图像数据到指定路径
        np.savez_compressed(compressed_file_path, np_image=compressed_data['np_image'], original_shape=original_shape, n_clusters=self.n_clusters, max_colors=self.max_colors, center_colors=compressed_data['center_colors'])
(2)decompress(self, compressed_file_path)
  1. 介绍:
    解压缩彩色图像并返回解压缩后的图像对象。
  2. 参数:
    compressed_file_path:压缩后的图像文件路径。
    返回:
    reconstructed_image:解压缩后的图像对象。
  3. 函数体:
    def decompress(self, compressed_file_path):
        """
        解压缩彩色图像并返回解压缩后的图像对象。

        参数:
        - compressed_file_path:压缩后的图像文件路径。

        返回:
        - reconstructed_image:解压缩后的图像对象。
        """
        # 加载压缩后的图像数据
        compressed_data = np.load(compressed_file_path)
        np_image = compressed_data['np_image'].reshape(-1, 3)
        center_colors = compressed_data['center_colors']

        # 根据聚类中心替换像素颜色
        for i in range(self.n_clusters):
            np_image[np_image[:, 0] == i] = center_colors[i]

        # 将重构后的图像数据重塑为原始形状
        original_shape = compressed_data['original_shape']
        reconstructed_image = np_image.reshape(*original_shape).astype('uint8')
        reconstructed_image = Image.fromarray(reconstructed_image, 'RGB')

        # 恢复图像原始尺寸
        original_size = (int(reconstructed_image.width / self.resize_factor), int(reconstructed_image.height / self.resize_factor))
        reconstructed_image = reconstructed_image.resize(original_size)

        return reconstructed_image
(3)_dynamic_programming_quantization(self, image_array)
  1. 介绍:
    动态规划量化,将彩色图像颜色量化为指定数量的颜色。
  2. 参数:
    image_array:图像数据的 NumPy 数组表示。
    返回:
    compressed_data:包含压缩后图像数据及相关信息的字典。
  3. 函数体:
    def _dynamic_programming_quantization(self, image_array):
        """
        动态规划量化,将彩色图像颜色量化为指定数量的颜色。

        参数:
        - image_array:图像数据的 NumPy 数组表示。

        返回:
        - compressed_data:包含压缩后图像数据及相关信息的字典。
        """
        # 使用 KMeans 进行聚类
        kmeans = KMeans(n_clusters=self.n_clusters)
        labels = kmeans.fit_predict(image_array)
        quantized_image = np.zeros_like(image_array)

        # 遍历每个聚类簇
        for i in range(self.n_clusters):
            # 获取当前簇的像素颜色及其出现次数
            cluster_pixels = image_array[labels == i]
            unique_colors, color_counts = np.unique(cluster_pixels, axis=0, return_counts=True)
            
            # 选取出现次数最多的前 max_colors 个颜色作为量化后的颜色
            color_indices = np.argsort(color_counts)[::-1][:self.max_colors]
            quantized_colors = unique_colors[color_indices]

            # 计算聚类中像素与量化后颜色的距离
            distances = np.linalg.norm(cluster_pixels[:, None] - quantized_colors, axis=2)
            quantized_indices = np.argmin(distances, axis=1)

            # 使用量化后颜色替换聚类中的像素颜色
            quantized_image[labels == i] = quantized_colors[quantized_indices]

        # 存储聚类中心颜色
        center_colors = kmeans.cluster_centers_.astype('uint8')

        return {'np_image': quantized_image, 'n_clusters': self.n_clusters, 'max_colors': self.max_colors, 'center_colors': center_colors}

(四)使用说明

# 创建压缩器对象  
compressor = ColorfulImageCompressor(n_clusters=4, max_colors=2, resize_factor=0.5)  
  
# 压缩彩色图像  
image_path = "./img/image2.jpg"  
compressed_file_path = "./npz/compressed_image2_n4_c2.npz"  
compressor.compress(image_path, compressed_file_path)  
  
# 解压缩图像并显示  
reconstructed_image = compressor.decompress(compressed_file_path)  
reconstructed_image.show()  
reconstructed_image.save("./img/reconstructed_image2_n4_c2.jpg")  

3.测试结果

测试图片我们使用的采用的一张818*818分辨率,大小为79.49KB的彩色图片。分别使用不同的聚类数量和颜色数量来进行测试。

descriptiondescription
原始图片聚类数为8,颜色为2的压缩图片

详细运行数据如下表(下面文件名中的n为聚类数,而c为颜色数):

文件名原始大小(KB)压缩后的中间文件大小(KB)解压缩后的图片大小 (KB)
reconstructed_image2_n4_c279.4929.541.7
reconstructed_image2_n4_c479.4949.345.2
reconstructed_image2_n4_c879.4970.951.3
reconstructed_image2_n4_c1679.4994.359.3
reconstructed_image2_n8_c279.4948.348.7
reconstructed_image2_n8_c479.4973.352.5
reconstructed_image2_n8_c879.4910159.1
reconstructed_image2_n8_c1679.4912561.1

结束语

如果有疑问欢迎大家留言讨论,你如果觉得这篇文章对你有帮助可以给我一个免费的赞吗?你们的认可是我最大的分享动力!

### K-means聚类算法原理 K-means是一种广泛应用于数据分析机器学习领域中的无监督学习方法,用于解决聚类问题。此算法旨在将给定的数据集划分为预定义数量\(K\)的簇(cluster),使得每个簇内的对象尽可能相似,而不同簇之间的差异最大化。 具体而言,在每次迭代过程中,算法执行两个主要操作: - **分配阶段**:计算每个观测点到各个质心的距离,并将其指派至最近的那个质心所代表的簇; - **更新阶段**:重新计算各簇的新质心位置,即该簇内所有成员坐标的平均值; 上述过程会持续循环直到满足特定停止条件为止,比如达到最大迭代次数或是前后两次迭代间质心变化幅度小于设定阈值[^2]。 值得注意的是,由于K-means采用随机方式初始化质心,这可能导致最终结果依赖于初始状态的选择,从而影响收敛速度甚至得到局部最优解而非全局最佳方案[^1]。 为了改善这一情况,实践中常使用一种称为K-means++的方法来优化初值选取策略,通过更合理的方式挑选初始质心以提高整体性能表现。 另外还存在一些变体形式如Kernel-KMeans,其核心思想是在原始特征基础上引入核函数映射技术,先将样本投影转换成更高维度的空间后再实施标准版K-means运算逻辑,以此增强模型捕捉复杂结构模式的能力[^3]。 #### 应用实例 考虑到实际场景下的需求多样性,这里给出一个基于Python编程语言利用`scikit-learn`库实现简单图像压缩的例子作为示范用途之一: ```python from sklearn.cluster import MiniBatchKMeans import numpy as np import matplotlib.pyplot as plt def image_compression(image_path, n_colors=64): # 加载图片并转化为二维数组 (height * width, color_depth) img = plt.imread(image_path).reshape(-1, 3) # 使用MiniBatchKMeans进行颜色量化 kmeans = MiniBatchKMeans(n_clusters=n_colors, random_state=0).fit(img) # 将像素替换为其最接近的颜色中心 compressed_img = kmeans.cluster_centers_[kmeans.predict(img)].astype(np.uint8) return compressed_img.reshape(plt.imread(image_path).shape) # 展示原图与压缩后效果对比 fig, ax = plt.subplots(1, 2, figsize=(12, 6)) ax[0].imshow(plt.imread('example.jpg')) ax[0].set_title('Original Image') compressed_image = image_compression('example.jpg', n_colors=64) ax[1].imshow(compressed_image) ax[1].set_title(f'Compressed to {64} colors') for a in ax.flat: a.set_axis_off() plt.show() ``` 这段代码展示了如何借助K-means减少一幅彩色照片中可用色彩的数量,进而实现一定程度上的文件大小缩减目的的同时保持视觉质量基本不变的效果[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

SheathedSharp

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值