简体   繁体   English

Python OpenCV 如何删除行之间的空间

[英]Python OpenCV how to remove space between lines

I have this image:我有这张图片:

在此处输入图像描述

And my goal is to separate the L-Shape as two different rectangles (the two who together make the L-Shape).我的目标是将 L 形分隔为两个不同的矩形(两个共同构成 L 形)。 With the long rectangle there is no problem because it is being detected as a contour.对于长矩形没有问题,因为它被检测为轮廓。 But with the wider rectangle it is a problem, because there is a space between two lines.但是对于较宽的矩形,这是一个问题,因为两条线之间有一个空间。 Is there a solution for this matter?这个问题有解决方案吗?

I didn't write any code for it yet, so I cant post anything我还没有为它写任何代码,所以我不能发布任何东西

Thanks in advance提前致谢

Whenever performing image-processing with OpenCV, you want to have the desired manipulated objects in white with the background in black.每当使用 OpenCV 执行图像处理时,您都希望将所需的操作对象设为白色,背景设为黑色。 In this case, since you want to modify the lines, the image first needs to be inverted so the lines are in white and the background in black.在这种情况下,由于您要修改线条,因此首先需要反转图像,使线条为白色,背景为黑色。 From here, we can construct a horizontal kernel and perform morphological closing to connect the lines together.从这里,我们可以构造一个水平的 kernel 并执行形态闭合以将线条连接在一起。 Similarly, if you wanted to close spaces between vertical lines, you could perform the same steps with a vertical kernel.同样,如果您想关闭垂直线之间的空间,您可以使用垂直 kernel 执行相同的步骤。

Result结果

在此处输入图像描述

Code代码

import cv2

image = 255 - cv2.imread('1.png', 0)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (60,1))
result = 255 - cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel, iterations=1)

cv2.imshow('result', result)
cv2.waitKey()

If you want to use contour-based methods only, then you can try with erosion.如果您只想使用基于轮廓的方法,那么您可以尝试使用侵蚀。 Apply erosion to the image and with appropriate parameters, you can close the spacing at the cost of increasing the thickness of the lines, but I think that's ok for your case, since you are relying on contour extraction only.对图像应用腐蚀并使用适当的参数,您可以以增加线条的粗细为代价来缩小间距,但我认为这对您的情况来说是可以的,因为您只依赖于轮廓提取。 Try this:尝试这个:

kernel = np.ones((7,7), np.uint8)
eroded_im = cv2.erode(im, kernel, iterations=5 or 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM