python实现简单KMeans算法

匿名 (未验证) 提交于 2019-12-02 22:51:30

参考链接:北京理工大学公开课

code:

import numpy as np import PIL.Image as image # PILfrom sklearn.cluster import KMeans # KMeans # def loadData(filepath):     # "rb"    f = open(filepath,"rb")     data = []     img = image.open(f)     m,n = img.size     for i in range(m):         for j in range(n):             x,y,z = img.getpixel((i,j))             data.append([x/256.0,y/256.0,z/256.0])     f.close()     return np.mat(data),m,n  imageData,row,col = loadData(".//data//bull.jpg")  # km = KMeans(n_clusters=3) label =  km.fit_predict(imageData) label = label.reshape([row,col])  # # "L"pic_new = image.new("L",(row,col))  # for i in range(row):     for j in range(col):         pic_new.putpixel((i,j),int(256/(label[i][j]+1)))  # JPEGpic_new.save("After_segmentation_bull.jpg","JPEG")

Original_image:


Output_image:


The end.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!