python——数据挖掘学习_聚类——压缩图片

这个是今天上课做的实验,就先把代码贴上来先吧

import numpy as np

from scipy import misc

from sklearn import cluster

import matplotlib.pyplot as plt

###STEP1###

#compress_image函数实现图片压缩功能,compress_image函数将每个像素作为一个元素进行聚类,以此减少其颜色个数。

#参数img是图片传入的接口,因此我们需要知道变量img的数据结构,请自行查看。

def compress_image(img, num_clusters):

    #思考,聚类算法对输入的数据结构要求如何?

    #问题一:补全代码,将img结构进行转换即每个像素作为一个元素,使之能符合聚类算法数据输入的要求。

    X = img.reshape(-1,1)  #自动生成一个一列的矩阵 多少行由-1觉得

    # 创建KMeans聚类模型,并训练

    kmeans = cluster.KMeans(n_clusters=num_clusters, n_init=4, random_state=5)

    kmeans.fit(X)

    #问题二:补全代码,分别获取每个数据聚类后的label,以及每个label的质心。

    lable = kmeans.labels_

    centroids = kmeans.cluster_centers_.squeeze() #squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉

    #问题三:使用质心的数值代替原数据的label值,那么我们将获得一个新的图像。

    # 提示,使用numpy的choose函数进行进行质心值的代替,reshape函数回复原图片的数据结构,并返回结果。

    input_image_compressed = np.choose(lable,centroids).reshape(img.shape)

    return input_image_compressed

###STEP2###

#plot_image函数打印图片

def plot_image(img, title):

    vmin = img.min()

    vmax = img.max()

    plt.figure()

    plt.title(title)

    plt.imshow(img, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)

###STEP3###

#读入图片,设置压缩率,实现压缩

if __name__=='__main__':

    #设置图片的路径和压缩比例

    input_file = "G:\lzypy\pandans.jpg"

    num_bits = 2

    if not 1 <= num_bits <= 8:

        raise TypeError('Number of bits should be between 1 and 8')

    num_clusters = np.power(2, num_bits)

    # 输出压缩的比例

    compression_rate = round(100 * (8.0 - num_bits) / 8.0, 2)

    print ("\nThe size of the image will be reduced by a factor of", 8.0/num_bits)

    print ("\nCompression rate = " + str(compression_rate) + "%")

    # 加载需要压缩的图片

    input_image = misc.imread(input_file, True).astype(np.uint8)

    # 原始图像的输出

    plot_image(input_image, 'Original image')

    # 压缩后的图像输出

    input_image_compressed = compress_image(input_image, num_clusters)

    plot_image(input_image_compressed, 'Compressed image; compression rate = ' + str(compression_rate) + '%')

    plt.show()


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容