【问题标题】:separate connected components to multiple images将连接的组件分离到多个图像
【发布时间】:2019-04-18 00:28:50
【问题描述】:

我有this 类型的白色和黑色图像,我想将每个白色形状保存到适合形状大小的图像。

我使用connectedComponentsWithStats() 来标记连接区域,然后我使用一个包围该区域的矩形来提取它并将其分开保存。

img = imread('shapes.png', IMREAD_GRAYSCALE)
_ , img = threshold(img,120,255,THRESH_BINARY)
n_labals, labels, stats, centroids = connectedComponentsWithStats(img)
for label in range(1,n_labals):
    width = stats[label, CC_STAT_WIDTH]
    height = stats[label, CC_STAT_HEIGHT]
    x = stats[label, CC_STAT_LEFT]
    y = stats[label, CC_STAT_TOP]
    roi = img[y-5:y + height+5, x-5:x + width+5]
    pyplot.imshow(roi,cmap='gray')
    pyplot.show()

但是,这样我在形状之间有一些交叉点,如图所示 here

我希望将每个连接区域保存到一个单独的图像中,没有任何交叉,如图所示here


更新

我拿了一个长方形来嵌入兴趣区域,然后我删除了其他标签

img = imread('shapes.png', IMREAD_GRAYSCALE)
_ , img = threshold(img,120,255,THRESH_BINARY)
n_labals, labels, stats, centroids = connectedComponentsWithStats(img)
for label in range(1,n_labals):
    width = stats[label, CC_STAT_WIDTH]
    height = stats[label, CC_STAT_HEIGHT]
    x = stats[label, CC_STAT_LEFT]
    y = stats[label, CC_STAT_TOP]
    roi = labels[y-1:y + height+1, x-1:x + width+1].copy() # create a copy of the interest region from the labeled image
    roi[ roi != label] = 0  # set the other labels to 0 to eliminate untersections with other labels
    roi[ roi == label] = 255 # set the interest region to white
    pyplot.imshow(roi,cmap='gray')
    pyplot.show()

【问题讨论】:

    标签: python opencv connected-components


    【解决方案1】:

    来自this post 的已接受答案,详细说明了函数 connectedComponentsWithStats:

    Labels 是一个矩阵,其大小为输入图像的大小,其中每个元素都有 一个等于其标签的值。

    因此,这意味着对象 1 的所有像素都具有值 1,对象 2 的所有像素都具有值 2,依此类推。

    解决您的问题我的建议是regionprops 这是在skimage 中实现的(非常适合在 python 中进行图像处理)

    可以使用 pip 或 conda 安装,详情here

    因此,在整数数组上调用 regionprops 将返回一个生成器列表,这些生成器几乎可以计算所有您想要的基本对象属性。具体来说,您要创建的图像可以通过 'filled_image' 访问:

    import numpy as np
    from skimage.measure import regionprops
    
    # generate dummy image:
    labels = np.zeros((100,100), dtype=np.int) # this does not work on floats
    # adding two rectangles, similar to output of your label function
    labels[10:20, 10:20] = 1
    labels[40:50, 40:60] = 2
    
    props = regionprops(labels)
    print(type(props))
    

    现在,我们可以遍历列表中的每一项:

    for prop in props:
       print(prop['label']) # individual properties can be accessed via square brackets
       cropped_shape = prop['filled_image'] # this gives you the content of the bounding box as an array of bool.
       cropped_shape = 1 * cropped_shape # convert to integer
       # save image with your favourite imsave. Data conversion might be neccessary if you use cv2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2020-02-08
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2018-05-09
      • 2021-09-08
      相关资源
      最近更新 更多