Skip to content Skip to sidebar Skip to footer

How To Extract Vertical And Horizontal Lines From The Image

Task: I have a set of images where every image looks like this: I'd like to extract all horizontal and all vertical lines from this image. Desired results: Current approach: imp

Solution 1:

The idea is to bring all those lines to the same "Size" by Skeletonization before applying a morphological filter & use a smaller filter Size

image = cv2.imread('Your_ImagePath' , cv2.IMREAD_COLOR)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

thresh = skeletonize(thresh)
cv2.imshow("Skelton",thresh)
cv2.waitKey()

horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 1))
horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, 
iterations=1)

cv2.imshow("Horizontal Lines" , horizontal)
v2.waitKey()

OUTPUT IMAGE :

enter image description here

NOTE : Skeletonization code from skeletonize.py

Solution 2:

I would be thinking about doing a "Morphological Opening" with a tall, thin structuring element (i.e. a vertical line 15 pixels tall and 1 pixel wide) to find the vertical bars and with a horizontal line 15 pixels long and 1 pixel high to find the horizontal bars.

You can do it just the same with OpenCV. but I am just doing it here with ImageMagick in the Terminal because I am quicker at that! Here's a command for the vertical work - try varying the 15 to get different results:

magick shapes.png -morphology open rectangle:1x15 result.png

Here's an animation of how the result changes as you vary the 15 (the length of the line):

enter image description here

And here is how it looks when you make the structuring element a horizontal line:

magick shapes.png -morphology open rectangle:15x1 result.png

enter image description here

If you are new to morphology, there is an excellent description by Anthony Thyssen here. Note that it may be explained in terms of ImageMagick but the principles are equally applicable in Python OpenCV - see here.

Post a Comment for "How To Extract Vertical And Horizontal Lines From The Image"