Python scipy.ndimage.morphology.generate_binary_structure() Examples
The following are 14
code examples of scipy.ndimage.morphology.generate_binary_structure().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
scipy.ndimage.morphology
, or try the search function
.
Example #1
Source File: soma.py From rivuletpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #2
Source File: starmatch_hist.py From drizzlepac with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #3
Source File: prepare.py From DeepLung with GNU General Public License v3.0 | 5 votes |
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
Example #4
Source File: hmutils.py From simnibs with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: util.py From Qualia2.0 with MIT License | 5 votes |
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
Example #6
Source File: loss.py From weakalign with MIT License | 5 votes |
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();
Example #7
Source File: post.py From EverybodyDanceNow_reproduce_pytorch with MIT License | 5 votes |
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
Example #8
Source File: local_extrema.py From aitom with GNU General Public License v3.0 | 5 votes |
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)
Example #9
Source File: prepare.py From lung_nodule_detector with MIT License | 5 votes |
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
Example #10
Source File: post.py From part-affinity with MIT License | 5 votes |
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
Example #11
Source File: mkoutersurf.py From mmvt with GNU General Public License v3.0 | 5 votes |
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)
Example #12
Source File: prepare.py From DeepSEED-3D-ConvNets-for-Pulmonary-Nodule-Detection with MIT License | 5 votes |
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
Example #13
Source File: prepareLIDC.py From DeepSEED-3D-ConvNets-for-Pulmonary-Nodule-Detection with MIT License | 5 votes |
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
Example #14
Source File: common.py From PPGNet with MIT License | 4 votes |
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))