Python skimage.morphology 模块,binary_erosion() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用skimage.morphology.binary_erosion()

项目:qtim_ROP    作者:QTIM-Lab    | 项目源码 | 文件源码
def create_mask(im_arr, erode=0):

    if im_arr.shape[2] == 3:
        im_arr = rgb2gray(im_arr)

    thresh = 0.05
    inv_bin = np.invert(im_arr > thresh)
    all_labels = measure.label(inv_bin)

    # Select largest object and invert
    seg_arr = all_labels == 0

    if erode > 0:
        strel = selem.disk(erode, dtype=np.bool)
        seg_arr = binary_erosion(seg_arr, selem=strel)
    elif erode < 0:
        strel = selem.disk(abs(erode), dtype=np.bool)
        seg_arr = binary_dilation(seg_arr, selem=strel)

    return seg_arr.astype(np.bool)
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def compute_binary_mask_sprengel(spectrogram, threshold):
    """ Computes a binary mask for the spectrogram
    # Arguments
        spectrogram : a numpy array representation of a spectrogram (2-dim)
        threshold   : a threshold for times larger than the median
    # Returns
        binary_mask : the binary mask
    """
    # normalize to [0, 1)
    norm_spectrogram = normalize(spectrogram)

    # median clipping
    binary_image = median_clipping(norm_spectrogram, threshold)

    # erosion
    binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4)))

    # dilation
    binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))

    # extract mask
    mask = np.array([np.max(col) for col in binary_image.T])
    mask = smooth_mask(mask)

    return mask
项目:TC-Lung_nodules_detection    作者:Shicoder    | 项目源码 | 文件源码
def get_segmented_lungs(im, plot=False):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is    to keep nodules attached to the lung wall.
    selem = disk(10) # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def _create_facade_mask(self):
        facade_mask = self.driving_layers.building() > 0.5
        facade_mask = binary_erosion(facade_mask, disk(10))  # Sky is noisy
        # Remove non-wall elements from the facade (we want just the wall)
        facade_mask[self.window_mask()] = 0
        facade_mask[self.facade_layers.door() > 0.5] = 0
        facade_mask[self.balcony_mask()] = 0
        # facade_mask[self.shop_mask()] = 0
        facade_mask[self.pillar_mask()] = 0
        facade_mask[self.facade_layers.molding() > 0.5] = 0
        return facade_mask
项目:tda-image-analysis    作者:rachellevanger    | 项目源码 | 文件源码
def get_unclassified_defect_region(classified_defect_region, td_detect, radius):

  # Expand topological defects by radius
  td_region = morphology.binary_dilation((td_detect != 0).astype(np.int), morphology.disk(radius))

  # Remove classified region
  unclassified_defect_region = np.multiply(td_region, 1 - classified_defect_region)


  unclassified_defect_region = morphology.binary_dilation(unclassified_defect_region, morphology.disk(radius))
  unclassified_defect_region = morphology.binary_erosion(unclassified_defect_region, morphology.disk(radius))

  return unclassified_defect_region
项目:tensorlayer-chinese    作者:shorxp    | 项目源码 | 文件源码
def binary_erosion(x, radius=3):
    """ Return binary morphological erosion of an image,
    see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`_.

    Parameters
    -----------
    x : 2D array image.
    radius : int for the radius of mask.
    """
    from skimage.morphology import disk, dilation, binary_erosion
    mask = disk(radius)
    x = binary_erosion(x, selem=mask)
    return x
项目:kaggle_ndsb2017    作者:juliandewit    | 项目源码 | 文件源码
def get_segmented_lungs(im, plot=False):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is    to keep nodules attached to the lung wall.
    selem = disk(10) # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
