captainst
captainst

Reputation: 657

line detection using HoughLines in opencv

I want to detect lines in a picture like this: enter image description here

And my code is like this:

import numpy as np
import cv2
import math

# prepare the image
image = cv2.imread("image")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
ret3,thesh = cv2.threshold(blurred,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# line detection
rho=1
theta=math.pi/180
thresh = 10
minLength= 30
maxGap= 5
lines = cv2.HoughLinesP(th3.copy(), 1, rho, thresh, minLength, maxGap)
img = image.copy()
for line in lines:
  for x1,y1,x2,y2 in line:
    cv2.line(image,(x1,y1),(x2,y2),(255,0,0),1)

And the result is like this: enter image description here

It seems that HoughLinesP is not able to detect the horizontal lines, no matter what value of the parameters above I twisted. Is there a way to detect both the horizontal and vertical lines ?

Many thanks !

Upvotes: 1

Views: 995

Answers (2)

Aliaksei Sanko
Aliaksei Sanko

Reputation: 11

There are wrong HoughLinesP paramerers here. The correct ones would be:

lines = cv2.HoughLinesP(th3, rho, theta, thresh, None, minLength, maxGap)

Upvotes: 1

Deep
Deep

Reputation: 646

If finding lines is only objective, then I would suggest you to use a Sobel operator, as it will detect the gradient in x and y direction.

Steps:
- Convert image to grayscale
- Get sobel operator implemented image in both x and y direction cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5) inx direction
cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5) in y direction This will give you vertical and horizontal lines respectively
- Create a scaled image using np.uint8 which can be used to perform binary masking. - Create a binary mask like this sbin[(scax >= 90) & (scax <= 150) | (scay >= 90) & (scay <= 150)] = 1, where scax = scaled sobel image in x and scay is scaled sobel image in y.

You can play around with the minimum and maximum threshold values to get line gradients.

You will see output like this, with the edges of the lines detected: enter image description here

Upvotes: 0

Related Questions