Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to find all connected pixels if I know an origin pixel's position?

Tags:

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?

like image 770
Felix Avatar asked Feb 10 '17 14:02

Felix


1 Answers

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
like image 138
Logan Byers Avatar answered Sep 21 '22 10:09

Logan Byers