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


Python ndimage.binary_erosion函数代码示例

本文整理汇总了Python中scipy.ndimage.binary_erosion函数的典型用法代码示例。如果您正苦于以下问题:Python binary_erosion函数的具体用法?Python binary_erosion怎么用?Python binary_erosion使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: find_initial_worm

def find_initial_worm(small_image, well_mask):
    # plan here is to find known good worm edges with Canny using a stringent threshold, then
    # relax the threshold in the vicinity of the good edges.
    # back off another pixel from the well edge to avoid gradient from the edge
    shrunk_mask = ndimage.binary_erosion(well_mask, structure=S)
    smoothed, gradient, sobel = canny.prepare_canny(small_image, 2, shrunk_mask)
    local_maxima = canny.canny_local_maxima(gradient, sobel)
    # Calculate stringent and medium-stringent thresholds. The stringent threshold
    # is the 200th-brightest edge pixel, and the medium is the 450th-brightest pixel
    highp = 100 * (1-200/local_maxima.sum())
    highp = max(highp, 94)
    mediump = 100 * (1-450/local_maxima.sum())
    mediump = max(mediump, 94)
    low_worm, medium_worm, high_worm = numpy.percentile(gradient[local_maxima], [94, mediump, highp])
    stringent_worm = canny.canny_hysteresis(local_maxima, gradient, low_worm, high_worm)
    # Expand out 20 pixels from the stringent worm edges to make our search space
    stringent_area = ndimage.binary_dilation(stringent_worm, mask=well_mask, iterations=20)
    # now use the relaxed threshold but only in the stringent area
    relaxed_worm = canny.canny_hysteresis(local_maxima, gradient, low_worm, medium_worm) & stringent_area
    # join very close-by objects, and remove remaining small objects
    candidate_worm = ndimage.binary_dilation(relaxed_worm, structure=S)
    candidate_worm = ndimage.binary_erosion(candidate_worm)
    candidate_worm = mask.remove_small_area_objects(candidate_worm, 30, structure=S)
    # Now figure out the biggest blob of nearby edges, and call that the worm region
    glommed_candidate = ndimage.binary_dilation(candidate_worm, structure=S, iterations=2)
    glommed_candidate = ndimage.binary_erosion(glommed_candidate, iterations=2)
    # get just outline, not any regions filled-in due to closing
    glommed_candidate ^= ndimage.binary_erosion(glommed_candidate)
    glommed_candidate = mask.get_largest_object(glommed_candidate, structure=S)
    worm_area = ndimage.binary_dilation(glommed_candidate, mask=well_mask, structure=S, iterations=12)
    worm_area = mask.fill_small_radius_holes(worm_area, max_radius=15)
    candidate_edges = relaxed_worm & candidate_worm & worm_area
    return candidate_edges, worm_area
开发者ID:zpincus,项目名称:scanner-lifespans,代码行数:33,代码来源:find_worm.py

示例2: cell_to_image

	def cell_to_image(self):
	
		# Find x, y coordinate bounds
		x_res = max(self.pix_list, key=itemgetter(0))[0]
		y_res = max(self.pix_list, key=itemgetter(1))[1]

		# Creating labeled_img
		self.cell_img = NP.zeros([x_res+2, y_res+2], dtype=NP.int_)
		
		for (x_pix, y_pix) in self.pix_list:
			self.cell_img[x_pix-1, y_pix-1] = 1

		# Find the pixels that make up the perimeter
		eroded_image = NDI.binary_erosion(self.cell_img)

		eroded_image_open = NDI.binary_opening(eroded_image, structure=NP.ones((3,3)))
		eroded_image_open2 = NDI.binary_erosion(eroded_image_open)

		# self.perim_img = self.cell_img - eroded_image
		self.eroded_img = eroded_image_open - eroded_image_open2
		self.perim_img = self.cell_img - eroded_image

		# Create a list of the coordinates of the pixels (use the center of the pixels)
		perim_image_ind = NP.where(self.perim_img == 1)
		perim_image_coord = NP.array([perim_image_ind[0], perim_image_ind[1]])
		self.perim_coord = NP.transpose(perim_image_coord)

		return
开发者ID:ldarrick,项目名称:Research-Scripts,代码行数:28,代码来源:extractcellfeatures.py

示例3: prepare_roi_from_probtissue

def prepare_roi_from_probtissue(in_file, epi_mask, epi_mask_erosion_mm=0,
                                erosion_mm=0):
    import os
    import nibabel as nb
    import scipy.ndimage as nd

    probability_map_nii = nb.load(in_file)
    probability_map_data = probability_map_nii.get_data()

    # thresholding
    probability_map_data[probability_map_data < 0.95] = 0
    probability_map_data[probability_map_data != 0] = 1

    epi_mask_nii = nb.load(epi_mask)
    epi_mask_data = epi_mask_nii.get_data()
    if epi_mask_erosion_mm:
        epi_mask_data = nd.binary_erosion(epi_mask_data,
                                      iterations=int(epi_mask_erosion_mm/max(probability_map_nii.header.get_zooms()))).astype(int)
        eroded_mask_file = os.path.abspath("erodd_mask.nii.gz")
        nb.Nifti1Image(epi_mask_data, epi_mask_nii.affine, epi_mask_nii.header).to_filename(eroded_mask_file)
    else:
        eroded_mask_file = epi_mask
    probability_map_data[epi_mask_data != 1] = 0

    # shrinking
    if erosion_mm:
        iter_n = int(erosion_mm/max(probability_map_nii.header.get_zooms()))
        probability_map_data = nd.binary_erosion(probability_map_data,
                                                 iterations=iter_n).astype(int)


    new_nii = nb.Nifti1Image(probability_map_data, probability_map_nii.affine,
                             probability_map_nii.header)
    new_nii.to_filename("roi.nii.gz")
    return os.path.abspath("roi.nii.gz"), eroded_mask_file
开发者ID:shoshber,项目名称:preprocessing-workflow,代码行数:35,代码来源:utils.py

示例4: binary_erosion

def binary_erosion(image, selem=None, out=None):
    """Return fast binary morphological erosion of an image.

    This function returns the same result as greyscale erosion but performs
    faster for binary images.

    Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all
    pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright
    regions and enlarges dark regions.

    Parameters
    ----------
    image : ndarray
        Binary input image.
    selem : ndarray, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use cross-shaped structuring element (connectivity=1).
    out : ndarray of bool, optional
        The array to store the result of the morphology. If None is
        passed, a new array will be allocated.

    Returns
    -------
    eroded : ndarray of bool or uint
        The result of the morphological erosion taking values in
        ``[False, True]``.

    """
    if out is None:
        out = np.empty(image.shape, dtype=np.bool)
    ndi.binary_erosion(image, structure=selem, output=out, border_value=True)
    return out
开发者ID:Cadair,项目名称:scikit-image,代码行数:32,代码来源:binary.py

示例5: get_base_positions_bimanual

def get_base_positions_bimanual(rars, joints):
    PR2.SetDOFValues(joints)
    f = np.load("/home/joschu/bulletsim/data/knots/l_reachability.npz")
    
    
    xtorso, ytorso, ztorso = xyz_torso = PR2.GetLink("torso_lift_link").GetTransform()[:3,3] - PR2.GetLink("base_footprint").GetTransform()[:3,3]
        
    xyz_l = rars["xyz_l"]
    xyz_r = rars["xyz_r"]
    
    left_used = (rars["grab_l"] > -1).any()
    right_used = (rars["grab_r"] > -1).any()
    print "left_used: %i, right_used: %i"%(left_used, right_used)
    
    invreachL = f["reachable"][::-1, ::-1, :] #places that can reach the origin
    invreachR = f["reachable"][::-1, :, :] #places that can reach the origin

    invreachL = ndi.binary_erosion(invreachL,np.ones((3,3,3)))
    invreachR = ndi.binary_erosion(invreachR,np.ones((3,3,3)))
    

    xticksir = - f["xticks"][::-1]
    yticksirL = - f["yticks"][::-1]
    yticksirR = f["yticks"]
    zticksir = f["zticks"]
    
    leftbounds = [xminL, xmaxL, yminL, ymaxL] = get_xy_bounds(xyz_l, xticksir, yticksirL) # bounds for torso position array
    rightbounds = [xminR, xmaxR, yminR, ymaxR] = get_xy_bounds(xyz_r, xticksir, yticksirR) 
    
    [xmin, xmax, ymin, ymax] = [min(xminL, xminR), max(xmaxL, xmaxR), min(yminL, yminR), max(ymaxL, ymaxR)]

    if WITH_VIEWER:
        HANDLES.append(ENV.drawlinestrip(points=np.array([[xmin, ymin, 0],
                                                        [xmin, ymax, 0],
                                                        [xmax, ymax, 0],
                                                        [xmax, ymin, 0]]),
                               linewidth=1.0))  

    xticks = np.arange(xmin-DL, xmax+DL, DL) # torso positions
    yticks = np.arange(ymin-DL, ymax+DL, DL)

    collision_cost = 1e9
    left_fail_cost = 1000000. if left_used else 100
    right_fail_cost = 1000000. if right_used else 100
    dist_cost = 1.

    base_costs = np.zeros((len(rars), xticks.size, yticks.size))
    coll_mask = get_collision_mask(xticks, yticks)
    base_costs += collision_cost * coll_mask[None,:,:]
    
    for (i, (xl, yl, zl), (xr, yr, zr)) in zip(xrange(len(rars)), xyz_l, xyz_r):
        zlind = intround(  (zl - ztorso - zticksir[0]) / DL  )
        zrind = intround(  (zr - ztorso - zticksir[0]) / DL  )
                
        base_costs[i] += (shift_and_place_image(invreachL[:,:,zlind], xl, yl, xticksir, yticksirL, xticks, yticks) <= 0) * left_fail_cost + dist_cost
        base_costs[i] += (shift_and_place_image(invreachR[:,:,zrind], xr, yr, xticksir, yticksirR, xticks, yticks) <= 0) * right_fail_cost + dist_cost
            
    xinds_base, yinds_base = get_feasible_path(base_costs).T
    return np.c_[xticks[xinds_base] - xtorso, yticks[yinds_base] - ytorso]
开发者ID:benkehoe,项目名称:python,代码行数:59,代码来源:reachability.py

示例6: erosion

def erosion():
    image_list = get_one_imagefrom_mnist()
    image_array =np.asarray(image_list)
    image =image_array.reshape(28, 28)
    
    ndimage.binary_erosion(image).astype(int)
    plt.imshow(image, cmap=cm.binary)
    plt.show()
开发者ID:ybdesire,项目名称:machinelearning,代码行数:8,代码来源:scikit_image_process.py

示例7: edge_detect_first

def edge_detect_first(i):
    import numpy as np
    from scipy import ndimage
    ero =  ndimage.binary_erosion(i, iterations=2).astype(i.dtype)
    dil =  ndimage.binary_dilation(i, iterations=1).astype(i.dtype)
    sep = dil-ero
    sep = ndimage.binary_erosion(sep, iterations=1).astype(sep.dtype)
    sep[sep==0]=np.nan
    return sep
开发者ID:amadeuskanaan,项目名称:Tourettome,代码行数:9,代码来源:plot_volumes.py

示例8: analyseClusters

