{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Local Binary Pattern for texture classification\n\nIn this example, we will see how to classify textures based on LBP (Local\nBinary Pattern). LBP looks at points surrounding a central point and tests\nwhether the surrounding points are greater than or less than the central point\n(i.e. gives a binary result).\n\nBefore trying out LBP on an image, it helps to look at a schematic of LBPs.\nThe below code is just used to plot the schematic.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nMETHOD = 'uniform'\nplt.rcParams['font.size'] = 9\n\n\ndef plot_circle(ax, center, radius, color):\n    circle = plt.Circle(center, radius, facecolor=color, edgecolor='0.5')\n    ax.add_patch(circle)\n\n\ndef plot_lbp_model(ax, binary_values):\n    \"\"\"Draw the schematic for a local binary pattern.\"\"\"\n    # Geometry spec\n    theta = np.deg2rad(45)\n    R = 1\n    r = 0.15\n    w = 1.5\n    gray = '0.5'\n\n    # Draw the central pixel.\n    plot_circle(ax, (0, 0), radius=r, color=gray)\n    # Draw the surrounding pixels.\n    for i, facecolor in enumerate(binary_values):\n        x = R * np.cos(i * theta)\n        y = R * np.sin(i * theta)\n        plot_circle(ax, (x, y), radius=r, color=str(facecolor))\n\n    # Draw the pixel grid.\n    for x in np.linspace(-w, w, 4):\n        ax.axvline(x, color=gray)\n        ax.axhline(x, color=gray)\n\n    # Tweak the layout.\n    ax.axis('image')\n    ax.axis('off')\n    size = w + 0.2\n    ax.set_xlim(-size, size)\n    ax.set_ylim(-size, size)\n\n\nfig, axes = plt.subplots(ncols=5, figsize=(7, 2))\n\ntitles = ['flat', 'flat', 'edge', 'corner', 'non-uniform']\n\nbinary_patterns = [\n    np.zeros(8),\n    np.ones(8),\n    np.hstack([np.ones(4), np.zeros(4)]),\n    np.hstack([np.zeros(3), np.ones(5)]),\n    [1, 0, 0, 1, 1, 1, 0, 0],\n]\n\nfor ax, values, name in zip(axes, binary_patterns, titles):\n    plot_lbp_model(ax, values)\n    ax.set_title(name)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The figure above shows example results with black (or white) representing\npixels that are less (or more) intense than the central pixel. When\nsurrounding pixels are all black or all white, then that image region is\nflat (i.e. featureless). Groups of continuous black or white pixels are\nconsidered \"uniform\" patterns that can be interpreted as corners or edges.\nIf pixels switch back-and-forth between black and white pixels, the pattern\nis considered \"non-uniform\".\n\nWhen using LBP to detect texture, you measure a collection of LBPs over an\nimage patch and look at the distribution of these LBPs. Lets apply LBP to a\nbrick texture.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage.transform import rotate\nfrom skimage.feature import local_binary_pattern\nfrom skimage import data\nfrom skimage.color import label2rgb\n\n# settings for LBP\nradius = 3\nn_points = 8 * radius\n\n\ndef overlay_labels(image, lbp, labels):\n    mask = np.logical_or.reduce([lbp == each for each in labels])\n    return label2rgb(mask, image=image, bg_label=0, alpha=0.5)\n\n\ndef highlight_bars(bars, indexes):\n    for i in indexes:\n        bars[i].set_facecolor('r')\n\n\nimage = data.brick()\nlbp = local_binary_pattern(image, n_points, radius, METHOD)\n\n\ndef hist(ax, lbp):\n    n_bins = int(lbp.max() + 1)\n    return ax.hist(\n        lbp.ravel(), density=True, bins=n_bins, range=(0, n_bins), facecolor='0.5'\n    )\n\n\n# plot histograms of LBP of textures\nfig, (ax_img, ax_hist) = plt.subplots(nrows=2, ncols=3, figsize=(9, 6))\nplt.gray()\n\ntitles = ('edge', 'flat', 'corner')\nw = width = radius - 1\nedge_labels = range(n_points // 2 - w, n_points // 2 + w + 1)\nflat_labels = list(range(0, w + 1)) + list(range(n_points - w, n_points + 2))\ni_14 = n_points // 4  # 1/4th of the histogram\ni_34 = 3 * (n_points // 4)  # 3/4th of the histogram\ncorner_labels = list(range(i_14 - w, i_14 + w + 1)) + list(\n    range(i_34 - w, i_34 + w + 1)\n)\n\nlabel_sets = (edge_labels, flat_labels, corner_labels)\n\nfor ax, labels in zip(ax_img, label_sets):\n    ax.imshow(overlay_labels(image, lbp, labels))\n\nfor ax, labels, name in zip(ax_hist, label_sets, titles):\n    counts, _, bars = hist(ax, lbp)\n    highlight_bars(bars, labels)\n    ax.set_ylim(top=np.max(counts[:-1]))\n    ax.set_xlim(right=n_points + 2)\n    ax.set_title(name)\n\nax_hist[0].set_ylabel('Percentage')\nfor ax in ax_img:\n    ax.axis('off')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The above plot highlights flat, edge-like, and corner-like regions of the\nimage.\n\nThe histogram of the LBP result is a good measure to classify textures.\nHere, we test the histogram distributions against each other using the\nKullback-Leibler-Divergence.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# settings for LBP\nradius = 2\nn_points = 8 * radius\n\n\ndef kullback_leibler_divergence(p, q):\n    p = np.asarray(p)\n    q = np.asarray(q)\n    filt = np.logical_and(p != 0, q != 0)\n    return np.sum(p[filt] * np.log2(p[filt] / q[filt]))\n\n\ndef match(refs, img):\n    best_score = 10\n    best_name = None\n    lbp = local_binary_pattern(img, n_points, radius, METHOD)\n    n_bins = int(lbp.max() + 1)\n    hist, _ = np.histogram(lbp, density=True, bins=n_bins, range=(0, n_bins))\n    for name, ref in refs.items():\n        ref_hist, _ = np.histogram(ref, density=True, bins=n_bins, range=(0, n_bins))\n        score = kullback_leibler_divergence(hist, ref_hist)\n        if score < best_score:\n            best_score = score\n            best_name = name\n    return best_name\n\n\nbrick = data.brick()\ngrass = data.grass()\ngravel = data.gravel()\n\nrefs = {\n    'brick': local_binary_pattern(brick, n_points, radius, METHOD),\n    'grass': local_binary_pattern(grass, n_points, radius, METHOD),\n    'gravel': local_binary_pattern(gravel, n_points, radius, METHOD),\n}\n\n# classify rotated textures\nprint('Rotated images matched against references using LBP:')\nprint(\n    'original: brick, rotated: 30deg, match result: ',\n    match(refs, rotate(brick, angle=30, resize=False)),\n)\nprint(\n    'original: brick, rotated: 70deg, match result: ',\n    match(refs, rotate(brick, angle=70, resize=False)),\n)\nprint(\n    'original: grass, rotated: 145deg, match result: ',\n    match(refs, rotate(grass, angle=145, resize=False)),\n)\n\n# plot histograms of LBP of textures\nfig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=(9, 6))\nplt.gray()\n\nax1.imshow(brick)\nax1.axis('off')\nhist(ax4, refs['brick'])\nax4.set_ylabel('Percentage')\n\nax2.imshow(grass)\nax2.axis('off')\nhist(ax5, refs['grass'])\nax5.set_xlabel('Uniform LBP values')\n\nax3.imshow(gravel)\nax3.axis('off')\nhist(ax6, refs['gravel'])\n\nplt.show()"
      ]
    }
  ],
  "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.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}