最近刚开始接触机器学习,用无监督学习的方法处理了一下自己的头像,整体思路是将图片的每一个像素点作为一个元素,利用K均值聚类将将这些像素点分为两类,黑的全黑白的全白,也可以换各种颜色,先看原图
这是处理之后的图
换个颜色
代码如下
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
class img():
def __init__(self,imgname):
self.imgname=imgname
def img_read(self):
data = plt.imread(self.imgname)
return data
def img_to_pixel(self):
data=self.img_read()
shape=data.shape
pixel=pd.DataFrame(data.reshape([shape[0]*shape[1],shape[2]]),columns=['r','g','b'])
return pixel
def cluster_KMeans(self):
pixel=self.img_to_pixel()
imgdata=self.img_read()
shape=imgdata.shape
cluster=KMeans(n_clusters=2)
cluster.fit(pixel)
label=cluster.labels_
pixel['label']=label
pixel.iloc[pixel[pixel['label'] != 0].index, :3] = [255, 255, 255]
pixel.iloc[pixel[pixel['label'] != 1].index, :3] = [0, 0, 0]
img_label=pixel.values.reshape([shape[0],shape[1],4])
return img_label[:,:,:3]
def plot_img(self):
img_label=self.cluster_KMeans()
plt.imshow(img_label)
plt.show()
if __name__=='__main__':
img=img('1.jpg')
img.plot_img()