假设你想在第二步中使用这些轮廓进行轮廓检测,我有一个更直接的解决方案。使用膨胀操作会放大白色区域,从而填补空隙:
import cv2
import numpy as np
image = cv2.imread('lineswithgaps.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
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 = cv2.cvtColor(canvas, cv2.COLOR_GRAY2RGB)
contours, hierarchy = cv2.findContours(dilated_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
for i,cont in enumerate(contours):
if ( hierarchy[0][i][3] != -1 ):
cv2.fillPoly(canvas, pts =[cont], color=(0, 180, 0))
else:
cv2.drawContours(canvas, cont, -1, (255, 0, 0), 1)
cv2.imshow("Contours detected", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()