项目:bird-species-classification    作者:johnmartinsson    | 项目源码 | 文件源码
def sprengel_binary_mask_from_wave_file(filepath):
    fs, x = utils.read_wave_file(filepath)
    Sxx = sp.wave_to_amplitude_spectrogram(x, fs)
    Sxx_log = sp.wave_to_log_amplitude_spectrogram(x, fs)

    # plot spectrogram
    fig = plt.figure(1)
    subplot_image(Sxx_log, 411, "Spectrogram")

    Sxx = pp.normalize(Sxx)
    binary_image = pp.median_clipping(Sxx, 3.0)

    subplot_image(binary_image + 0, 412, "Median Clipping")

    binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4)))

    subplot_image(binary_image + 0, 413, "Erosion")

    binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))

    subplot_image(binary_image + 0, 414, "Dilation")

    mask = np.array([np.max(col) for col in binary_image.T])
    mask = morphology.binary_dilation(mask, np.ones(4))
    mask = morphology.binary_dilation(mask, np.ones(4))

    # plot_vector(mask, "Mask")

    fig.set_size_inches(10, 12)
    plt.tight_layout()
    fig.savefig(utils.get_basename_without_ext(filepath) + "_binary_mask.png", dpi=100)
项目:cancer    作者:yancz1989    | 项目源码 | 文件源码
def segment_lung_mask(image, speedup=4):
    def largest_label_volume(im, bg=-1):
        vals, counts = np.unique(im, return_counts=True)

        counts = counts[vals != bg]
        vals = vals[vals != bg]

        if len(counts) > 0:
            return vals[np.argmax(counts)]
        else:
            return None
    if speedup>1:
        smallImage = transform.downscale_local_mean(image,(1,speedup,speedup));
    else:
        smallImage = image;
    # not actually binary, but 1 and 2. 
    # 0 is treated as background, which we do not want
    binary_image = np.array((smallImage < -320) & (smallImage>-1400), dtype=np.int8)
    #return binary_image;
    for i, axial_slice in enumerate(binary_image):
        axial_slice = 1-axial_slice
        labeling = measure.label(axial_slice)
        l_max = largest_label_volume(labeling, bg=0)
        if l_max is not None: #This slice contains some lung
            binary_image[i][(labeling!=l_max)] = 1

    # Remove other air pockets insided body
    labels = measure.label(binary_image, background=0)
    m = labels.shape[0]//2;
    check_layers = labels[m-12:m+20:4,:,:];
    l_max = largest_label_volume(check_layers, bg=0)

    while l_max is not None: # There are air pockets
        idx = np.where(check_layers==l_max);
        ii = np.vstack(idx[1:]).flatten();
        if np.max(ii)>labels.shape[1]-24/speedup or np.min(ii)<24/speedup:
            binary_image[labels==l_max] = 0;
            labels = measure.label(binary_image, background=0)
            m = labels.shape[0]//2;
            check_layers = labels[m-12:m+20:4,:,:];
            l_max = largest_label_volume(check_layers, bg=0)
        else:     
            binary_image[labels != l_max] = 0
            break

    if speedup<=1:
        return binary_image
    else:
        res = np.zeros(image.shape,dtype=np.uint8);
        for i,x in enumerate(binary_image):
            orig = np.copy(x);
            x = binary_dilation(x,disk(5))
            x = binary_erosion(x,disk(5))
            x = np.logical_or(x,orig)            
            y = transform.resize(x*1.0,image.shape[1:3]);
            res[i][y>0.5]=1

        return res;
