1

I am given a task to detect all rectangular objects in the image. It's very simple if I use cv2.findContours function in OpenCV. However, I am not allowed to use it. I am told to detect all parallel lines and then highlight them. I am using Hough Transform to find all lines and then find parallel lines according to their slope. But somehow the number of lines is very large and the result is not accurate at all.

Below is my code, anyone knows how to fix it?

import cv2
import numpy as np


def getSlopeOfLine(line):
    xDis = line[0][2] - line[0][0]
    if (xDis == 0):
        return None
    return (line[0][3] - line[0][1]) / xDis


if __name__ == '__main__':
    inputFileName = '/Users/James/Desktop/img.jpg'
    img = cv2.imread(inputFileName)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    lines = cv2.HoughLinesP(gray, 1, np.pi / 180, 100, 30, 2)

    parallelLines = []
    for a in lines:
        for b in lines:
            if a is not b:
                slopeA = getSlopeOfLine(b)
                slopeB = getSlopeOfLine(b)
                if slopeA is not None and slopeB is not None:
                    if 0 <= abs(slopeA - slopeB) <= 0.6:
                        parallelLines.append({'lineA': a, 'lineB': b})

    for pairs in parallelLines:
        lineA = pairs['lineA']
        lineB = pairs['lineB']

        leftx, boty, rightx, topy = lineA[0]
        cv2.line(img, (leftx, boty), (rightx, topy), (0, 0, 255), 2)

    cv2.imshow('linesImg', img)
    cv2.waitKey(0)

source image

5
  • Welcome to StackOverflow! I see that in the image you are getting a large number of lines, that is because a single line is broken into many as you can see in the image that the lines are not continuous and rather broken, find a way to fix that. Commented Dec 1, 2018 at 14:34
  • @parthagar thx, do you have any suggestions? Commented Dec 1, 2018 at 14:53
  • This seems like homework to me so try doing this on your own, but a hint would be stackoverflow.com/questions/16665742/…. Commented Dec 1, 2018 at 15:02
  • @parthagar thanks for your hint. I tried to blur and threshold it before using canny edge detection. Now the number of lines is reduced. But there are sill some non-continuous lines. Do you know how to fix it? Commented Dec 2, 2018 at 6:41
  • Try these (stackoverflow.com/questions/1372047/…), (stackoverflow.com/questions/48677185/…). Commented Dec 2, 2018 at 8:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.