• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python morphology.generate_binary_structure函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: get2DPeaks

def get2DPeaks(arr2D):
    """
        Generates peaks of a spectogram.
        Args:
            arr2D: spectogram.
        Returns:
            List of pairs (time, frequency) of peaks.
    """

    struct = generate_binary_structure(2, 1)
    neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)

    # find local maxima using our fliter shape
    local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D
    background = (arr2D == 0)
    eroded_background = binary_erosion(background, structure=neighborhood,
                                       border_value=1)

    # Boolean mask of arr2D with True at peaks
    detected_peaks = local_max - eroded_background

    # extract peaks
    amps = arr2D[detected_peaks]
    j, i = np.where(detected_peaks)

    # filter peaks
    amps = amps.flatten()
    peaks = zip(i, j, amps)
    peaks_filtered = [x for x in peaks if x[2] > AMP_MIN]  # freq, time, amp

    # get indices for frequency and time
    frequency_idx = [x[1] for x in peaks_filtered]
    time_idx = [x[0] for x in peaks_filtered]

    return zip(frequency_idx, time_idx)
开发者ID:rthrs,项目名称:TagIt,代码行数:35,代码来源:fingerprints.py


示例2: get_2D_peaks

def get_2D_peaks(arr2D, plot=False, amp_min=DEFAULT_AMP_MIN):
    struct = generate_binary_structure(2, 1)
    neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)

    # find local maxima using our fliter shape
    local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D

    background = (arr2D == 0)

    eroded_background = binary_erosion(background, structure=neighborhood,
                                       border_value=1)

    # Boolean mask of arr2D with True at peaks
    detected_peaks = local_max - eroded_background

    # extract peaks
    amps = arr2D[detected_peaks]
    j, i = np.where(detected_peaks)

    # filter peaks
    amps = amps.flatten()
    peaks = zip(i, j, amps)
    peaks_filtered = [x for x in peaks if x[2] > amp_min]  # freq, time, amp

    # get indices for frequency and time
    frequency_idx = [x[1] for x in peaks_filtered]
    time_idx = [x[0] for x in peaks_filtered]

    return zip(frequency_idx, time_idx)
开发者ID:sa-matiny,项目名称:Audio-Fingerprinting,代码行数:29,代码来源:fingerprint1.py


示例3: plotPeaks

def plotPeaks(arr2D, amp_min=DEFAULT_AMP_MIN):
	# http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.morphology.iterate_structure.html#scipy.ndimage.morphology.iterate_structure
	struct = generate_binary_structure(2, 1)
	neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)

	# find local maxima using our fliter shape
	local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D
	background = (arr2D == 0)
	eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

	# Boolean mask of arr2D with True at peaks
	detected_peaks = local_max - eroded_background

	# extract peaks
	amps = arr2D[detected_peaks]
	j, i = np.where(detected_peaks)

	# filter peaks
	amps = amps.flatten()
	peaks = zip(i, j, amps)
	peaks_filtered = [x for x in peaks if x[2] > amp_min]  # freq, time, amp

	# get indices for frequency and time
	frequency_idx = [x[1] for x in peaks_filtered]
	time_idx = [x[0] for x in peaks_filtered]

	# scatter of the peaks
	fig, ax = plt.subplots()
	ax.imshow(arr2D)
	ax.scatter(time_idx, frequency_idx)
	ax.set_xlabel('Time')
	ax.set_ylabel('Frequency')
	ax.set_title("Spectrogram")
	plt.gca().invert_yaxis()
	plt.show()
开发者ID:chris-wood,项目名称:MusicPrint,代码行数:35,代码来源:main.py


示例4: get_2D_peaks

def get_2D_peaks(arr2D, plot=False, amp_min=DEFAULT_AMP_MIN):
    struct = generate_binary_structure(2, 1)
    neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)

    local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D
    background = arr2D == 0
    eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

    detected_peaks = local_max - eroded_background

    amps = arr2D[detected_peaks]
    j, i = np.where(detected_peaks)

    amps = amps.flatten()
    peaks = zip(i, j, amps)
    peaks_filtered = [x for x in peaks if x[2] > amp_min]  # freq, time, amp

    frequency_idx = [x[1] for x in peaks_filtered]
    time_idx = [x[0] for x in peaks_filtered]

    if plot:
        # scatter of the peaks
        fig, ax = plt.subplots()
        ax.imshow(arr2D)
        ax.scatter(time_idx, frequency_idx)
        ax.set_xlabel("Time")
        ax.set_ylabel("Frequency")
        ax.set_title("Spectrogram")
        plt.gca().invert_yaxis()
        plt.show()

    return zip(frequency_idx, time_idx)
