zoukankan      html  css  js  c++  java
  • K-means算法应用:图片压缩

    from sklearn.datasets import load_sample_image
    from sklearn.cluster import KMeans
    import matplotlib.pyplot as plt
    import numpy as np
    
    china = load_sample_image("china.jpg")
    plt.imshow(china)
    plt.show()

    image = china[::3,::3] #降低分辨率
    X = image.reshape(-1,3)
    print(china.shape,image.shape,X.shape)

    x=image.reshape(-1,3)            #重造数组
    n_colors = 64                    #(256,256,256)
    model = KMeans(n_colors)
    labels = model.fit_predict(X)    #每个点的颜色分类,0-63
    colors = model.cluster_centers_    #64个聚类中心,颜色值
    new_image=colors[labels]#进行颜色填充
    new_image=image.reshape(143,214,3)
    new_image=new_image.reshape(image.shape)    #还原原来的数组
    plt.imshow(image);
    plt.show()
    plt.imshow(new_image.astype(np.uint8)  )#转换为数据类型
    plt.show()

    #查看图片大小
    import sys
    print(sys.getsizeof(china)) #原图片
    print(sys.getsizeof(new_image))  #新图片

    #将原始图片与新图片保存成文件,观察文件的大小。
    import matplotlib.image as img
    img.imsave('img.jpg',china)
    
    img.imsave('new_image.jpg',new_image)

     

     

  • 相关阅读:
    切蛋糕
    STL----deque
    Java语法 [常识1]
    SQL Server 数据库基础编程
    SQL Server 数据库基础编程
    SQL Server 索引和视图
    SQL Server 索引和视图
    SQL Server 事务、异常和游标
    SQL Server 事务、异常和游标
    SQL Server 存储过程
  • 原文地址:https://www.cnblogs.com/fanfanfan/p/9917256.html
Copyright © 2011-2022 走看看