Reputation: 648
I have a binary 2D Numpy array with potentially overlapping bounding boxes that I'd like to fill in. I've attached a figure to illustrate my problem. The input is on the left, and the ideal output is on the right. I've tried the solution mentioned here, which outputs the subfigure in the center, which does not suit my purposes.
Upvotes: 1
Views: 217
Reputation: 221514
Approach #1 : Direct fill-hole tool with SciPy : scipy.ndimage.morphology.binary_fill_holes
-
import numpy as np
import cv2
from scipy.ndimage.morphology import binary_fill_holes
# Read in image as grayscale and assuming blobs are at 255 and background at 0
im = cv2.imread('boxes.png',0)
cv2.imwrite('out.png', (binary_fill_holes(im)*255).astype(np.uint8))
Approach #2 : Floodfill at one corner (that is background with 0
) with 255
. So, all of background is now 255
. Invert it to get inner regions at 255, but this will set the inner box intersection lines at 0. So, OR
it with the original image to get our desired output. Hence, implementation would look something along these lines -
from skimage.segmentation import flood_fill
filled = flood_fill(im.copy(), (0, 0), 255)
mask = (filled==0) | (im==255)
cv2.imwrite('out.png', (255*mask).astype(np.uint8))
Or use im
data :
im[mask] = 255
cv2.imwrite('out.png', im)
Input ('boxes.png') :
Output ('out.png') :
Upvotes: 1