开发者ID:erynet,项目名称:IMHMv2,代码行数:32,代码来源:recognizer.py


示例5: __surface_distances

def __surface_distances(input1, input2, voxelspacing=None, connectivity=1):
    """
    The distances between the surface voxel of binary objects in input1 and their
    nearest partner surface voxel of a binary object in input2.
    """
    input1 = numpy.atleast_1d(input1.astype(numpy.bool))
    input2 = numpy.atleast_1d(input2.astype(numpy.bool))
    if voxelspacing is not None:
        voxelspacing = _ni_support._normalize_sequence(voxelspacing, input1.ndim)
        voxelspacing = numpy.asarray(voxelspacing, dtype=numpy.float64)
        if not voxelspacing.flags.contiguous:
            voxelspacing = voxelspacing.copy()
            
    # binary structure
    footprint = generate_binary_structure(input1.ndim, connectivity)
            
    # extract only 1-pixel border line of objects
    input1_border = input1 - binary_erosion(input1, structure=footprint, iterations=1)
    input2_border = input2 - binary_erosion(input2, structure=footprint, iterations=1)
    
    # compute average surface distance        
    # Note: scipys distance transform is calculated only inside the borders of the
    #       foreground objects, therefore the input has to be reversed
    dt = distance_transform_edt(~input2_border, sampling=voxelspacing)
    sds = dt[input1_border]
    
    return sds    
开发者ID:kleinfeld,项目名称:medpy,代码行数:27,代码来源:binary.py


示例6: detect_peaks

def detect_peaks(image):
 """
 from: http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array
 Takes an image and detect the peaks usingthe local maximum filter.
 Returns a boolean mask of the peaks (i.e. 1 when
 the pixel's value is the neighborhood maximum, 0 otherwise)
 """

 # define an 8-connected neighborhood
 neighborhood = generate_binary_structure(2,2)

 #apply the local maximum filter; all pixel of maximal value 
 #in their neighborhood are set to 1
 local_max = maximum_filter(image, footprint=neighborhood)==image
 #local_max is a mask that contains the peaks we are 
 #looking for, but also the background.
 #In order to isolate the peaks we must remove the background from the mask.

 #we create the mask of the background
 background = (image==0)

 #a little technicality: we must erode the background in order to 
 #successfully subtract it form local_max, otherwise a line will 
 #appear along the background border (artifact of the local maximum filter)
 eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

 #we obtain the final mask, containing only peaks, 
 #by removing the background from the local_max mask
 detected_peaks = local_max - eroded_background

 return detected_peaks
开发者ID:jgabriellima,项目名称:SOM,代码行数:31,代码来源:SOMTools.py


示例7: erodeDilate

    def erodeDilate(self, img, method=None):
        """
        Use morphological operators to erode or dilate the ridge structure.
        Dilate uses a recursive call to first dilate then erode.  Dilation
        alone produces ridge structures that are too thick to look
        authentic. Recursive call introduces random spurious minutiae when
        some valley structures are bridged.
        """
        img = np.array(img)
        if not method:
            method = random.choice(('erode', 'dilate', 'none'))
        inkIndex = np.where(img < 250)
        imgBin = np.zeros(np.shape(img))
        imgBin[inkIndex] = 1
        
        strel = morphology.generate_binary_structure(2,2)
        if method == 'erode':
            imgBin = morphology.binary_erosion(imgBin, strel)
        elif method == 'dilate':
            imgBin = morphology.binary_dilation(imgBin, strel)
        else:
            return img

        inkIndex = np.where(imgBin == 1)
        returnImg = 255*np.ones(np.shape(img))
        returnImg[inkIndex] = 0
        
        # Recursive call to erode after dilation to give more authentic
        # appearance.  Erode after dilate introduces spurious minutiae
        # but does not make the ridge structure too thick
        if method == 'dilate':
            self.erodeDilate(returnImg, method='erode')
        
        return returnImg
开发者ID:BTBurke,项目名称:synfinger,代码行数:34,代码来源:synfingerpress.py


示例8: getSaddlePoints

def getSaddlePoints(matrix, gaussian_filter_sigma=0., low=None, high=None):
    if low == None:
        low = matrix.min()
    if high == None:
        high = matrix.max()
    matrix = expandMatrix(matrix)
    neighborhood = morphology.generate_binary_structure(len(matrix.shape),2)
    # apply the local minimum filter; all locations of minimum value
    # in their neighborhood are set to 1
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.filters.html#minimum_filter
    matrix = filters.minimum_filter(matrix, footprint=neighborhood)
    matrix = condenseMatrix(matrix)
    outPath, clusterPathMat, grad = minPath(matrix)
    flood = numpy.asarray(outPath)
    potential = []
    for e in flood:
        i,j = e
        potential.append(matrix[i,j])
    potential = numpy.asarray(potential)
    potential = scipy.ndimage.filters.gaussian_filter(potential, gaussian_filter_sigma)
    derivative = lambda x: numpy.array(zip(-x,x[1:])).sum(axis=1)
    signproduct = lambda x: numpy.array(zip(x,x[1:])).prod(axis=1)
    potential_prime = derivative(potential)
    signproducts = numpy.sign(signproduct(potential_prime))
    extrema = flood[2:][numpy.where(signproducts<0)[0],:]
    bassinlimits = derivative(signproducts)
    saddlePoints = numpy.asarray(outPath[3:])[bassinlimits==-2]
    saddlePointValues = numpy.asarray(map(lambda x: matrix[x[0],x[1]], saddlePoints))
    saddlePoints = saddlePoints[numpy.logical_and(saddlePointValues>=low, saddlePointValues<=high),:]
    return saddlePoints
开发者ID:jgabriellima,项目名称:SOM,代码行数:30,代码来源:SOMTools.py


示例9: detect_local_maxima

def detect_local_maxima(vol):
    """
    Takes a 3D volume and detects the peaks using the local maximum filter.
    Returns a boolean mask of the peaks (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """
    # define a 26-connected neighborhood
    neighborhood = morphology.generate_binary_structure(3,3) # first is dimension, next is relative connectivity

    # apply the local maximum filter; all locations of maximum value 
    # in their neighborhood are set to 1
    local_max = (filters.maximum_filter(vol, footprint=neighborhood)==vol)

    # Remove background
    local_max[vol==0] = 0

    # Find endpoint indici
    [xOrig,yOrig,zOrig] = np.shape(vol)
    x = []
    y = []
    z = []
    for i in range(0,xOrig):
        for j in range(0,yOrig):
            for k in range(0,zOrig):
                if local_max[i,j,k] > 0:
                    x.append(i)
                    y.append(j)
                    z.append(k)

    return x, y, z
开发者ID:TLKline,项目名称:poreture,代码行数:30,代码来源:extract_centerline.py


示例10: incorporate_cells

def incorporate_cells(binary_image):    
    # invert input binary image
    inv_image = np.invert(binary_image)
    
    # matrix for binary_dilation
    struct = generate_binary_structure(2, 1)

    # do bunary dilation until the colony number even out
    plate_bin_dil = binary_dilation(inv_image, structure=struct)
    plate_dil_labels = label(plate_bin_dil)
    labels_number = len(np.unique(plate_dil_labels))  # initial number of colonies
    new_labels_number = labels_number - 1  # starting value
    cycle_number = 0  # starting value for dilation cycles
    while True:
        cycle_number += 1
        if cycle_number >= 30:
            break  # defence against infinite cycling
        else:
            if new_labels_number >= labels_number:
                break   # further dilation is useless (in theory)
            else:
                labels_number = new_labels_number
                plate_bin_dil = binary_dilation(plate_bin_dil, structure=struct)
                plate_dil_labels = label(plate_bin_dil)
                new_labels_number = len(np.unique(plate_dil_labels))
                
    return plate_bin_dil
开发者ID:varnivey,项目名称:hakoton_images,代码行数:27,代码来源:find_colonies.py


示例11: find_local_maxima

def find_local_maxima(arr):
    """
    Find local maxima in a multidimensional array `arr`.
    
    Parameters
    ----------
    arr : np.ndarray
        The array to find maxima in
    
    Returns
    -------
    indices : tuple of np.ndarray
        The indices of local maxima in `arr`
    """
    
    # http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710
    
    # neighborhood is simply a 3x3x3 array of True
    neighborhood = morphology.generate_binary_structure(len(arr.shape), 2)
    local_max = ( filters.maximum_filter(arr, footprint=neighborhood) == arr )
    
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#binary_erosion
    background = ( arr == 0 )
    eroded_background = morphology.binary_erosion(background,
                                                  structure=neighborhood,
                                                  border_value=1)
        
    # we obtain the final mask, containing only peaks, 
    # by removing the background from the local_min mask
    detected_max = local_max ^ eroded_background # ^ = XOR
    
    return np.where(detected_max)
开发者ID:tjlane,项目名称:thor,代码行数:32,代码来源:math2.py


示例12: mkoutersurf

def mkoutersurf(image, radius, outfile):
    #radius information is currently ignored
    #it is a little tougher to deal with the morphology in python

    fill = nib.load( image )
    filld = fill.get_data()
    filld[filld==1] = 255

    gaussian = np.ones((2,2))*.25

    image_f = np.zeros((256,256,256))

    for slice in xrange(256):
        temp = filld[:,:,slice]
        image_f[:,:,slice] = convolve(temp, gaussian, 'same')

    image2 = np.zeros((256,256,256))
    image2[np.where(image_f <= 25)] = 0
    image2[np.where(image_f > 25)] = 255

    strel15 = generate_binary_structure(3, 1)

    BW2 = grey_closing(image2, structure=strel15)
    thresh = np.max(BW2)/2
    BW2[np.where(BW2 <= thresh)] = 0
    BW2[np.where(BW2 > thresh)] = 255

    v, f = marching_cubes(BW2, 100)

    v2 = np.transpose(
             np.vstack( ( 128 - v[:,0],
                          v[:,2] - 128,
                          128 - v[:,1], )))
    
    write_surface(outfile, v2, f)
开发者ID:aestrivex,项目名称:ielu,代码行数:35,代码来源:mkoutersurf.py


示例13: __init__

 def __init__(self, geometric_model='affine', tps_grid_size=3, tps_reg_factor=0, h_matches=15, w_matches=15, use_conv_filter=False, dilation_filter=None, use_cuda=True, normalize_inlier_count=False, offset_factor=227/210):
     super(WeakInlierCount, self).__init__()
     self.normalize=normalize_inlier_count
     self.geometric_model = geometric_model
     self.geometricTnf = GeometricTnf(geometric_model=geometric_model,
                                      tps_grid_size=tps_grid_size,
                                      tps_reg_factor=tps_reg_factor,
                                      out_h=h_matches, out_w=w_matches,
                                      offset_factor = offset_factor,
                                      use_cuda=use_cuda)
     # define dilation filter
     if dilation_filter is None:
         dilation_filter = generate_binary_structure(2, 2)
     # define identity mask tensor (w,h are switched and will be permuted back later)
     mask_id = np.zeros((w_matches,h_matches,w_matches*h_matches))
     idx_list = list(range(0, mask_id.size, mask_id.shape[2]+1))
     mask_id.reshape((-1))[idx_list]=1
     mask_id = mask_id.swapaxes(0,1)
     # perform 2D dilation to each channel 
     if not use_conv_filter:
         if not (isinstance(dilation_filter,int) and dilation_filter==0):
             for i in range(mask_id.shape[2]):
                 mask_id[:,:,i] = binary_dilation(mask_id[:,:,i],structure=dilation_filter).astype(mask_id.dtype)
     else:
         for i in range(mask_id.shape[2]):
             flt=np.array([[1/16,1/8,1/16],
                              [1/8, 1/4, 1/8],
                              [1/16,1/8,1/16]])
             mask_id[:,:,i] = scipy.signal.convolve2d(mask_id[:,:,i], flt, mode='same', boundary='fill', fillvalue=0)
         
     # convert to PyTorch variable
     mask_id = Variable(torch.FloatTensor(mask_id).transpose(1,2).transpose(0,1).unsqueeze(0),requires_grad=False)
     self.mask_id = mask_id
     if use_cuda:
         self.mask_id = self.mask_id.cuda();
开发者ID:codealphago,项目名称:weakalign,代码行数:35,代码来源:loss.py


示例14: detect_local_maxima

def detect_local_maxima(image):
    neighborhood = generate_binary_structure(2,2)
    local_max = maximum_filter(image, footprint=neighborhood)==image
    background = (image==0)
    eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)
    detected_peaks = local_max - eroded_background
    return detected_peaks*256.0
开发者ID:linan7788626,项目名称:MyScriptsForTwinkles,代码行数:7,代码来源:local_peak_twinkles.py


示例15: get_2D_peaks

def get_2D_peaks(array2D):
    # This function is based on the function 'get_2D_peaks()' available at the URL below.
    # https://github.com/worldveil/dejavu/blob/master/dejavu/fingerprint.py
    # Copyright (c) 2013 Will Drevo, use permitted under the terms of the open-source MIT License.

    # Create a filter to extract peaks from the image data.
    struct = generate_binary_structure(2, 1)
    neighborhood = iterate_structure(struct, 25)

    # Find local maxima using our fliter shape. These are boolean arrays.
    local_maxima = maximum_filter(array2D, footprint=neighborhood) == array2D
    background = (array2D == 0)
    eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)

    # Boolean mask of array2D with True at peaks.
    detected_peaks = local_maxima - eroded_background

    # Extract peak amplitudes and locations.
    amps = array2D[detected_peaks]
    j, i = numpy.where(detected_peaks)

    # Filter peaks for those exceeding the minimum amplitude.
    amps = amps.flatten()
    peaks = zip(i, j, amps)
    peaks_filtered = [x for x in peaks if x[2] > AMP_MIN]

    # Get frequency and time at peaks.
    frequency_idx = [x[1] for x in peaks_filtered]
    time_idx = [x[0] for x in peaks_filtered]

    return (frequency_idx, time_idx)
开发者ID:djwbrown,项目名称:audio-signature-matching,代码行数:31,代码来源:audio_matching.py


示例16: detect_local_minima

def detect_local_minima(arr):
    # http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710
    """
    Takes an array and detects the troughs using the local maximum filter.
    Returns a boolean mask of the troughs (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """
    # define an connected neighborhood
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#generate_binary_structure
    neighborhood = morphology.generate_binary_structure(len(arr.shape),2)
    # apply the local minimum filter; all locations of minimum value 
    # in their neighborhood are set to 1
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.filters.html#minimum_filter
    local_min = (filters.minimum_filter(arr, footprint=neighborhood)==arr)
    # local_min is a mask that contains the peaks we are 
    # looking for, but also the background.
    # In order to isolate the peaks we must remove the background from the mask.
    # 
    # we create the mask of the background
    background = (arr==0)
    # 
    # a little technicality: we must erode the background in order to 
    # successfully subtract it from local_min, otherwise a line will 
    # appear along the background border (artifact of the local minimum filter)
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#binary_erosion
    eroded_background = morphology.binary_erosion(
        background, structure=neighborhood, border_value=1)
    # 
    # we obtain the final mask, containing only peaks, 
    # by removing the background from the local_min mask
    detected_minima = local_min - eroded_background
    return np.where(detected_minima)
开发者ID:JosephThomasParker,项目名称:BOUT-dev,代码行数:32,代码来源:local_min_max.py


示例17: fit_GLC_grid

def fit_GLC_grid( subjdata, z_limit=ZLIMIT ):
    #thesedata=subjdata
    dims = len(subjdata[0])-1
    
    bounds = [(.00001,50)] + [(-25,25) for _ in range( dims+1 ) ]
    optargs = ( subjdata, z_limit, None, True)
    
    xopt, fopt, grid, Jout = optimize.brute(func=negloglike_reduced 
                                              , ranges = bounds
                                              , args = optargs
                                              , Ns = 5
                                              , full_output=True
                                             )
    
    from scipy.ndimage.filters import minimum_filter
    from scipy.ndimage.morphology import generate_binary_structure
    
    neighborhood = generate_binary_structure( dims+2, dims+2 )
    local_mins = minimum_filter( Jout, footprint=neighborhood ) == Jout
    min_coords = np.array([ g[local_mins] for g in grid ]).T
    xoptglobal = xopt
    foptglobal = fopt
    for coords in min_coords:
        xopt, fopt, iter, im, sm = optimize.fmin(func=negloglike_reduced 
                                                  , x0 = coords
                                                  , args = optargs
                                                  , full_output=True
                                                 )
        if fopt < foptglobal:
            xoptglobal = xopt
            foptglobal = fopt
    
    return xoptglobal, foptglobal
