【发布时间】: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