Skip to content

Instantly share code, notes, and snippets.

@jaidevd
Created April 3, 2012 00:43
Show Gist options
  • Save jaidevd/2288343 to your computer and use it in GitHub Desktop.
Save jaidevd/2288343 to your computer and use it in GitHub Desktop.
Image Segmentation by Clustering
#!/usr/bin/env python -tt
import numpy as np
import scipy as sp
import pylab as pl
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import KMeans
from scikits.image.data import imread
# Read image
im = imread('sandeep hardas.jpg')
# Make the feature vectors
X = np.reshape(im, (im.shape[0]*im.shape[1], im.shape[2]))
# Perform Clustering
N_clus = 3
km = KMeans(k = N_clus, init = 'random')
km.fit(X.astype(float)) # the .astype method is only to stop the .fit method
# from throwing a warning.
labels = np.reshape(km.labels_, im.shape[0:2])
# Plotting results
pl.figure()
pl.imshow(im)
for l in range(N_clus):
pl.contour(label == l, contours=1, \
colors=[pl.cm.spectral(l / float(N_clus)), ])
pl.xticks(())
pl.yticks(())
pl.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment