{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "from matplotlib import pyplot as plt\n",
    "from sklearn.datasets import load_sample_image\n",
    "import dautil as dl\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('extracting_patches')\n",
    "lr = dl.nb.LatexRenderer(chapter=11, start=4, context=context)\n",
    "lr.render(r'\\sigma^2_w(t)=\\omega_1(t)\\sigma^2_1(t)+\\omega_2(t)\\sigma^2_2(t) ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "context = dl.nb.Context('extracting_patches')\n",
    "dl.nb.RcWidget(context)\n",
    "dl.nb.LabelWidget(2, 2, context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sp = dl.plotting.Subplotter(2, 2, context)\n",
    "img = load_sample_image('flower.jpg')\n",
    "dl.plotting.img_show(sp.ax, img)\n",
    "sp.label()\n",
    "\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "_, thresh = cv2.threshold(gray, 0, 255,\n",
    "                          cv2.THRESH_OTSU)\n",
    "\n",
    "dl.plotting.img_show(sp.next_ax(), thresh)\n",
    "sp.label()\n",
    "\n",
    "kernel = np.ones((3, 3), np.uint8)\n",
    "opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,\n",
    "                           kernel, iterations=2)\n",
    "\n",
    "bg = cv2.dilate(opening, kernel, iterations=3)\n",
    "\n",
    "dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)\n",
    "_, fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(),\n",
    "                      255, 0)\n",
    "\n",
    "fg = np.uint8(fg)\n",
    "rest = cv2.subtract(bg, fg)\n",
    "\n",
    "dl.plotting.img_show(sp.next_ax(), rest)\n",
    "sp.label()\n",
    "\n",
    "_, markers = cv2.connectedComponents(fg)\n",
    "markers += 1\n",
    "markers[rest == 255] = 0\n",
    "\n",
    "dl.plotting.img_show(sp.next_ax(), markers)\n",
    "sp.label()\n",
    "\n",
    "HTML(sp.exit())"
   ]
  }
 ],
 "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
}
