如何使用 OpenCV 删除小的连接对象

新手上路,请多包涵

我使用 OpenCV 和 Python,我想从我的图像中删除连接的小对象。

我有以下二进制图像作为输入:

输入二值图像

该图像是这段代码的结果:

 dilation = cv2.dilate(dst,kernel,iterations = 2)
erosion = cv2.erode(dilation,kernel,iterations = 3)

我想删除以红色突出显示的对象:

在此处输入图像描述

我如何使用 OpenCV 实现这一目标?

原文由 Zahra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 794
2 个回答

connectedComponentsWithStats (文档) 怎么样:

 # find all of the connected components (white blobs in your image).
# im_with_separated_blobs is an image where each detected blob has a different pixel value ranging from 1 to nb_blobs - 1.
nb_blobs, im_with_separated_blobs, stats, _ = cv2.connectedComponentsWithStats(im)
# stats (and the silenced output centroids) gives some information about the blobs. See the docs for more information.
# here, we're interested only in the size of the blobs, contained in the last column of stats.
sizes = stats[:, -1]
# the following lines result in taking out the background which is also considered a component, which I find for most applications to not be the expected output.
# you may also keep the results as they are by commenting out the following lines. You'll have to update the ranges in the for loop below.
sizes = sizes[1:]
nb_blobs -= 1

# minimum size of particles we want to keep (number of pixels).
# here, it's a fixed value, but you can set it as you want, eg the mean of the sizes or whatever.
min_size = 150

# output image with only the kept components
im_result = np.zeros((output.shape))
# for every component in the image, keep it only if it's above min_size
for blob in range(nb_blobs):
    if sizes[blob] >= min_size:
        # see description of im_with_separated_blobs above
        im_result[im_with_separated_blobs == blob + 1] = 255

输出 : 在此处输入图像描述

原文由 Soltius 发布,翻译遵循 CC BY-SA 4.0 许可协议

为了自动删除对象,您需要在图像中找到它们。从您提供的图片中,我看不出这 7 个突出显示的项目与其他项目有什么区别。你必须告诉你的计算机如何识别你不想要的对象。如果它们看起来一样,这是不可能的。

如果您有多个图像,其中对象总是看起来像您可以使用模板匹配技术。

此外,关闭操作对我来说没有多大意义。

原文由 Piglet 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题