开发者ID:johndpope,项目名称:General-Recognition-Theory,代码行数:33,代码来源:grt.py


示例18: __surface_distances

def __surface_distances(result, reference, voxelspacing=None, connectivity=1):
    """
    The distances between the surface voxel of binary objects in result and their
    nearest partner surface voxel of a binary object in reference.
    """
    result = numpy.atleast_1d(result.astype(numpy.bool))
    reference = numpy.atleast_1d(reference.astype(numpy.bool))
    if voxelspacing is not None:
        voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)
        voxelspacing = numpy.asarray(voxelspacing, dtype=numpy.float64)
        if not voxelspacing.flags.contiguous:
            voxelspacing = voxelspacing.copy()
            
    # binary structure
    footprint = generate_binary_structure(result.ndim, connectivity)
    
    # test for emptiness
    if 0 == numpy.count_nonzero(result): 
        raise RuntimeError('The first supplied array does not contain any binary object.')
    if 0 == numpy.count_nonzero(reference): 
        raise RuntimeError('The second supplied array does not contain any binary object.')    
            
    # extract only 1-pixel border line of objects
    result_border = result - binary_erosion(result, structure=footprint, iterations=1)
    reference_border = reference - binary_erosion(reference, structure=footprint, iterations=1)
    
    # compute average surface distance        
    # Note: scipys distance transform is calculated only inside the borders of the
    #       foreground objects, therefore the input has to be reversed
    dt = distance_transform_edt(~reference_border, sampling=voxelspacing)
    sds = dt[result_border]
    
    return sds
开发者ID:potis,项目名称:medpy,代码行数:33,代码来源:binary.py


示例19: snapshot_shaded_area

def snapshot_shaded_area(file_name):
    """
    Return an array of shaded cloud areas for a 3D model snapshot.
        
    Parameters
    ----------
    file_name : netCDF file name
        Data has dimensions float x(x), float y(y) and float z(z) and the field
        has been conditionally sampled for condensed area in variable int
        condensed(z, y, x).
      
    Return
    ------
    numpy.array
        Array of shaded cloud areas in units of grid cell.    
    """
    
    # Read netCDF dataset
    data = Dataset(file_name)
    condensed = data.variables['condensed'][...]
    
    # Determine shaded area mask (logical or along vertical axis)
    shaded_mask = np.any(condensed, axis=0)
    
    # Tag clouds; consider clouds connected even if they touch diagonally
    s = morphology.generate_binary_structure(2, 2)
    clouds, n = measurements.label(shaded_mask, s)
    
    # Count number of grid cells in each cloud; remove cloud free area
    cloud_areas = np.bincount(clouds.flatten().astype(int))[1:]
    
    return cloud_areas
开发者ID:vladpopa,项目名称:ent_analysis,代码行数:32,代码来源:shaded_area.py


示例20: detect_peaks

def detect_peaks(image):
    """
    http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array

    Takes an image and detect the peaks using the local maximum filter.
    Returns a boolean mask of the peaks (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """
    from scipy.ndimage.filters import maximum_filter
    from scipy.ndimage.morphology import generate_binary_structure, binary_erosion

    # define an 8-connected neighborhood
    neighborhood = generate_binary_structure(2,2)

    #apply the local maximum filter; all pixel of maximal value 
    #in their neighborhood are set to 1
    local_max = maximum_filter(image, footprint=neighborhood)==image
    background = (image==0)

    #a little technicality: we must erode the background in order to 
    #successfully subtract it form local_max, otherwise a line will 
    #appear along the background border (artifact of the local maximum filter)
    eroded_background = binary_erosion(background, structure=neighborhood, 
                                       border_value=1)
    detected_peaks = local_max - eroded_background
    peaks = np.array(np.where(detected_peaks)).T

    return peaks
开发者ID:theandygross,项目名称:Luc,代码行数:28,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python morphology.iterate_structure函数代码示例发布时间:2022-05-27
下一篇:
Python morphology.distance_transform_edt函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap