本文整理汇总了Python中scipy.ndimage.morphology.generate_binary_structure函数的典型用法代码示例。如果您正苦于以下问题:Python generate_binary_structure函数的具体用法?Python generate_binary_structure怎么用?Python generate_binary_structure使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了generate_binary_structure函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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()
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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)
示例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)
示例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();
示例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
示例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)