def analyseClusters(binary, newlabels):
    """
    Calculates the sizes and porosities of the clusters.
    """
    
    # dilate particles to find cluster
    dilated = ndimage.binary_dilation(binary, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER)
    labels, num = label(dilated, background=0, return_num=True)
    pxArea = (_CONVERSIONFACTOR_FOR_PIXEL) ** 2
    outputImage = labels.copy()
    clusterAreas = np.zeros(num)
    porosities = np.zeros(num)
    circumference = np.zeros(num)
    fcirc = np.zeros(num)
    particlesPerCluster = np.zeros(num)
    illegalIndex = []
    
    for i in range(num):
        cluster = labels == i
        cluster = ndimage.binary_fill_holes(cluster)
        helper = np.zeros_like(newlabels)
        helper[cluster] = newlabels[cluster]
        newLabel, particleNum = label(helper, background=0, return_num=True)
        particlesPerCluster[i] = particleNum
        particleArea = float(np.sum(binary[cluster].astype(np.int)))
        
        # cluster area and porosity
        outputImage[cluster] = i
        helper = ndimage.binary_erosion(cluster, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER-3, border_value=1)        
        helper = ndimage.binary_erosion(helper, iterations=3, border_value=0)
        fl = float(np.sum(helper[cluster].astype(np.int)))
        clusterAreas[i] = fl * pxArea
        porosity = (fl - particleArea)/ fl
        porosity = porosity if porosity >= 0 else 0.0  # porosity can not be less than 0
        porosities[i] = porosity
        
        # circumference
        new = np.zeros((helper.shape[0],helper.shape[1],3), dtype=np.uint8)
        new[:,:,1] = helper
        gray = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
        gray[gray > 0] = 255
        blur = cv2.GaussianBlur(gray,(5,5),0)
        gray = cv2.Canny(blur, 10, 200)
        contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        arclength = 0
        for con in contours:
            arclength += cv2.arcLength(con,True)
        circumference[i] = arclength * _CONVERSIONFACTOR_FOR_PIXEL
        fcirc[i] = (4. * np.pi * fl) / arclength**2
        
        if fcirc[i] > 1.0:  # fcirc can not be greater than 1
            illegalIndex.append(i)
    
    fcirc = np.delete(fcirc, illegalIndex)
    clusterData = {'areas':clusterAreas,'circ':circumference,'ppc':particlesPerCluster,'fcirc':fcirc,'porosities':porosities}
    return outputImage, clusterData, num
开发者ID:MATSEAusbildung-RWTHAachen,项目名称:Clusterman,代码行数:56,代码来源:histoComp.py

示例9: test_binary_closing_noninteger_brute_force_passes_when_true

def test_binary_closing_noninteger_brute_force_passes_when_true():
    # regression test for gh-9905, gh-9909: ValueError for
    # non integer iterations
    data = numpy.ones([1])

    assert sndi.binary_erosion(
        data, iterations=2, brute_force=1.5
    ) == sndi.binary_erosion(data, iterations=2, brute_force=bool(1.5))
    assert sndi.binary_erosion(
        data, iterations=2, brute_force=0.0
    ) == sndi.binary_erosion(data, iterations=2, brute_force=bool(0.0))
开发者ID:WarrenWeckesser,项目名称:scipy,代码行数:11,代码来源:test_morphology.py

示例10: erode

def erode(volume, iterations, out=None):
    if out is None:
        out = zeros_like(volume)
    if SCIPY:
        binary_erosion(volume.array, iterations=iterations, output=out.array)
    else:
        tmp = volume.array.copy()
        for i in range(iterations):
            binary_erosion(tmp, out.array)
            tmp[:] = out.array[:]

    return out
开发者ID:mtrellet,项目名称:disvis,代码行数:12,代码来源:volume.py

示例11: _tpm2roi

def _tpm2roi(in_tpm, in_mask, mask_erosion_mm=None, erosion_mm=None,
             mask_erosion_prop=None, erosion_prop=None, pthres=0.95,
             newpath=None):
    """
    Generate a mask from a tissue probability map
    """
    tpm_img = nb.load(in_tpm)
    roi_mask = (tpm_img.get_data() >= pthres).astype(np.uint8)

    eroded_mask_file = None
    erode_in = (mask_erosion_mm is not None and mask_erosion_mm > 0 or
                mask_erosion_prop is not None and mask_erosion_prop < 1)
    if erode_in:
        eroded_mask_file = fname_presuffix(in_mask, suffix='_eroded',
                                           newpath=newpath)
        mask_img = nb.load(in_mask)
        mask_data = mask_img.get_data().astype(np.uint8)
        if mask_erosion_mm:
            iter_n = max(int(mask_erosion_mm / max(mask_img.header.get_zooms())), 1)
            mask_data = nd.binary_erosion(mask_data, iterations=iter_n)
        else:
            orig_vol = np.sum(mask_data > 0)
            while np.sum(mask_data > 0) / orig_vol > mask_erosion_prop:
                mask_data = nd.binary_erosion(mask_data, iterations=1)

        # Store mask
        eroded = nb.Nifti1Image(mask_data, mask_img.affine, mask_img.header)
        eroded.set_data_dtype(np.uint8)
        eroded.to_filename(eroded_mask_file)

        # Mask TPM data (no effect if not eroded)
        roi_mask[~mask_data] = 0

    # shrinking
    erode_out = (erosion_mm is not None and erosion_mm > 0 or
                 erosion_prop is not None and erosion_prop < 1)
    if erode_out:
        if erosion_mm:
            iter_n = max(int(erosion_mm / max(tpm_img.header.get_zooms())), 1)
            iter_n = int(erosion_mm / max(tpm_img.header.get_zooms()))
            roi_mask = nd.binary_erosion(roi_mask, iterations=iter_n)
        else:
            orig_vol = np.sum(roi_mask > 0)
            while np.sum(roi_mask > 0) / orig_vol > erosion_prop:
                roi_mask = nd.binary_erosion(roi_mask, iterations=1)

    # Create image to resample
    roi_fname = fname_presuffix(in_tpm, suffix='_roi', newpath=newpath)
    roi_img = nb.Nifti1Image(roi_mask, tpm_img.affine, tpm_img.header)
    roi_img.set_data_dtype(np.uint8)
    roi_img.to_filename(roi_fname)
    return roi_fname, eroded_mask_file or in_mask
