使用 OpenCV 找到没有狭窄瓶颈的连续区域
Find continuous area without narrow bottlenecks using OpenCV
我想获得连续区域的轮廓,但输出中没有非常狭窄的地方。
输入图像可以看起来像这个图像(应用阈值后):
通过调用 OpenCVs findContours 方法,我得到以下结果:
我的问题是我不想在结果中出现窄(白)峰。只是模糊图像是行不通的,因为我不能包括黑色峰。所以想要的输出应该看起来像这条绿线:
是否可以告诉 OpenCV (findContours) 区域的最小 "thickness"?
使用侵蚀,然后在执行 findContours
之前使用小内核进行膨胀。 OpenCV 中有一种特殊的运算符可以做到这一点,称为 Opening 和 morphologyEx
像这样的东西应该可以工作:
morphologyEx(src, dst, MORPH_OPEN, Mat());
Erosion can be thought as adding the boundary pixels to the background. Thus, it gets rid of such narrow pieces in your input. However, since it distorts all the boundaries, you need to apply dilation afterwards, to undo the effect of erosion on the actual boundary. The erosion+dilation process is called opening.
下面的代码部分生成所需的输出。根据您的图像大小播放 k_size
。然后申请findContours
.
# Read and binarize the image
image = cv2.imread("test.png",cv2.IMREAD_GRAYSCALE)
ret, im_th =cv2.threshold(image,150,255,cv2.THRESH_BINARY)
# Set the kernel and perform opening
k_size = 7
kernel = np.ones((k_size,k_size),np.uint8)
opened = cv2.morphologyEx(im_th, cv2.MORPH_OPEN, kernel)
cv2.imwrite("opened.png", opened)
输出:
我想获得连续区域的轮廓,但输出中没有非常狭窄的地方。
输入图像可以看起来像这个图像(应用阈值后):
通过调用 OpenCVs findContours 方法,我得到以下结果:
我的问题是我不想在结果中出现窄(白)峰。只是模糊图像是行不通的,因为我不能包括黑色峰。所以想要的输出应该看起来像这条绿线:
是否可以告诉 OpenCV (findContours) 区域的最小 "thickness"?
使用侵蚀,然后在执行 findContours
之前使用小内核进行膨胀。 OpenCV 中有一种特殊的运算符可以做到这一点,称为 Opening 和 morphologyEx
像这样的东西应该可以工作:
morphologyEx(src, dst, MORPH_OPEN, Mat());
Erosion can be thought as adding the boundary pixels to the background. Thus, it gets rid of such narrow pieces in your input. However, since it distorts all the boundaries, you need to apply dilation afterwards, to undo the effect of erosion on the actual boundary. The erosion+dilation process is called opening.
下面的代码部分生成所需的输出。根据您的图像大小播放 k_size
。然后申请findContours
.
# Read and binarize the image
image = cv2.imread("test.png",cv2.IMREAD_GRAYSCALE)
ret, im_th =cv2.threshold(image,150,255,cv2.THRESH_BINARY)
# Set the kernel and perform opening
k_size = 7
kernel = np.ones((k_size,k_size),np.uint8)
opened = cv2.morphologyEx(im_th, cv2.MORPH_OPEN, kernel)
cv2.imwrite("opened.png", opened)
输出: