Esempio n. 1
0
def skeleton_image(folder, image_file, threshold=50, area_thresh=50, figsize=(10, 10), show=False):
    """
    Skeletonizes the image and returns properties of each skeleton.

    Parameters
    ----------

    Returns
    -------

    Examples
    --------

    """
    # Median filtered image.
    fname = '{}/{}'.format(folder, image_file)
    image0 = sio.imread(fname)
    image0 = np.ceil(255* (image0[:, :, 1] / image0[:, :, 1].max())).astype(int)
    image0 = skimage.filters.median(image0)
    filt = 'filt_{}.png'.format(image_file.split('.')[0])
    sio.imsave(folder+'/'+filt, image0)

    #threshold the image
    binary0 = binary_image(folder, filt, threshold=threshold, close=True, show=False)
    clean = 'clean_{}'.format(filt)

    #label image
    short_image, props = label_image(folder, clean, area_thresh=area_thresh, show=False)
    short = 'short_{}'.format(clean)
    short_image = short_image > 1
    # Skeletonize
    skeleton0 = skeletonize(short_image)

    branch_data = csr.summarise(skeleton0)
    branch_data_short = branch_data

    #Remove small branches
    mglia = branch_data['skeleton-id'].max()
    nbranches = []

    ncount = 0
    for i in range(1, mglia+1):
        bcount = branch_data[branch_data['skeleton-id']==i]['skeleton-id'].count()
        if bcount > 0:
            ids = branch_data.index[branch_data['skeleton-id']==i].tolist()
            nbranches.append(bcount)
            for j in range(0, len(ids)):
                branch_data_short.drop([ids[j]])

            ncount = ncount + 1
    if show:
        fig, ax = plt.subplots(figsize=(10, 10))
        draw.overlay_euclidean_skeleton_2d(image0, branch_data_short,
                                           skeleton_color_source='branch-type', axes=ax)
        plt.savefig('{}/skel_{}'.format(folder, short))

    return skeleton0, branch_data_short, nbranches, short_image, props
Esempio n. 2
0
 def skan(self, n):
     blur = cv2.blur(self.mask, (5, 5))
     binary = blur > filters.threshold_otsu(blur)
     skeleton = morphology.skeletonize(binary)
     ax = plt.subplot(2, 2, 2 * n - 1)
     draw.overlay_skeleton_2d(blur, skeleton, dilate=1, axes=ax)
     branch_data = summarize(Skeleton(skeleton))
     ax = plt.subplot(2, 2, 2 * n)
     draw.overlay_euclidean_skeleton_2d(blur,
                                        branch_data,
                                        skeleton_color_source='branch-type',
                                        axes=ax)
     df1 = branch_data.loc[branch_data['branch-type'] == 1]
     return df1
Esempio n. 3
0
def test_overlay_euclidean_skeleton(test_image, test_stats):
    draw.overlay_euclidean_skeleton_2d(test_image, test_stats)
    draw.overlay_euclidean_skeleton_2d(test_image, test_stats,
                                       skeleton_color_source='branch-distance')
Esempio n. 4
0
shape_skeleton = skeleton_image * shape

from skan import summarise

data = summarise(shape_skeleton)
data.head()

from skan import draw
draw.overlay_skeleton_2d(im, shape_skeleton, dilate=1)

def filtered(values):
    return np.digitize(values, [0.125, 0.625])

data['filtered'] = filtered(data['mean pixel value'])
draw.overlay_euclidean_skeleton_2d(im, data,
                                   skeleton_color_source='filtered')

from skan import Skeleton
skeleton = Skeleton(shape_skeleton, source_image=im)
# second time is much faster thanks to Numba JIT
skeleton = Skeleton(shape_skeleton, source_image=im)

def filtered2(skeleton):
    values = skeleton.path_means()
    return filtered(values)

ax, cvals = draw.overlay_skeleton_2d_class(skeleton,
                                           skeleton_color_source=filtered2)

Esempio n. 5
0
#h, w = imgb.shape[:2]
#imgb = cv2.resize(imgb,(h,h), interpolation=cv2.INTER_CUBIC)
pbef = Process(imgb)
pbef.lowp = np.array([150, 60, 100])
pbef.highp = np.array([170, 255, 255])
pbef.loww = np.array([90, 15, 150])
pbef.highw = np.array([115, 255, 255])
maskb = pbef.mask(kernel)
resb = pbef.res(maskb)
maskb = cv2.blur(maskb, (5, 5))

binaryb = maskb > filters.threshold_otsu(maskb)
skeletonb = morphology.skeletonize(binaryb)
fig, ax = plt.subplots()
draw.overlay_skeleton_2d(maskb, skeletonb, dilate=1, axes=ax)

