最近刚开始接触机器学习 用无监督学习的方法处理了一下自己的头像 整体思路是将图片的每一个像素点作为一个元素 利用K均值聚类将将这些像素点分为两类 黑的全黑白的全白 也可以换各种颜色 先看原图
这是处理之后的图
换个颜色
代买如下
import matplotlib.pyplot as plt import numpy as np 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 [] for i in range(shape[0]): for j in range(shape[1]): pixel.append(data[i,j,:]) 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_.reshape(shape[0],shape[1],1) img_label np.concatenate([imgdata,label],axis 2) return img_label def plot_img(self): img_label self.cluster_KMeans() shape img_label.shape fig,ax plt.subplots() for i in range(shape[0]): for j in range(shape[1]): if img_label[i,j,3]! 0: img_label[i,j,:3] np.array([[[0, 0, 0]]]) else: img_label[i, j, :3] np.array([[[255,255,255]]]) ax.imshow(img_label[:,:,:3]) plt.show() if __name__ __main__ : img img( 1.jpg ) img.plot_img()



