I have a binary image: numpy.ndarray(dtype=bool)
. It has a few hundreds of connected regions filled with True
value.
But I'm interested only in one region. I know the posision of one of its elements and want to find out the bounding box of this region-of-interest (and maybe the positions of other points of this region too).
What is the best way to do it?
Depending on the size of your image it might be simplest to label the image to get all the connected components. Use the label of the known pixel to get the connected pixels as well. skimage
makes this really simple using skimage.measure.label
and skimage.measure.regionprops
. Be sure to understand the connectivity
or neighbors
parameter to label
, as it affects whether diagonal neighbors touch or not.
from skimage import measure
import numpy as np
# load array; arr = np.ndarray(...)
# arr = np.zeros((10,10), dtype=bool)
# arr[:2,:2] = True
# arr[-4:,-4:] = True
labeled = measure.label(arr, background=False, connectivity=2)
label = labeled[8,8] # known pixel location
rp = measure.regionprops(labeled)
props = rp[label - 1] # background is labeled 0, not in rp
props.bbox # (min_row, min_col, max_row, max_col)
props.image # array matching the bbox sub-image
props.coordinates # list of (row,col) pixel indices
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With