栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

聚类:K-means进行图像压缩

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

聚类:K-means进行图像压缩

from numpy.core.fromnumeric import reshape
from skimage import io
from sklearn import cluster 
from sklearn.cluster import KMeans
import numpy as np

#第一步读取图像
image = io.imread("ladybug.png")
# io.imshow(image)
# io.show()

#第二步取出长和宽
rows = image.shape[0]
cols = image.shape[1]
# print("rows:"+int(rows))

#第三步选取reshape,选取kmeans进行训练(fit)
#reshape成为一个二维样本 ,3为三个通道
image = image.reshape(image.shape[0]*image.shape[1],3)    
kmeans = KMeans(n_clusters=128,n_init=10,max_iter=200)     #分为128个簇,使用cpu数量,最大迭代次数
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
kmeans.fit(image)       #进行训练

#第四步将labels图像转为灰度图
clusters = np.asarray(kmeans.cluster_centers_,dtype=np.uint8)
labels = np.asarray(kmeans.labels_,dtype=np.uint8)
labels = labels.reshape(rows,cols)   #转化为灰度图
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
print(clusters.shape)
np.save("codebook_test.npy",clusters)
io.imsave("compressed_test.jpg",labels)


image1 = io.imread("compressed_test.jpg")
io.imshow(image1)
io.show()
print("**********************************")

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/619238.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号