In [2]:
import time as time
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering

In [25]:
###############################################################################
# Generate data
lena = sp.misc.face()
# Downsample the image by a factor of 4
#lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2]
X = np.reshape(lena, (-1, 1))

In [27]:
X[0]


Out[27]:
array([121], dtype=uint8)

In [31]:
# connectivity


Out[31]:
<2359296x2359296 sparse matrix of type '<type 'numpy.int64'>'
	with 14931456 stored elements in COOrdinate format>

In [24]:
lena.shape


Out[24]:
(768, 1024, 3)

In [30]:
###############################################################################
# Define the structure A of the data. Pixels connected to their neighbors.
connectivity = grid_to_graph(*lena.shape)

In [10]:
##############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
st = time.time()
n_clusters = 15  # number of regions
ward = AgglomerativeClustering(n_clusters=n_clusters,
        linkage='ward', connectivity=connectivity).fit(X)
label = np.reshape(ward.labels_, lena.shape)
print("Elapsed time: ", time.time() - st)
print("Number of pixels: ", label.size)
print("Number of clusters: ", np.unique(label).size)


Compute structured hierarchical clustering...
('Elapsed time: ', 139.56812500953674)
('Number of pixels: ', 589824)
('Number of clusters: ', 15)

In [11]:
###############################################################################
# Plot the results on an image
plt.figure(figsize=(5, 5))
plt.imshow(lena, cmap=plt.cm.gray)
for l in range(n_clusters):
    plt.contour(label == l, contours=1,
                colors=[plt.cm.spectral(l / float(n_clusters)), ])
plt.xticks(())
plt.yticks(())
plt.show()


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-fa88e7264545> in <module>()
      5 for l in range(n_clusters):
      6     plt.contour(label == l, contours=1,
----> 7                 colors=[plt.cm.spectral(l / float(n_clusters)), ])
      8 plt.xticks(())
      9 plt.yticks(())

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/pyplot.pyc in contour(*args, **kwargs)
   2764         ax.hold(hold)
   2765     try:
-> 2766         ret = ax.contour(*args, **kwargs)
   2767     finally:
   2768         ax.hold(washold)

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
   1810                     warnings.warn(msg % (label_namer, func.__name__),
   1811                                   RuntimeWarning, stacklevel=2)
-> 1812             return func(ax, *args, **kwargs)
   1813         pre_doc = inner.__doc__
   1814         if pre_doc is None:

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in contour(self, *args, **kwargs)
   5642             self.cla()
   5643         kwargs['filled'] = False
-> 5644         return mcontour.QuadContourSet(self, *args, **kwargs)
   5645     contour.__doc__ = mcontour.QuadContourSet.contour_doc
   5646 

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/contour.pyc in __init__(self, ax, *args, **kwargs)
   1422         are described in QuadContourSet.contour_doc.
   1423         """
-> 1424         ContourSet.__init__(self, ax, *args, **kwargs)
   1425 
   1426     def _process_args(self, *args, **kwargs):

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/contour.pyc in __init__(self, ax, *args, **kwargs)
    861         self._transform = kwargs.get('transform', None)
    862 
--> 863         self._process_args(*args, **kwargs)
    864         self._process_levels()
    865 

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/contour.pyc in _process_args(self, *args, **kwargs)
   1443                 self._corner_mask = mpl.rcParams['contour.corner_mask']
   1444 
-> 1445             x, y, z = self._contour_args(args, kwargs)
   1446 
   1447             _mask = ma.getmask(z)

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/contour.pyc in _contour_args(self, args, kwargs)
   1523         if Nargs <= 2:
   1524             z = ma.asarray(args[0], dtype=np.float64)
-> 1525             x, y = self._initialize_x_y(z)
   1526             args = args[1:]
   1527         elif Nargs <= 4:

/Users/alfredogarbuno/anaconda/envs/hashcode/lib/python2.7/site-packages/matplotlib/contour.pyc in _initialize_x_y(self, z)
   1608         """
   1609         if z.ndim != 2:
-> 1610             raise TypeError("Input must be a 2D array.")
   1611         else:
   1612             Ny, Nx = z.shape

TypeError: Input must be a 2D array.

In [ ]: