I have this kind of white and black images and i would like to save each white shape to an image that fits the shape's size.
I'm using connectedComponentsWithStats()
in order to label connected regions, and then I use a rectangle englobing the region to extract it and saving it apart.
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()
However, this way I'm having some intersections between shapes as shown here
I would like to have each connected region saved into a separated image without any intersection as shown here
UPDATE
I took a rectangle engobing the interest region and then I ommoted the other labels
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()