# Detect Straight Lines in Opencv Python using Hough Line Transform

Straight lines are everywhere in the world and detecting them using Computer Vision is an important skill to learn. Straight lines are found throughout the world ranging from roads to the tiny bacteria under the microscope. As a Computer Vision developer, you may be required to detect the straight lines.

Its important to learn how to perform Canny Edge Detection and perform Hough Transform to detect straight lines in OpenCV.

This post teaches you how to detect horizontal lines in a given image. Lets quickly set the imports and get the image in OpenCV

``````import os
import math
import cv2
from matplotlib import pyplot as plt # To show on the screen

# Read the image

# Make it Black & White
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)``````

Now that we have the image, lets find the edges in the image and create a mask using these edges. We will be using Canny to detect those edges. The parameters of Canny function are:

``cv2.canny(Image, Threshold lower, Threshold Uppper)``

The thresholds are called Hysteresis counters. The value of point on a line is accepted, rejected on the basis of the following information:

But which of those lines is actually Horizontal? Time to introduce Hough Line Transform

## Hough Line Transform

Hough Line Transform is a transform algorithm which is used to detect straight lines. both horizontal as well as vertical. It is desirable for this algorithm that edges are detected prior to using this algorithm to make our lives easier. Example:

``cv.HoughLinesP(	image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])``

The Hough Algorithm here requires these parameters:

We use this algorithm as

``lines = cv2.HoughLinesP(edges, 1, math.pi/2, 2, None, 30, 1);``

Now in the lines variable, we have got a multidimensional array containing every found straight horizontal line. Parse these lines

``````for line in lines:
pt1 = (line,line)
pt2 = (line,line)
cv2.line(img, pt1, pt2, (0,0,255), 3)``````

Finally, display on Matplotlib

``````plt.imshow(img,  cmap='Greys_r') # cmap prevents yellow image
plt.title('my picture')
plt.show()``````