将连接的组件分离到多个图像

时间:2019-04-17 14:34:20

标签: python opencv connected-components

我有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()

1 个答案:

答案 0 :(得分:1)

this post的详细答案中可以看出,该函数详细说明了connectedComponentsWithStats函数:

  

标签是每个元素具有的输入图像大小的矩阵   等于其标签的值。

因此,这意味着对象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