一、简介
图像分割是将图像分成多个分割的任务。在语义分割中,属于同一对象类型的所有像素均被分配给同一像素。
这里做一个简单的颜色分割。如果像素具有相似的颜色,就将它们分配给同一分割。
二、原图
原图:我家小可爱的魔方大军,xixixi
三、步骤分析
- 读取图像
- 对图像矩阵进行KMeans聚类
- 输出图像并观察结果
四、代码
1. 导包
from matplotlib.image import imread
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
2.读取图像
img = imread(r'./a.jpg')
img.shape
结果为:
3. 裁剪图像并重置矩阵
img = img[1500:2000,1500:2000] #裁剪图像,原图像训练时间过长
X = img.reshape(-1,3) #reshape为三列,即每个像素点的RGB值
plt.imshow(img)
img.shape
结果为:
4. 聚类
1.难点
2. 代码
plt.figure(figsize = (10,10)) #定义画布大小
segmented_imgs = []
n_colors = [10,8,6,4,2] #聚类簇的个数
plt.subplot(231)
plt.title("Original image") #原图
plt.imshow(img)
for n_clusters in n_colors:
kmeans = KMeans(n_clusters = n_clusters ,random_state = 42).fit(X)
#对矩阵X进行训练
segmented_img = kmeans.cluster_centers_[kmeans.labels_]
#kmeans.labels_是每个样本点的归属中心点
segmented_imgs.append(segmented_img.reshape(img.shape)/255)
#将图像reshape成原图像大小
for idx,n_clusters in enumerate(n_colors):
plt.subplot(232+idx)
plt.imshow(segmented_imgs[idx])
plt.title("cluster = {}".format(n_clusters))
plt.show()
结果为: