{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.misc import ascent\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.feature_extraction.image import grid_to_graph\n",
    "from sklearn.cluster import AgglomerativeClustering\n",
    "import dautil as dl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "img = ascent()\n",
    "X = np.reshape(img, (-1, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "connectivity = grid_to_graph(*img.shape)\n",
    "NCLUSTERS = 9\n",
    "ac = AgglomerativeClustering(n_clusters=NCLUSTERS,\n",
    "                             connectivity=connectivity)\n",
    "ac.fit(X)\n",
    "label = np.reshape(ac.labels_, img.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "for l in range(NCLUSTERS):\n",
    "    plt.contour(label == l, contours=1,\n",
    "                colors=[plt.cm.spectral(l/float(NCLUSTERS)), ])\n",
    "\n",
    "dl.plotting.img_show(plt.gca(), img, cmap=plt.cm.gray)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
