如何使用OpenCV删除小的连接对象 [英] How to remove small connected objects using OpenCV

查看:691
本文介绍了如何使用OpenCV删除小的连接对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use OpenCV and Python and I want to remove the small connected object from my image.

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

I have the following binary image as input:

图像是此代码的结果:

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

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

I want to remove the objects highlighted in red:

如何使用OpenCV实现此目的?

How can I achieve this using OpenCV?

推荐答案

如何使用 connectedComponentsWithStats

#find all your connected components (white blobs in your image)
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
#connectedComponentswithStats yields every seperated component with information on each of them, such as size
#the following part is just taking out the background which is also considered a component, but most of the time we don't want that.
sizes = stats[1:, -1]; nb_components = nb_components - 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  

#your answer image
img2 = np.zeros((output.shape))
#for every component in the image, you keep it only if it's above min_size
for i in range(0, nb_components):
    if sizes[i] >= min_size:
        img2[output == i + 1] = 255

输出:

这篇关于如何使用OpenCV删除小的连接对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