2

I am new to opencv-python. I have found the lines in image through houghtransformP. The lines drawn from hough transform are discontinued and are giving multiple lines. I need to draw only one line for the edges and find the 'distance' between lines which are found.

The output image is shown below

"""
Created on Fri Nov  8 11:41:16 2019

@author: romanth.chowan
"""

import cv2
import numpy as np
import math


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_ =r"C:\Users\romanth.chowan\Desktop\opencv\stent spec\2prox.jpeg"
    img = cv2.imread(inputFileName_)
    img1=cv2.GaussianBlur(img,(5,5),0)

    gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    edges = cv2.Laplacian(gray,cv2.CV_8UC1) # Laplacian Edge Detection
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 300, 10, 10)
    print(len(lines))
    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) <= 10:
                       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)


        left_x, bot_y, right_x, top_y = lineB[0]
        cv2.line(img, (left_x, bot_y), (right_x, top_y), (0, 0, 255), 2)

    cv2.imwrite('linesImg.jpg', img)

output image after drawing lines:

enter image description here

underscore_d
  • 6,309
  • 3
  • 38
  • 64

1 Answers1

1

It's mostly geometric task, not specific to OpenCV.

For each line you have two points (x1,y1) and (x2,y2) which are already used in your getSlopeOfLine(line) method. You can denote each line in form:

ax + by + c = 0

To do that use two known line's points:

(y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0

Note than parallel lines have same a and b while different c.

And than measure distance between any two of them (distance between non-parallel lines is equal to zero since they have a crossing point) :

d = abs(c2 - c1) / sqrt(a*a + b*b)

In Euclidean geometry line may be denoted in several ways and one may suit specific task better than another.

Currently you evaluate line's slope, from formula above we can get:

y = (-b / a)x - c / b

same to (b has another meaning now)

y = kx + b

Or using two line's points:

y = (x1 - x2) / (y1 - y2) * x + (x1y2 - x2y1)

Where k is line's slope (tan(alpha)) and b is shift. Now you just match parallel lines (one with close k). You can take in account line's shift to merge several parallel lines into one.

f4f
  • 891
  • 5
  • 13