Python 无监督图像分割 代码实操

目的: 将RGB图像进行无监督语义分割(将地面、楼顶、楼测、树木分割出来)。
输入:
请添加图片描述

  • 1、K-means方法
import numpy as np
import matplotlib.pyplot as plt
import cv2
from sklearn.cluster import KMeans

img = cv2.imread(r'E:\odmxiaoyuan\notree\right\class_rec_A\10\20.jpg')#打开的是BGR模式的图
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)#转化为RGB
width = img.shape[0]
height = img.shape[1]

#RGB3通道,每个通道都展平来分割K类
img = img.reshape(-1,3)
k = 4   #自己定义的主颜色分类将地面、楼顶、楼测、树木,4类
classifier = KMeans(n_clusters=k,max_iter=100,
                init='k-means++')#建立分类器
kmeans = classifier.fit(img)#进行分类
#得到图像分类的标签
labels = kmeans.labels_#得到了每个像素点位置的标签
dominating_colors = np.array(kmeans.cluster_centers_,dtype='uint8')#确定了每种分类的核心颜色RGB组成
print(dominating_colors)#可以看到4行,每行3列为别为RGB的值
colors = []
for col in dominating_colors:
	r = col[0]
	g = col[1]
	b = col[2]
	colors.append([r, g, b])
segmented_img = np.zeros((img.shape[0],3),dtype='uint8')
segmented_img2 = np.zeros((img.shape[0],3),dtype='uint8')
#将每个像素点都进行分类
for pix in range(segmented_img.shape[0]):
	r_g_b = colors[labels[pix]]
	segmented_img[pix] = r_g_b
#将展平的像素点转为原图的二维
segmented_img = segmented_img.reshape((width,height,3))
plt.imshow(segmented_img)#原色4种颜色展示
#不方便观测分类,转为显著的颜色(红,黄,蓝,绿)
colors2=[[255,0,0],[255,255,0],[0,0,255],[0,255,0]]
for pix in range(segmented_img2.shape[0]):
	r_g_b = colors2[labels[pix]]
	segmented_img2[pix] = r_g_b
#将展平的像素点转为原图的二维
segmented_img2 = segmented_img2.reshape((width,height,3))
plt.imshow(segmented_img2)
#联合出图
plt.subplot(131)
plt.imshow(img),plt.axis('off'),plt.title('original')
plt.subplot(132)
plt.imshow(segmented_img),plt.axis('off'),plt.title('Primary Color')
plt.subplot(133)
plt.imshow(segmented_img2),plt.axis('off'),plt.title('Different color')
plt.show()

在这里插入图片描述
可以看出来分类效果不佳。
2、

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值