# Python: Line Detection using hough transform

In this tutorial, we will learn how to detect line using Hough Transform in Python. But let’s first try to understand what is Hough Transform.  Hough Transform is a method which  can easily detect mathematically representable simple shapes. Hough Transform is a feature extraction method, which can successfully detect shapes even if the image is broken/distorted. A circle represented using center and radius is a simple shape. The idea is quite clear.

## Line detection using Hough Transform in Python

A line can be represented in polar form, using the perpendicular distance from origin and the angle it makes with positive x-axis. In that case, equation of the line is r = xcosθ+ysinθ. Here ‘r’ is the perpendicular distance from the origin to the line and θ is the angle formed by this perpendicular line with x-axis. Thus the line is of form (r,θ).
Working of Hough Transform:

• Create a 2-d array to store the values of 2 parameters
• Let rows denote the r-values and columns denote the θ-values.
• If you want the accuracy to be 1 degree, then there must be 180 columns
• (no. of rows)*(per unit length) = perpendicular distance from origin.

Now let’s jump into the code.

```import cv2
import numpy as np
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180, 200)

for r,theta in lines:
a, b = np.cos(theta), np.sin(theta)
x0, y0 = a*r, b*r
x1, y1 = int(x0 + 1000*(-b)), int(y0 + 1000*(a))
x2, y2 = int(x0 - 1000*(-b)), int(y0 - 1000*(a))
cv2.line(img,(x1,y1), (x2,y2), (0,0,255),2)

cv2.imwrite('linesDetected.jpg', img)```

Now let’s understand the code. Firstly we import OpenCV  and numpy.  Then we read the image ‘image.jpg’ in same directory. Then we convert the image to greyscale and then apply edge detection method to the image as below.

`edges = cv2.Canny(gray,50,150,apertureSize = 3)`

Then we take the edges to yield r and θ values in form of array as shown.

`lines = cv2.HoughLines(edges,1,np.pi/180, 200)`

Below this line in the code, we have a for loop that runs for all values of r and θ in the array. We store cosθ and sinθ values in 2 parameters i.e a and b respectively. ‘x0’ and ‘y0’ stores values of ‘rcosθ’ and ‘rsinθ’ respectively. cv2.line in the code draws the line from (x1,y1) to (x2,y2).  Lastly, all changes are written on new image i.e linesDetected.jpg . It will look something like shown below. 