【问题标题】:How to remove small connected objects using OpenCV如何使用 OpenCV 删除小的连接对象
【发布时间】:2017-03-14 23:50:07
【问题描述】:

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

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

图片是这段代码的结果:

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

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

如何使用 OpenCV 实现这一点?

【问题讨论】:

  • 您使用什么标准来确定要突出显示的对象?为什么是那些特定的 7 和任何其他类似大小或更小的物体?
  • nn 我想移除所有小物件,这 7 个只是我想要移除它的对象示例
  • @DanMašek 我想使用对象的表面作为标准
  • @DanMašek 我知道这种方法,但我需要使用没有轮廓的方法:(
  • @Zahra 那你为什么不在你的问题中提到这个事实(并指定那个要求)?

标签: python opencv image-processing


【解决方案1】:

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

输出:

【讨论】:

  • @sotius 谢谢...我尝试了您的解决方案,但它给了我一个错误:Build\OpenCV\opencv-3.2.0\modules\imgproc\src\connectedcomponents.cpp:1664: error: ( -215) iDepth == CV_8U ||函数 cv::connectedComponents_sub1 中的 iDepth == CV_8S
  • @Zahra ,函数的输入图像需要是8bit。使用 img=img.astype(numpy.uint8) 进行转换
  • @DanMašek,也许是这样,我从 3.x 开始。这可能是我最喜欢的功能;)
【解决方案2】:

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

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

关闭操作对我来说也没有多大意义。

【讨论】:

    【解决方案3】:

    #对于孤立或未连接的 blob:试试这个(您可以将 noise_removal_threshold 设置为您喜欢的任何值,并使其相对于最大轮廓,例如 100 或 25 等标称值)。

        mask = np.zeros_like(img)
        for contour in contours:
          area = cv2.contourArea(contour)
          if area > noise_removal_threshold:
            cv2.fillPoly(mask, [contour], 255)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多