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

Za*_*hra 6 python opencv image-processing

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

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

输入二进制图像

图像是此代码的结果:

dilation = cv2.dilate(dst,kernel,iterations = 2)
erosion = cv2.erode(dilation,kernel,iterations = 3)
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

Sol*_*ius 27

怎么样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
Run Code Online (Sandbox Code Playgroud)

输出:在此输入图像描述

  • @Zahra ,该函数的输入图像需要为 8 位。使用 img=img.astype(numpy.uint8) 进行转换 (3认同)
  • @sotius谢谢...我尝试你的解决方案,但它给了我一个错误:Build\OpenCV\opencv-3.2.0\modules\imgproc\src\connectedcomponents.cpp:1664: error: (-215) iDepth == CV_8U | | 函数 cv::connectedComponents_sub1 中的 iDepth == CV_8S (2认同)
  • 请注意,行“im_result = np.zeros(im.shape)”始终创建一个 dtype float64 的数组,而不是调整输入图像的 dtype。在更复杂的图像处理链中更改图像数组的 dtype 可能会导致意外错误,这就是为什么我建议将该行更改为“im_result = np.zeros_like(im)”。 (2认同)