print(__doc__)# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>, Brian Cheung# License: BSD 3 clauseimporttimeimportnumpyasnpimportscipyasspimportmatplotlib.pyplotaspltfromsklearn.feature_extractionimportimagefromsklearn.clusterimportspectral_clusteringlena=sp.misc.lena()# Downsample the image by a factor of 4lena=lena[::2,::2]+lena[1::2,::2]+lena[::2,1::2]+lena[1::2,1::2]lena=lena[::2,::2]+lena[1::2,::2]+lena[::2,1::2]+lena[1::2,1::2]# Convert the image into a graph with the value of the gradient on the# edges.graph=image.img_to_graph(lena)# Take a decreasing function of the gradient: an exponential# The smaller beta is, the more independent the segmentation is of the# actual image. For beta=1, the segmentation is close to a voronoibeta=5eps=1e-6graph.data=np.exp(-beta*graph.data/lena.std())+eps# Apply spectral clustering (this step goes much faster if you have pyamg# installed)N_REGIONS=11################################################################################ Visualize the resulting regionsforassign_labelsin('kmeans','discretize'):t0=time.time()labels=spectral_clustering(graph,n_clusters=N_REGIONS,assign_labels=assign_labels,random_state=1)t1=time.time()labels=labels.reshape(lena.shape)plt.figure(figsize=(5,5))plt.imshow(lena,cmap=plt.cm.gray)forlinrange(N_REGIONS):plt.contour(labels==l,contours=1,colors=[plt.cm.spectral(l/float(N_REGIONS)),])plt.xticks(())plt.yticks(())plt.title('Spectral clustering: %s, %.2fs'%(assign_labels,(t1-t0)))plt.show()

Total running time of the example: 60.48 seconds
( 1 minutes 0.48 seconds)