如何在opencv中填充轮廓中的小间隙

brc7rcf0  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(169)

下面是我正在使用的二进制图像:

我正在迭代一堆轮廓并尝试为它们着色,这是我到目前为止所做的:

input_image = imread(img)
_retval, thresh = cv2.threshold(input_image, 125, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
output = np.zeros((input_image.shape[0], input_image.shape[1], 3), dtype=np.uint8)
for i, contour in enumerate(contours):
   cv2.drawContours(output, contours, i, (255,0,0), thickness=3)

上面的代码工作并给出以下输出:

我想要的是填充这些间隙,我可以通过将厚度更改为cv2.FILLED来实现这一点,但是当我这样做时,我得到以下输出:

我只是想填补线没有大斑点被填补以及,我希望保持透明或没有任何颜色,任何帮助将不胜感激,请让我知道,如果我需要澄清什么。

iih3973s

iih3973s1#

为了用红色着色遮罩,我们不必找到轮廓,我们可以简单地将thresh设置为BGR图像的红色通道(绿色和蓝色通道为零):

import cv2
import numpy as np

input_image = cv2.imread('input_image.png', cv2.IMREAD_GRAYSCALE)  # Read input image as grayscale.
_retval, thresh = cv2.threshold(input_image, 125, 255, cv2.THRESH_BINARY)
output = np.zeros((input_image.shape[0], input_image.shape[1], 3), dtype=np.uint8)

output[:, :, 2] = thresh  # Set thresh as the red color channel of the output image (blue and green channels are zeros).

cv2.imwrite('output.png', output)

输出:

如果期望的输出是较粗的线,我们可以在彩色输出上绘制轮廓:

import cv2
import numpy as np

input_image = cv2.imread('input_image.png', cv2.IMREAD_GRAYSCALE)  # Read input image as grayscale.
_retval, thresh = cv2.threshold(input_image, 125, 255, cv2.THRESH_BINARY)
output = np.zeros((input_image.shape[0], input_image.shape[1], 3), dtype=np.uint8)

output[:, :, 2] = thresh  # Set thresh as the red color channel of the output image (blue and green channels are zeros).

contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
#output = np.zeros((input_image.shape[0], input_image.shape[1], 3), dtype=np.uint8)
for i, contour in enumerate(contours):
    cv2.drawContours(output, contours, i, (0,0,255), thickness=3)

cv2.imwrite('output.png', output)

输出:

相关问题