How to extract vertical and horizontal lines from the image

為{幸葍}努か 提交于 2021-02-11 12:44:55

问题


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:

import cv2


image = cv2.imread('img.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

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

Here's the result:

Problem:

It's clear that the current kernel is too narrow to bypass this thick vertical line on the left. This line is 41-pixel thick, so the kernel (42, 1) works fine, but I lose true horizontal lines that a shorter than 41 pixel:

Are there any flawless techniques for solving this problem?


回答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 :

NOTE : Skeletonization code from skeletonize.py




回答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):

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

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

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.



来源:https://stackoverflow.com/questions/63395167/how-to-extract-vertical-and-horizontal-lines-from-the-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!