当前位置: 首页>>代码示例>>Python>>正文


Python morphology.binary_erosion方法代码示例

本文整理汇总了Python中skimage.morphology.binary_erosion方法的典型用法代码示例。如果您正苦于以下问题:Python morphology.binary_erosion方法的具体用法?Python morphology.binary_erosion怎么用?Python morphology.binary_erosion使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.morphology的用法示例。


在下文中一共展示了morphology.binary_erosion方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_connected_component_shape

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def get_connected_component_shape(layer, event):
        cords = np.round(layer.coordinates).astype(int)
        val = layer.get_value()
        if val is None:
            return
        if val != 0:
            data = layer.data
            binary = data == val
            if 'Shift' in event.modifiers:
                binary_new = binary_erosion(binary)
                data[binary] = 0
                data[binary_new] = val
            else:
                binary_new = binary_dilation(binary)
                data[binary_new] = val
            size = np.sum(binary_new)
            layer.data = data
            msg = f'clicked at {cords} on blob {val} which is now {size} pixels'
        else:
            msg = f'clicked at {cords} on background which is ignored'
        layer.status = msg
        print(msg) 
开发者ID:napari,项目名称:napari,代码行数:24,代码来源:custom_mouse_functions.py

示例2: compute_binary_mask_sprengel

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
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 
开发者ID:johnmartinsson,项目名称:bird-species-classification,代码行数:27,代码来源:preprocessing.py

示例3: get_pos_dst_transform

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def get_pos_dst_transform(label_unmodified, img, instance, old_label=None, dt_method="edt"):
  label = np.where(label_unmodified == instance, 1, 0)

  # If an old label is available, then sample positive clicks on the difference between the two.
  if old_label is not None:
    # The difference should be taken only if there is atleast one object pixel in the difference.
    label = np.max(0, label - old_label) if np.any((label - old_label) == 1) else label

  # Leave a margin around the object boundary
  img_area = morphology.binary_erosion(label, morphology.diamond(D_MARGIN))
  img_area = img_area if len(np.where(img_area == 1)[0]) > 0 else np.copy(label)

  # Set of ground truth pixels.
  O = np.where(img_area == 1)
  # Randomly sample the number of positive clicks and negative clicks to use.
  num_clicks_pos = 0 if len(O) == 0 else random.sample(list(range(1, Npos + 1)), 1)
  # num_clicks_pos = random.sample(range(1, Npos + 1), 1)
  pts = get_sampled_locations(O, img_area, num_clicks_pos)
  u1 = get_distance_transform(pts, img_area, img=img, dt_method=dt_method)

  return u1, pts 
开发者ID:JonathonLuiten,项目名称:PReMVOS,代码行数:23,代码来源:Util.py

示例4: basin

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def basin(label_mask, wall):
    h,w = np.shape(label_mask)
    y, x = np.mgrid[0:h, 0:w]
    struct = generate_binary_structure(2,2)
    shifty, shiftx = np.mgrid[0:3, 0:3]
    shifty = (shifty-1).flatten()
    shiftx = (shiftx-1).flatten()

    for i in range(4):
        obdr = label_mask^binary_dilation(label_mask, struct)
        ibdr = label_mask^binary_erosion(label_mask, struct)
        yob, xob = y[obdr], x[obdr]        
        ynb, xnb = yob.reshape(-1,1)+shifty, xob.reshape(-1,1)+shiftx
        
        wallnb = np.min(map_coords(wall, (ynb, xnb))*(map_coords(ibdr, (ynb, xnb))==1)+\
                        5*(map_coords(ibdr, (ynb, xnb))!=1),1)
        keep = (wall[yob,xob]>wallnb)&(wallnb<=4)
        label_mask[yob[keep], xob[keep]]=True
        if np.sum(keep)==0:
            break
    return label_mask 
开发者ID:jacobkie,项目名称:2018DSB,代码行数:23,代码来源:postprocess0.py

示例5: buffer_mask_in_place

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def buffer_mask_in_place(mask_path, buffer_size):
    """Expands a mask in-place, overwriting the previous mask"""
    log = logging.getLogger(__name__)
    log.info("Buffering {} with buffer size {}".format(mask_path, buffer_size))
    mask = gdal.Open(mask_path, gdal.GA_Update)
    mask_array = mask.GetVirtualMemArray(eAccess=gdal.GA_Update)
    cache = morph.binary_erosion(mask_array.squeeze(), selem=morph.disk(buffer_size))
    np.copyto(mask_array, cache)
    mask_array = None
    mask = None 
开发者ID:clcr,项目名称:pyeo,代码行数:12,代码来源:raster_manipulation.py

示例6: _create_facade_mask

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
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 
开发者ID:jfemiani,项目名称:facade-segmentation,代码行数:13,代码来源:megafacade.py

示例7: sprengel_binary_mask_from_wave_file

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
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) 
开发者ID:johnmartinsson,项目名称:bird-species-classification,代码行数:33,代码来源:visualizer.py

示例8: create_mask

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def create_mask(aseg_data, dnum, enum):
    from skimage.morphology import binary_dilation, binary_erosion
    from skimage.measure import label
    print ("Creating dilated mask ...")

    # treat lateral orbital frontal and parsorbitalis special to avoid capturing too much of eye nerve
    lat_orb_front_mask = np.logical_or(aseg_data == 2012, aseg_data == 1012)
    parsorbitalis_mask = np.logical_or(aseg_data == 2019, aseg_data == 1019)
    frontal_mask = np.logical_or(lat_orb_front_mask, parsorbitalis_mask)
    print("Frontal region special treatment: ", format(np.sum(frontal_mask)))

    # reduce to binary
    datab = (aseg_data > 0)
    datab[frontal_mask] = 0
    # dilate and erode
    for x in range(dnum):
        datab = binary_dilation(datab, np.ones((3, 3, 3)))
    for x in range(enum):
        datab = binary_erosion(datab, np.ones((3, 3, 3)))

    # extract largest component
    labels = label(datab)
    assert (labels.max() != 0)  # assume at least 1 real connected component
    print("  Found {} connected component(s)!".format(labels.max()))

    if labels.max() > 1:
        print("  Selecting largest component!")
        datab = (labels == np.argmax(np.bincount(labels.flat)[1:]) + 1)

    # add frontal regions back to mask
    datab[frontal_mask] = 1

    # set mask
    aseg_data[~datab] = 0
    aseg_data[datab] = 1
    return aseg_data 
开发者ID:Deep-MI,项目名称:FastSurfer,代码行数:38,代码来源:reduce_to_aseg.py

示例9: get_simple_eroded_mask

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def get_simple_eroded_mask(mask, selem_size, small_annotations_size):
    if mask.sum() > small_annotations_size**2:
        selem = rectangle(selem_size, selem_size)
        mask_eroded = binary_erosion(mask, selem=selem)
    else:
        mask_eroded = mask
    return mask_eroded 
开发者ID:neptune-ai,项目名称:open-solution-mapping-challenge,代码行数:9,代码来源:preparation.py

示例10: get_simple_eroded_dilated_mask

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def get_simple_eroded_dilated_mask(mask, erode_selem_size, dilate_selem_size, small_annotations_size):
    if mask.sum() > small_annotations_size**2:
        selem = rectangle(erode_selem_size, erode_selem_size)
        mask_ = binary_erosion(mask, selem=selem)
    else:
        selem = rectangle(dilate_selem_size, dilate_selem_size)
        mask_ = binary_dilation(mask, selem=selem)
    return mask_ 
开发者ID:neptune-ai,项目名称:open-solution-mapping-challenge,代码行数:10,代码来源:preparation.py

