skimage.morphology.label

label

skimage.morphology.label(inputneighbors=Nonebackground=Nonereturn_num=Falseconnectivity=None)[source]

Label connected regions of an integer array.

Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:

1-connectivity      2-connectivity     diagonal connection close-up

     [ ]           [ ]  [ ]  [ ]         [ ]
      |               \  |  /             |  <- hop 2
[ ]--[x]--[ ]      [ ]--[x]--[ ]    [x]--[ ]
      |               /  |  \         hop 1
     [ ]           [ ]  [ ]  [ ]
Parameters:

input : ndarray of dtype int

Image to label.

neighbors : {4, 8}, int, optional

Whether to use 4- or 8-“connectivity”. In 3D, 4-“connectivity” means connected pixels have to share face, whereas with 8-“connectivity”, they have to share only edge or vertex. Deprecated, use ``connectivity`` instead.

background : int, optional

Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels.

return_num : bool, optional

Whether to return the number of assigned labels.

connectivity : int, optional

Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used.

Returns:

labels : ndarray of dtype int

Labeled array, where all connected regions are assigned the same integer value.

num : int, optional

Number of labels, which equals the maximum label index and is only returned if return_num is True.

    labels = label(img)
    if img.ndim > 2:
        return [rle_encode(np.sum(labels == k, axis=2), **kwargs) for k in np.unique(labels[labels > 0])]
    else:
        return [rle_encode(labels == k, **kwargs) for k in np.unique(labels[labels > 0])]


# ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode
def rle_encode(img, min_max_threshold=1e-3, max_mean_threshold=None):
    '''
    img: numpy array, 1 - mask, 0 - background
    Returns run length as string formated
    '''
    if np.max(img) < min_max_threshold:
        return ''  # no need to encode if it's all zeros
    if max_mean_threshold and np.mean(img) > max_mean_threshold:
        return ''  # ignore overfilled mask
    pixels = img.T.flatten()
    pixels = np.concatenate([[0], pixels, [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)

猜你喜欢

转载自blog.csdn.net/grllery/article/details/83662069