#graphb = csgraph_from_masked(binaryb)
#plt.imshow(graphb)
gb, cb, db = skeleton_to_csgraph(skeletonb)
draw.overlay_skeleton_networkx(gb, cb, image=maskb)
branch_datab = summarize(Skeleton(skeletonb))
dfb = branch_datab.loc[branch_datab['branch-type'] == 1]

#dfb.to_csv(r'./before.csv')
draw.overlay_euclidean_skeleton_2d(maskb,
                                   branch_datab,
                                   skeleton_color_source='branch-type')

plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
Esempio n. 6
0
def skeleton_image(folder, image_file, threshold=50, area_thresh=50,
                   tofilt=True, ajar=True, close=True, figsize=(10, 10),
                   show=False, channel=0, disp_binary=True, imname=None):
    """Skeletonizes the image and returns properties of each skeleton.

    Composite function of binary_image, clean_image and skeletonizing
    functionality from skan.

    Parameters
    ----------
    folder : string
        Directory containing image_file
    image_file : string
        Filename of image to be analyzed
    threshold : int or float
        Intensity threshold level for threshold.
    area_thresh : int or float
        Size cutoff level to remove small objects
    figsize : tuple of int or float
        Size out output figure
    show : bool
        If True, prints image to Jupyter notebook
    channel : int
        If multichannel is True, reads in image corresponding to this channel in
        file.
    disp_binary: bool
        If True, prints binary image instead of raw image
    imname : string
        Output filename

    Returns
    -------
    skeleton0 : numpy.ndarray
        Skeletonized version of input image_file
    branch_data_short : pandas.core.frame.DataFrame
        Data associated with each branch found in input image
    nbranches : list
        Number of branches on each cell in branch_data_short
    short_image : numpy.ndarray
        Cleaned up binary image from image_file prior to skeletonization
    props : skimage.object
        Contains all properties of objects identified in image

    Examples
    --------

    """

    # Median filtered image.
    fname = '{}/{}'.format(folder, image_file)
    image0 = sio.imread(fname)
    if channel is None:
        image0 = np.ceil(255 * (image0[:, :] / image0[:, :].max())).astype(int)
    else:
        image0 = np.ceil(255 * (image0[:, :, channel
                                       ] / image0[:, :, channel
                                                  ].max())).astype(int)

    if tofilt:
        image0 = skimage.filters.median(image0)
        image_file = 'filt_{}'.format(image_file)
        sio.imsave(folder+'/'+image_file, image0)

    # label image
    short_image, props = clean_image(folder, image_file, threshold=threshold,
                                     area_thresh=area_thresh, ajar=ajar,
                                     close=close, imname='labelim.tif',
                                     channel=None, show=False)
    short_image = short_image > 1
    # Skeletonize
    skeleton0 = skeletonize(short_image)

    branch_data = csr.summarise(skeleton0)
    branch_data_short = branch_data

    # Remove small branches
    mglia = branch_data['skeleton-id'].max()
    nbranches = []

    ncount = 0
    for i in range(1, mglia+1):
        bcount = branch_data[branch_data['skeleton-id'
                                         ] == i]['skeleton-id'].count()
        if bcount > 0:
            ids = branch_data.index[branch_data['skeleton-id'] == i].tolist()
            nbranches.append(bcount)
            for j in range(0, len(ids)):
                branch_data_short.drop([ids[j]])

            ncount = ncount + 1
    if show:
        fig, ax = plt.subplots(figsize=figsize)
        if disp_binary:
            draw.overlay_euclidean_skeleton_2d(short_image, branch_data_short,
                                               skeleton_color_source='branch-type',
                                               axes=ax)
        else:
            draw.overlay_euclidean_skeleton_2d(image0, branch_data_short,
                                               skeleton_color_source='branch-type',
                                               axes=ax)

    if imname is None:
        output = "skel_{}".format(image_file)
    else:
        output = imname
    plt.savefig('{}/{}'.format(folder, output))

    skel = Bunch(im=skeleton0, branchdat=branch_data_short, nbran=nbranches,
                 shortim=short_image, props=props)

    return skel
    branch_data = summarize(Skeleton(image_skeleton))

    print(branch_data.head())

    fig = plt.plot()

    branch_data.hist(column='branch-distance', by='branch-type', bins=100)

    result_file = (save_path + base_name + '_hist.' + ext)

    plt.savefig(result_file,
                transparent=True,
                bbox_inches='tight',
                pad_inches=0)

    fig = plt.plot()

    draw.overlay_euclidean_skeleton_2d(source_image,
                                       branch_data,
                                       skeleton_color_source='branch-distance',
                                       skeleton_colormap='hsv')

    result_file = (save_path + base_name + '_overlay.' + ext)

    plt.savefig(result_file,
                transparent=True,
                bbox_inches='tight',
                pad_inches=0)

    print(filename, abs_path)