开发者ID:poldracklab,项目名称:niworkflows,代码行数:52,代码来源:utils.py

示例12: get_uv_mask

def get_uv_mask(vertices_vis, triangles, uv_coords, h, w, resolution):
    triangles = triangles.T
    vertices_vis = vertices_vis.astype(np.float32)
    uv_mask = render_texture(uv_coords.T, vertices_vis[np.newaxis, :], triangles, resolution, resolution, 1)
    uv_mask = np.squeeze(uv_mask > 0)
    uv_mask = ndimage.binary_closing(uv_mask)
    uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))  
    uv_mask = ndimage.binary_closing(uv_mask)
    uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))  
    uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))  
    uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))  
    uv_mask = uv_mask.astype(np.float32)

    return np.squeeze(uv_mask)
开发者ID:royaljava,项目名称:PRNet,代码行数:14,代码来源:render_app.py

示例13: process_blob

def process_blob(cim):
    #cim = ndimage.binary_erosion(cim>0)
    for i in range(4):
        cim = ndimage.binary_erosion(cim>0)
        cim=ndimage.binary_dilation(cim>0)

    filterk = np.ones(Param.process_conv_size);
    cim = ndimage.convolve(cim, filterk, mode='constant', cval=0.0)

    for i in range(Param.num_dilation):
        cim = ndimage.binary_dilation(cim>0)
    for i in range(Param.num_erosion):
        cim = ndimage.binary_erosion(cim>0)
    return cim
开发者ID:deepakrox,项目名称:FastObjectLocalization,代码行数:14,代码来源:deconv_utils.py

示例14: _post_process_mask

def _post_process_mask(mask, affine, opening=2, connected=True,
                       warning_msg=""):
    if opening:
        opening = int(opening)
        mask = ndimage.binary_erosion(mask, iterations=opening)
    mask_any = mask.any()
    if not mask_any:
        warnings.warn("Computed an empty mask. %s" % warning_msg,
            MaskWarning, stacklevel=2)
    if connected and mask_any:
        mask = largest_connected_component(mask)
    if opening:
        mask = ndimage.binary_dilation(mask, iterations=2 * opening)
        mask = ndimage.binary_erosion(mask, iterations=opening)
    return mask, affine
开发者ID:jeromedockes,项目名称:nilearn,代码行数:15,代码来源:masking.py

示例15: _post_process_mask

def _post_process_mask(mask, affine, opening=2, connected=True, msg=""):
    if opening:
        opening = int(opening)
        mask = ndimage.binary_erosion(mask, iterations=opening)
    mask_any = mask.any()
    if not mask_any:
        warnings.warn("Computed an empty mask. %s" % msg,
            MaskWarning, stacklevel=2)
    if connected and mask_any:
        mask = largest_connected_component(mask)
    if opening:
        mask = ndimage.binary_dilation(mask, iterations=2*opening)
        mask = ndimage.binary_erosion(mask, iterations=opening)
    return Nifti1Image(_utils.as_ndarray(mask, dtype=np.int8),
                       affine)
开发者ID:VirgileFritsch,项目名称:nilearn,代码行数:15,代码来源:masking.py


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