{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Straight line Hough transform\n\nThe Hough transform in its simplest form is a method to detect straight lines\n[1]_.\n\nIn the following example, we construct an image with a line intersection. We\nthen use the [Hough transform](https://en.wikipedia.org/wiki/Hough_transform)_.\nto explore a parameter space for straight lines that may run through the image.\n\n## Algorithm overview\n\nUsually, lines are parameterised as $y = mx + c$, with a gradient\n$m$ and y-intercept `c`. However, this would mean that $m$ goes to\ninfinity for vertical lines. Instead, we therefore construct a segment\nperpendicular to the line, leading to the origin. The line is represented by\nthe length of that segment, $r$, and the angle it makes with the x-axis,\n$\\theta$.\n\nThe Hough transform constructs a histogram array representing the parameter\nspace (i.e., an $M \\times N$ matrix, for $M$ different values of\nthe radius and $N$ different values of $\\theta$).  For each\nparameter combination, $r$ and $\\theta$, we then find the number\nof non-zero pixels in the input image that would fall close to the\ncorresponding line, and increment the array at position $(r, \\theta)$\nappropriately.\n\nWe can think of each non-zero pixel \"voting\" for potential line candidates. The\nlocal maxima in the resulting histogram indicates the parameters of the most\nprobable lines. In our example, the maxima occur at 45 and 135 degrees,\ncorresponding to the normal vector angles of each line.\n\nAnother approach is the Progressive Probabilistic Hough Transform [2]_. It is\nbased on the assumption that using a random subset of voting points give a good\napproximation to the actual result, and that lines can be extracted during the\nvoting process by walking along connected components. This returns the\nbeginning and end of each line segment, which is useful.\n\nThe function `probabilistic_hough` has three parameters: a general threshold\nthat is applied to the Hough accumulator, a minimum line length and the line\ngap that influences line merging. In the example below, we find lines longer\nthan 10 with a gap less than 3 pixels.\n\n## References\n\n.. [1] Duda, R. O. and P. E. Hart, \"Use of the Hough Transformation to\n       Detect Lines and Curves in Pictures,\" Comm. ACM, Vol. 15,\n       pp. 11-15 (January, 1972)\n\n.. [2] C. Galamhos, J. Matas and J. Kittler,\"Progressive probabilistic\n       Hough transform for line detection\", in IEEE Computer Society\n       Conference on Computer Vision and Pattern Recognition, 1999.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Line Hough Transform\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nfrom skimage.transform import hough_line, hough_line_peaks\nfrom skimage.feature import canny\nfrom skimage.draw import line as draw_line\nfrom skimage import data\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\n# Constructing test image\nimage = np.zeros((200, 200))\nidx = np.arange(25, 175)\nimage[idx, idx] = 255\nimage[draw_line(45, 25, 25, 175)] = 255\nimage[draw_line(25, 135, 175, 155)] = 255\n\n# Classic straight-line Hough transform\n# Set a precision of 0.5 degree.\ntested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360, endpoint=False)\nh, theta, d = hough_line(image, theta=tested_angles)\n\n# Generating figure 1\nfig, axes = plt.subplots(1, 3, figsize=(15, 6))\nax = axes.ravel()\n\nax[0].imshow(image, cmap=cm.gray)\nax[0].set_title('Input image')\nax[0].set_axis_off()\n\nangle_step = 0.5 * np.diff(theta).mean()\nd_step = 0.5 * np.diff(d).mean()\nbounds = [\n    np.rad2deg(theta[0] - angle_step),\n    np.rad2deg(theta[-1] + angle_step),\n    d[-1] + d_step,\n    d[0] - d_step,\n]\nax[1].imshow(np.log(1 + h), extent=bounds, cmap=cm.gray, aspect=1 / 1.5)\nax[1].set_title('Hough transform')\nax[1].set_xlabel('Angles (degrees)')\nax[1].set_ylabel('Distance (pixels)')\nax[1].axis('image')\n\nax[2].imshow(image, cmap=cm.gray)\nax[2].set_ylim((image.shape[0], 0))\nax[2].set_axis_off()\nax[2].set_title('Detected lines')\n\nfor _, angle, dist in zip(*hough_line_peaks(h, theta, d)):\n    (x0, y0) = dist * np.array([np.cos(angle), np.sin(angle)])\n    ax[2].axline((x0, y0), slope=np.tan(angle + np.pi / 2))\n\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Probabilistic Hough Transform\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage.transform import probabilistic_hough_line\n\n# Line finding using the Probabilistic Hough Transform\nimage = data.camera()\nedges = canny(image, 2, 1, 25)\nlines = probabilistic_hough_line(edges, threshold=10, line_length=5, line_gap=3)\n\n# Generating figure 2\nfig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(image, cmap=cm.gray)\nax[0].set_title('Input image')\n\nax[1].imshow(edges, cmap=cm.gray)\nax[1].set_title('Canny edges')\n\nax[2].imshow(edges * 0)\nfor line in lines:\n    p0, p1 = line\n    ax[2].plot((p0[0], p1[0]), (p0[1], p1[1]))\nax[2].set_xlim((0, image.shape[1]))\nax[2].set_ylim((image.shape[0], 0))\nax[2].set_title('Probabilistic Hough')\n\nfor a in ax:\n    a.set_axis_off()\n\nplt.tight_layout()\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
}