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

2024-05-15 06:06:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Input binary image

图像是此代码的结果:

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

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

enter image description here

如何使用OpenCV实现这一点?


Tags: 对象代码图像二进制cv2kernelopencvdst
2条回答

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

输出:enter image description here

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

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

另外,关闭操作对我来说也没什么意义。

相关问题 更多 >

    热门问题