项目:luna16    作者:gzuidhof    | 项目源码 | 文件源码
def unet_candidates():
    cands = glob.glob("../data/predictions_epoch9_23_all/*.png")
    #df = pd.DataFrame(columns=['seriesuid','coordX','coordY','coordZ','class'])
    data = []
    imname = ""
    origin = []
    spacing = []
    nrimages = 0
    for name in tqdm(cands):

        #image = imread(name)
        image_t = imread(name)
        image_t = image_t.transpose()
        #Thresholding
        image_t[image_t<THRESHOLD] = 0
        image_t[image_t>0] = 1
        #erosion
        selem = morphology.disk(1)
        image_eroded = image_t
        image_eroded = morphology.binary_erosion(image_t,selem=selem)

        label_im, nb_labels = ndimage.label(image_eroded)
        imname3 = os.path.split(name)[1].replace('.png','')

        splitted = imname3.split("slice")
        slice = splitted[1]
        imname2 = splitted[0][:-1]
        centers = []
        for i in xrange(1,nb_labels+1):
            blob_i = np.where(label_im==i,1,0)
            mass = center_of_mass(blob_i)
            centers.append([mass[1],mass[0]])


        if imname2 != imname:
            if os.path.isfile("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2)):
                with open("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2), 'rb') as handle:
                    dic = pickle.load(handle)
                    origin = dic["origin"]
                    spacing = dic["spacing"]

            imname = imname2
            nrimages +=1

        for center in centers:
            coords = voxel_2_world([int(slice),center[1]+(512-324)*0.5,center[0]+(512-324)*0.5],origin,spacing)
            data.append([imname2,coords[2],coords[1],coords[0],'?'])

        #if nrimages == 5:
        #    break

    df = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)
    save_candidates("../data/candidates_unet_final_23.csv",df)
项目:huaat_ml_dl    作者:ieee820    | 项目源码 | 文件源码
def get_masks(im):
    '''
    Step 1: Convert into a binary image.
    '''
    print('step1')
    binary = im < 604
    # plt.imshow(binary,cmap=plt.cm.gray)
    # plt.show()

    '''
    Step 2: Remove the blobs connected to the border of the image.
    '''
    print('step2')
    cleared = clear_border(binary)
    # plt.imshow(cleared,cmap=plt.cm.gray)
    # plt.show()
    '''
    Step 3: Label the image.
    '''
    print('step3')
    label_image = label(cleared)
    # plt.imshow(label_image,cmap=plt.cm.gray)
    # plt.show()

    '''
    Step 4: Keep the labels with 2 largest areas.
    '''
    print('step4')
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < 10 and region.area > 3:
                print(region.centroid,region.area)
                # print(region.area)
                centroid = region.centroid
                plot_im(im,centroid)
                # label_image[int(centroid[0]),int(centroid[1])] = 1000
                # for coordinates in region.coords:
                #     label_image[coordinates[0], coordinates[1]] = 0
    # binary = label_image > 999
    # plt.imshow(binary,cmap=plt.cm.gray)
    # plt.show()

    '''
    Step 5: Erosion operation with a disk of radius 2. This operation is
    seperate the lung nodules attached to the blood vessels.
    '''
    # print('step5')
    # selem = disk(2)
    # binary = binary_erosion(binary, selem)
    # plt.imshow(binary,cmap=plt.cm.gray)
    # plt.show()
项目:kaggle_dsb    作者:syagev    | 项目源码 | 文件源码
def unet_candidates():
    cands = glob.glob('%s/*.png' % sys.argv[1]) #"/razberry/workspace/dsb_nodule_detection.109fd54/*.png
    #df = pd.DataFrame(columns=['seriesuid','coordX','coordY','coordZ','class'])
    data = []
    imname = ""
    origin = []
    spacing = []
    nrimages = 0
    for name in tqdm(cands):

        #image = imread(name)
        image_t = imread(name)
        image_t = image_t.transpose()
        #Thresholding
        image_t[image_t<THRESHOLD] = 0
        image_t[image_t>0] = 1
        #erosion
        selem = morphology.disk(1)
        image_eroded = image_t
        image_eroded = morphology.binary_erosion(image_t,selem=selem)

        label_im, nb_labels = ndimage.label(image_eroded)
        imname3 = os.path.split(name)[1].replace('.png','')

        splitted = imname3.split("_")
        slice = splitted[1]
        imname2 = splitted[0][:-1]
        centers = []
        for i in xrange(1,nb_labels+1):
            blob_i = np.where(label_im==i,1,0)
            mass = center_of_mass(blob_i)
            centers.append([mass[1],mass[0]])


        if imname2 != imname:
            if os.path.isfile("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2)):
                with open("../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle".format(imname2), 'rb') as handle:
                    dic = pickle.load(handle)
                    origin = dic["origin"]
                    spacing = dic["spacing"]

            imname = imname2
            nrimages +=1

        for center in centers:
            # coords = voxel_2_world([int(slice),center[1]+(512-324)*0.5,center[0]+(512-324)*0.5],origin,spacing)
            coords = [int(slice),center[1],center[0]]
            data.append([imname2,coords[2],coords[1],coords[0],'?'])

        #if nrimages == 5:
        #    break

    df = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)

    save_candidates('%s/candidates.csv' % work_dir, df)