示例11: postprocessing

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def postprocessing(prediction, threshold=0.75, dataset='G'):
    if dataset[0] == 'D':
        prediction = prediction.numpy()
        prediction_copy = np.copy(prediction)
        disc_mask = prediction[1]
        cup_mask = prediction[0]
        disc_mask = (disc_mask > 0.5)  # return binary mask
        cup_mask = (cup_mask > 0.1)  # return binary mask
        disc_mask = disc_mask.astype(np.uint8)
        cup_mask = cup_mask.astype(np.uint8)
        for i in range(5):
            disc_mask = scipy.signal.medfilt2d(disc_mask, 7)
            cup_mask = scipy.signal.medfilt2d(cup_mask, 7)
        disc_mask = morphology.binary_erosion(disc_mask, morphology.diamond(7)).astype(np.uint8)  # return 0,1
        cup_mask = morphology.binary_erosion(cup_mask, morphology.diamond(7)).astype(np.uint8)  # return 0,1
        disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8)  # return 0,1
        cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8)
        prediction_copy[0] = cup_mask
        prediction_copy[1] = disc_mask
        return prediction_copy
    else:
        prediction = prediction.numpy()
        prediction = (prediction > threshold)  # return binary mask
        prediction = prediction.astype(np.uint8)
        prediction_copy = np.copy(prediction)
        disc_mask = prediction[1]
        cup_mask = prediction[0]
        for i in range(5):
            disc_mask = scipy.signal.medfilt2d(disc_mask, 7)
            cup_mask = scipy.signal.medfilt2d(cup_mask, 7)
        disc_mask = morphology.binary_erosion(disc_mask, morphology.diamond(7)).astype(np.uint8)  # return 0,1
        cup_mask = morphology.binary_erosion(cup_mask, morphology.diamond(7)).astype(np.uint8)  # return 0,1
        disc_mask = get_largest_fillhole(disc_mask).astype(np.uint8)  # return 0,1
        cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8)
        prediction_copy[0] = cup_mask
        prediction_copy[1] = disc_mask
        return prediction_copy 
开发者ID:EmmaW8,项目名称:BEAL,代码行数:39,代码来源:Utils.py

示例12: get_segmented_lungs

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
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 
开发者ID:juliandewit,项目名称:kaggle_ndsb2017,代码行数:31,代码来源:helpers.py

示例13: postprocess

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
def postprocess(preds, config):
    assert preds.shape[2]==5
    ldelta = delta(preds[:,:,1:])
    #ldelta = delta0(preds[:,:,5:])
    connected = np.all(ldelta>config.GRADIENT_THRES, 2)
    base = connected * (preds[:,:,0]>config.MASK_THRES)
    
    wall = np.sum(np.abs(preds[:,:,1:]),axis = -1)   
    base_label = label(base) 
    vals, counts = np.unique(base_label[base_label>0], return_counts=True)
    for val in vals[(counts<config.CLIP_AREA_LOW)]:
        base_label[base_label==val]=0
    vals = vals[(counts>=config.CLIP_AREA_LOW)]

    for val in vals:
        
        label_mask = base_label == val   
        if np.sum(label_mask)==0:
            continue
        label_mask = remove_small_holes(label_mask)
        label_mask = basin(label_mask, wall)
        label_mask = remove_small_holes(label_mask)

        '''
        label_bdr = label_mask^binary_erosion(label_mask)
        min_wall = np.min(wall[label_mask])
        ave_bdr_wall = np.mean(wall[label_bdr])
        if ave_bdr_wall < min_wall + config.WALL_DEPTH:
            label_mask = 0
        '''
        base_label[label_mask] = val

    vals, counts = np.unique(base_label[base_label>0], return_counts=True)
    for val in vals[(counts<config.CLIP_AREA_LOW)]:
        base_label[base_label==val]=0        
    return base_label 
开发者ID:jacobkie,项目名称:2018DSB,代码行数:38,代码来源:postprocess0.py

示例14: unet_candidates

# 需要导入模块: from skimage import morphology [as 别名]
# 或者: from skimage.morphology import binary_erosion [as 别名]
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) 
开发者ID:gzuidhof,项目名称:luna16,代码行数:55,代码来源:candidates.py


注:本文中的skimage.morphology.binary_erosion方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。