假设在第二步中,您想使用这些轮廓进行轮廓检测,我有一个更直接的解决方案。使用 Dilation,将扩大白色区域,从而缩小差距:
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()