0

This is the image in which I want to count the lines I've tried this code already: this is the image Horizontal Line detection with OpenCV but it returns the output as an image too, as well as this code: Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV? I just want to return it as a number

pmdj
  • 22,018
  • 3
  • 52
  • 103
Aya Hany
  • 3
  • 3

2 Answers2

1

If you used lines = cv2.HoughLinesP(...), you can just take len(lines) to get the number of lines. If not, what did you use? You refer to some other stackoverflow posts, but can you post what code you used to calculate the lines?

Frederik Bode
  • 2,632
  • 1
  • 10
  • 17
0

Hope the below code helps you.

import cv2
img = cv2.imread("lines.png")
h,w = img.shape[0:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(img, 50, 200, None, 3)


def dist(x, y, x1, y1):
    return ((x-x1)**2+(y-y1)**2)**(0.5)


def slope(x, y, x1, y1):
    if y1 != y:
        return ((x1-x)/(y1-y))
    else:
        return 0


fld = cv2.ximgproc.createFastLineDetector()
lines = fld.detect(edges)
no_of_hlines = 0
#result_img = fld.drawSegments(img, lines)
for line in lines:
    x0 = int(round(line[0][0]))
    y0 = int(round(line[0][1]))
    x1 = int(round(line[0][2]))
    y1 = int(round(line[0][3]))
    d = dist(x0, y0, x1, y1)
    if d>150: #You can adjust the distance for precision
        m = (slope(x0, y0, x1, y1))
        if m ==0: #slope for horizontal lines and adjust slope for vertical lines
            no_of_hlines+=1
            cv2.line(img, (x0, y0), (x1, y1), (255, 0, 255), 1, cv2.LINE_AA)
print(no_of_hlines)
cv2.imshow("lines",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Hariprasad
  • 396
  • 1
  • 4
  • 14