如何从图像中提取垂直线和水平线 [英] How to extract vertical and horizontal lines from the image

查看:66
本文介绍了如何从图像中提取垂直线和水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务:

我有一组图像,其中每个图像都是这样的:

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.

预期结果:

目前的方法:

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)

结果如下:

问题:

很明显,当前内核太窄,无法绕过左侧的这条粗垂直线.这条线有 41 像素厚,所以内核 (42, 1) 工作正常,但我丢失了比 41 像素短的真正水平线:

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?

推荐答案

我会考虑用一个又高又细的结构元素(即一条 15 像素的垂直线)来做一个Morphological Opening"高和 1 像素宽)以找到垂直条,并使用 15 像素长和 1 像素高的水平线找到水平条.

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.

您可以使用 OpenCV 做到这一点.但我只是在终端中使用 ImageMagick 来做这件事,因为我在这方面更快!这是垂直工作的命令 - 尝试改变 15 以获得不同的结果:

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

这是一个动画,显示了当您改变 15(线的长度)时结果如何变化:

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

如果您不熟悉形态学,Anthony Thyssen 提供了出色的描述此处.请注意,它可能会根据 ImageMagick 进行解释,但这些原则同样适用于 Python OpenCV - 请参阅 这里.

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.

这篇关于如何从图像中提取垂直线和水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