首页 > 编程知识 正文

python实现聚类实例讲解,水平集图像分割python

时间:2023-05-04 04:34:19 阅读:152190 作者:2259

【Python实例第19集】图像分割的光谱聚类

发布时间: 2018-11-25 19:51、

陟览次数: 272

、标签:

Python

机器学习训练营——机器学习爱好者的自由交流空间(进入群qq:2279055353 ) )。

在数据的多元统计和聚类中,谱聚类技术利用数据相似矩阵的谱,即相似矩阵的特征值来降低特征维数。 然后,在降维后的空间中使用k均值

聚类。 的相似矩阵度量数据集任意两点的相似性。

本示例使用谱聚类方法spectral clustering生成具有连续圆形区域的图像

把这些区域分开。 在这种情况下,谱聚类法解决了标准的图像分割问题。 图像被认为是由三维像素连接而成的图,谱聚类算法等于选择图中分割的区域,将沿分割的梯度变化率最小化。 因为该算法试图平衡区域的大小,所以如果我们分隔的圆的大小不同,分割就等于失败。

详细调查实例

首先,从scikit-learn的feature_extraction中导入image,从clusters中导入频谱聚类函数spectral_clustering

在. image中定义四个圆区域。

importnumpyasnpimportmatplotlib.pyplotaspltfrom

sk learn.feature _ extractionimportimagefromsklearn.cluster import

spectral_clustering l=100 x,y=NP.indices () l,l ) ) (center1=(28,24 ) ) ) ) ) ) )

center2=(40,50 ) center3=) 67,58 ) center4=) 24,70 ) radius1,radius2,

radius3,radius4=16,14,15,14 circle1=(x-center1[0] ) *2) y-

center1[1] * *2radius1* *2circle2=(x-center2[0] ) *2) y-

center2[1] * *2radius2* *2circle3=(x-center3[0] ) *2) y-

center3[1] * *2radius3* *2circle4=(x-center4[0] ) *2) y-

center4[1]**2radius4**2

在这里,我想把被定义的四个区域分开,而不是从背景中分开。 因此,使用mask限制背景。

#4circles img=circle1circle2circle3circle4# weuseamaskthat

limitstotheforeground 3360 theproblemthatweare # interestedinhereisnot

separatingtheobjectsfromthebackground,# but separating them one from the

other.mask=img.astype(bool ) img=img.astype ) float ) img =1 0.2 *

NP.random.randn(img.shape ) converttheimageintoagraphwiththevalueof

thegradientonthe # edges.graph=image.img _ to _ graph (img,mask=mask ) # Take

adecreasingfunctionofthegradient : wetakeitweakly # dependent from the

gradientthesegmentationisclosetoavoronoigraph.data=NP.exp (-graph.data

/graph.data.std () (# Force the solver to be arpack,since amg is numerically # ) )

unstableonthisexamplelabels=spectral _ clustering (graph,n_clusters=4,

eigen_solver='arpack ' ) label_im=NP.full(mask.shape,-1. ) label_im[mask]=

labelsPLT.matshow(img ) PLT.mat show (label _ im ) plt.show ) )。

下一步是分隔两个圆的区域。

#2circles img=circle1circle2mask=img.as type (bool ) img=

img.astype(float ) img=10.2*NP.random.randn ) img.shape ) graph=

image.img_to_graph(img,mask=mask ) graph.data=NP.exp(-graph.data/

graph.data.std () labels=spectral_clustering ) graph,n_clusters=2,

eigen_solver='arpack ' ) label_im=NP.full(mask.shape,-1. ) label_im[mask]=

labelsPLT.matshow(img ) PLT.mat show (label _ im ) plt.show ) )。

更多详情请关注微信公众号“统计学习与大数据”

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。