Ask Your Question

Revision history [back]

after some morphologic operations you can find contours and count horizontal and vertical lines.

see the code below ( kernels are experimental and could be improved )

image description


image description

import cv2
import math

img = cv2.imread('e:/test/lines.jpg', cv2.IMREAD_GRAYSCALE)


ret,bw = cv2.threshold(img,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow("bw", bw)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 2))
dilated_Edges = cv2.dilate(bw, kernel, iterations=3)

eroded_Edges = cv2.erode(dilated_Edges, kernel, iterations=2)

cv2.imshow("vertical lines", eroded_Edges)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (1, 5))
dilated_Edges = cv2.dilate(bw, kernel, iterations=3)


cv2.imshow("horizontal lines", dilated_Edges)

cv2.waitKey()

after some morphologic operations you can find contours and count horizontal and vertical lines.

see the code below ( kernels are experimental and could be improved )

image descriptionimage description


image descriptionimage description

import cv2
import math

img = cv2.imread('e:/test/lines.jpg', cv2.IMREAD_GRAYSCALE)


ret,bw = cv2.threshold(img,0,255,cv2.THRESH_BINARY cv2.threshold(img,0,255,cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
cv2.imshow("bw", bw)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 2))
dilated_Edges eroded_Edges = cv2.dilate(bw, cv2.erode(bw, kernel, iterations=3)

eroded_Edges dilated_Edges = cv2.erode(dilated_Edges, cv2.dilate(eroded_Edges, kernel, iterations=2)

contours, hierarchy = cv2.findContours(dilated_Edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

print (len(contours) , " vertical lines")

cv2.imshow("vertical lines", eroded_Edges)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (1, 5))
dilated_Edges eroded_Edges = cv2.dilate(bw, cv2.erode(bw, kernel, iterations=3)

contours, hierarchy = cv2.findContours(eroded_Edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

print (len(contours) , " horizontal lines")

cv2.imshow("horizontal lines", dilated_Edges)
eroded_Edges)

cv2.waitKey()