我有以下图片:

我想要填写它的轮廓(也就是说,我想空白填充这张图片中的线条)。
我尝试过一个形态学闭包,但是使用大小为3x3的矩形内核和10迭代并不能填充整个边框。我也尝试过一个带有21x21迭代的1内核,但也没有成功。
更新:
我在OpenCV (Python)中尝试过这样的方法:
cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (21,21)))和
cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)), iterations=10)和科学图像
closing(img, square(21))我的最终目标是在不扭曲覆盖区域的情况下,有一个完整的图像填充版本。
发布于 2015-01-22 01:02:30
在下面的片段中,我计算了逆图像的距离图。我对其进行阈值化,以获得当前对象的大轮廓,然后将其骨架化以获得中心线。这可能已经足够你的目的了。但为了使其与给定的线厚度一致,我将骨架展开,并将其添加到原来的位置,从而消除任何间隙。我还移除了一个接触边界的物体。

from skimage import io, morphology, img_as_bool, segmentation
from scipy import ndimage as ndi
import matplotlib.pyplot as plt
image = img_as_bool(io.imread('/tmp/gaps.png'))
out = ndi.distance_transform_edt(~image)
out = out < 0.05 * out.max()
out = morphology.skeletonize(out)
out = morphology.binary_dilation(out, morphology.selem.disk(1))
out = segmentation.clear_border(out)
out = out | image
plt.imshow(out, cmap='gray')
plt.imsave('/tmp/gaps_filled.png', out, cmap='gray')
plt.show()发布于 2021-01-01 16:55:25
假设在第二步,您想要使用这些等高线进行轮廓检测,我有一个更直接的解决方案。使用膨胀,将扩大白色区域,从而缩小差距:

import cv2
import numpy as np
image = cv2.imread('lineswithgaps.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# apply dilation on src image
kernel = np.ones((3,3),np.uint8)
dilated_img = cv2.dilate(gray, kernel, iterations = 2)
cv2.imshow("filled gaps for contour detection", dilated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()作为一个缺点,边缘变得更厚,然而,这可能不是一个问题,如果你不需要高精度.如果现在要检测轮廓,只需将这些行添加到第一个代码片段:

canvas = dilated_img.copy() # Canvas for plotting contours on
canvas = cv2.cvtColor(canvas, cv2.COLOR_GRAY2RGB) # create 3 channel image so we can plot contours in color
contours, hierarchy = cv2.findContours(dilated_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
# loop through the contours and check through their hierarchy, if they are inner contours
# more here: https://docs.opencv.org/master/d9/d8b/tutorial_py_contours_hierarchy.html
for i,cont in enumerate(contours):
# look for hierarchy[i][3]!=-1, ie hole boundaries
if ( hierarchy[0][i][3] != -1 ):
#cv2.drawContours(canvas, cont, -1, (0, 180, 0), 1) # plot inner contours GREEN
cv2.fillPoly(canvas, pts =[cont], color=(0, 180, 0)) # fill inner contours GREEN
else:
cv2.drawContours(canvas, cont, -1, (255, 0, 0), 1) # plot all others BLUE, for completeness
cv2.imshow("Contours detected", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()https://stackoverflow.com/questions/28078530
复制相似问题