本文整理汇总了Python中scipy.ndimage.morphology.generate_binary_structure方法的典型用法代码示例。如果您正苦于以下问题:Python morphology.generate_binary_structure方法的具体用法?Python morphology.generate_binary_structure怎么用?Python morphology.generate_binary_structure使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.ndimage.morphology
的用法示例。
在下文中一共展示了morphology.generate_binary_structure方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simple_mask
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def simple_mask(self, bimg):
'''
Make soma binary mask with the original
binary image and its radius and position
'''
# Make a ball like mask with 2 X somaradius
ballvolume = np.zeros(bimg.shape)
ballvolume[self.centroid[0], self.centroid[1], self.centroid[2]] = 1
stt = generate_binary_structure(3, 1)
for i in range(math.ceil(self.radius * 2.5)):
ballvolume = binary_dilation(ballvolume, structure=stt)
# Make the soma mask with the intersection
# between the ball area and the original binary
self.mask = np.logical_and(ballvolume, bimg)
# Shift the centroid according to the cropped region
示例2: findpeaks
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def findpeaks(image, thresh):
"""
Return positions of all peaks in image above threshold thresh
Based on `"detect_peaks" Stack Overflow discussion <https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710>`_
:param image: array of values to search
:param thresh: threshold for peaks
:type image: numpy.ndarray
:type thresh: float
:returns: index array (equivalent of where output)
"""
# define an 8-connected neighborhood
neighborhood = generate_binary_structure(2,2)
# find local maximum for each pixel
amax = maximum_filter(image, footprint=neighborhood)
w = numpy.where((image == amax) & (image >= thresh))
return w
示例3: process_mask
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def process_mask(mask):
convex_mask = np.copy(mask)
for i_layer in range(convex_mask.shape[0]):
mask1 = np.ascontiguousarray(mask[i_layer])
if np.sum(mask1)>0:
mask2 = convex_hull_image(mask1)
if np.sum(mask2)>1.5*np.sum(mask1):
mask2 = mask1
else:
mask2 = mask1
convex_mask[i_layer] = mask2
struct = generate_binary_structure(3,1)
dilatedMask = binary_dilation(convex_mask,structure=struct,iterations=10)
return dilatedMask
示例4: decouple_volumes
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def decouple_volumes(v1, v2, mode, se=None, iterations=1):
"""
mode : {inner-from-outer, outer-from-inner, neighbors}
inner-from-outer: this changes v1 by removing voxels
outer-from-inner: this changes v2 by adding voxels
neighbors: this changes v2 by removing voxels
"""
assert mode in ["inner-from-outer","outer-from-inner","neighbors"]
if isinstance(v1, str) and os.path.isfile(v1):
v1 = nib.load(v1)
assert isinstance(v1, nib.Nifti1Image) or isinstance(v1, nib.Nifti2Image)
d1 = v1.get_data()
if isinstance(v2, str) and os.path.isfile(v2):
v2 = nib.load(v2)
assert isinstance(v2, nib.Nifti1Image) or isinstance(v2, nib.Nifti2Image)
d2 = v2.get_data()
assert d1.ndim is d2.ndim
if se is None:
se = mrph.generate_binary_structure(d1.ndim,1)
if mode == "inner-from-outer":
# make v2/d2 the inner volume
d1, d2 = d2, d1
v1, v2 = v2, v1
d2 = d2 & mrph.binary_erosion(d1, se, iterations)
if mode == "outer-from-inner":
d2 = d2 | mrph.binary_dilation(d1, se, iterations)
if mode == "neighbors":
d2 = d2 & ~mrph.binary_dilation(d1, se, iterations)
d2 = nib.Nifti1Image(d2, v2.affine, header=v2.header)
d2.set_filename(v2.get_filename())
return d2
示例5: find_peaks
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def find_peaks(param, img):
'''
Given a (grayscale) image, find local maxima whose value is above a given threshold (param['thre1'])
Args:
param (dict):
img (ndarray): Input image (2d array) where we want to find peaks
Returns:
2d np.array containing the [x,y] coordinates of each peak foun in the image
'''
peaks_binary = (maximum_filter(img, footprint=generate_binary_structure(2, 1)) == img) * (img > param['thre1'])
# Note reverse ([::-1]): we return [[x y], [x y]...] instead of [[y x], [y x]...]
return np.array(np.nonzero(peaks_binary)[::-1]).T
示例6: __init__
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
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();
示例7: find_peaks
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def find_peaks(param, img):
"""
Given a (grayscale) image, find local maxima whose value is above a given
threshold (param['thre1'])
:param img: Input image (2d array) where we want to find peaks
:return: 2d np.array containing the [x,y] coordinates of each peak found
in the image
"""
peaks_binary = (maximum_filter(img, footprint=generate_binary_structure(
2, 1)) == img) * (img > param['thre1'])
# Note reverse ([::-1]): we return [[x y], [x y]...] instead of [[y x], [y
# x]...]
return np.array(np.nonzero(peaks_binary)[::-1]).T
示例8: local_maxima
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def local_maxima(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 maximum filter; all locations of maximal value
# in their neighborhood are set to 1
# http://www.scipy.org/doc/api_docs/SciPy.ndimage.filters.html#maximum_filter
local_max = (filters.maximum_filter(arr, footprint=neighborhood)==arr)
# 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 = (arr==arr.min()) # mxu: in the original version, was background = (arr==0)
#
# a little technicality: we must erode the background in order to
# successfully subtract it from local_max, otherwise a line will
# appear along the background border (artifact of the local maximum 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_max mask
#detected_maxima = local_max - eroded_backround # mxu: this is the old version, but the boolean minus operator is deprecated
detected_maxima = np.bitwise_and(local_max, np.bitwise_not(eroded_background)) # Material nonimplication, see http://en.wikipedia.org/wiki/Material_nonimplication
return np.where(detected_maxima)
示例9: mkoutersurf
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
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 range(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, _, _ = measure.marching_cubes_lewiner(BW2, 100)
v2 = np.transpose(
np.vstack( ( 128 - v[:,0],
v[:,2] - 128,
128 - v[:,1], )))
write_surface(outfile, v2, f)
示例10: detect
# 需要导入模块: from scipy.ndimage import morphology [as 别名]
# 或者: from scipy.ndimage.morphology import generate_binary_structure [as 别名]
def detect(self, image):
# 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 < self.min_th)
# 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 (xor operation)
detected_peaks = local_max ^ eroded_background
detected_peaks[image < self.min_th] = False
peaks = np.array(np.nonzero(detected_peaks)).T
if len(peaks) == 0:
return peaks, np.array([])
# nms
if len(peaks) == 1:
clusters = [0]
else:
clusters = fclusterdata(peaks, self.min_dist, criterion="distance")
peak_groups = {}
for ind_junc, ind_group in enumerate(clusters):
if ind_group not in peak_groups.keys():
peak_groups[ind_group] = []
peak_groups[ind_group].append(peaks[ind_junc])
peaks_nms = []
peaks_score = []
for peak_group in peak_groups.values():
values = [image[y, x] for y, x in peak_group]
ind_max = np.argmax(values)
peaks_nms.append(peak_group[int(ind_max)])
peaks_score.append(values[int(ind_max)])
return np.float32(np.array(peaks_nms)), np.float32(np.array(peaks_score))