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

  • 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. – parthagar Dec 01 '18 at 14:34
  • @parthagar thx, do you have any suggestions? – James Gilbert Dec 01 '18 at 14:53
  • This seems like homework to me so try doing this on your own, but a hint would be https://stackoverflow.com/questions/16665742/a-good-approach-for-detecting-lines-in-an-image. – parthagar Dec 01 '18 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? – James Gilbert Dec 02 '18 at 06:41
  • Try these (https://stackoverflow.com/questions/1372047/how-to-test-proximity-of-lines-hough-transform-in-opencv), (https://stackoverflow.com/questions/48677185/parallel-line-detection-using-hough-transform-opencv-and-python). – parthagar Dec 02 '18 at 08:52

0 Answers0