Python scipy.ndimage 模块,binary_erosion() 实例源码

我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用scipy.ndimage.binary_erosion()

项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def _run_interface(self, runtime):

        in_file = nb.load(self.inputs.in_file)
        wm_mask = nb.load(self.inputs.wm_mask).get_data()
        wm_mask[wm_mask < 0.9] = 0
        wm_mask[wm_mask > 0] = 1
        wm_mask = wm_mask.astype(np.uint8)

        if self.inputs.erodemsk:
            # Create a structural element to be used in an opening operation.
            struc = nd.generate_binary_structure(3, 2)
            # Perform an opening operation on the background data.
            wm_mask = nd.binary_erosion(wm_mask, structure=struc).astype(np.uint8)

        data = in_file.get_data()
        data *= 1000.0 / np.median(data[wm_mask > 0])

        out_file = fname_presuffix(self.inputs.in_file,
                                   suffix='_harmonized', newpath='.')
        in_file.__class__(data, in_file.affine, in_file.header).to_filename(
            out_file)

        self._results['out_file'] = out_file

        return runtime
项目:diluvian    作者:aschampion    | 项目源码 | 文件源码
def __next__(self):
        while True:
            subv = six.next(self.subvolume_generator)

            subv.label_mask = ndimage.binary_erosion(subv.label_mask, structure=self.sel, border_value=1)

            if subv.has_seed_in_mask():
                return subv
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def eroded(self, structure=None, connectivity=2, iterations=100):

        """
        This function ...
        :param structure:
        :param connectivity:
        :param iterations:
        :return:
        """

        # Define the structure for the expansion
        if structure is None: structure = ndimage.generate_binary_structure(2, connectivity=connectivity)

        try:
            # Make the new mask, made from 100 iterations with the structure array
            data = ndimage.binary_erosion(self, structure, iterations)
        except:
            #print(self)
            #print(structure)
            data = np.zeros((self.ysize,self.xsize), dtype=bool)

        # Reassign this object
        #data, name=None, description=None
        return Mask(data, name=self.name, description=self.description)

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def eroded(self, structure=None, connectivity=2, iterations=100):

        """
        This function ...
        :param structure:
        :param connectivity:
        :param iterations:
        :return:
        """

        # Define the structure for the expansion
        if structure is None: structure = ndimage.generate_binary_structure(2, connectivity=connectivity)

        try:
            # Make the new mask, made from 100 iterations with the structure array
            data = ndimage.binary_erosion(self, structure, iterations)
        except:
            #print(self)
            #print(structure)
            data = np.zeros((self.ysize,self.xsize), dtype=bool)

        # Reassign this object
        #data, name=None, description=None
        return Mask(data, name=self.name, description=self.description)

    # -----------------------------------------------------------------
项目:segmentation    作者:zengyu714    | 项目源码 | 文件源码
def weights_map(ys):
    """Compute corresponding weight map when use cross entropy loss.

    Argument:
        ys: [depth, height, width]

    Return:
        weights_map: [depth, height, width]
    """
    weights = ys.astype(np.float64)

    # Balance class frequencies.
    cls_ratio = np.sum(1 - ys) / np.sum(ys)
    weights *= cls_ratio

    # Generate boundaries using morphological operation.
    se = generate_binary_structure(3, 1)
    bigger = binary_dilation(ys, structure=se).astype(np.float64)
    small = binary_erosion(ys, structure=se).astype(np.float64)
    edge = bigger - small

    # Balance edge frequencies.
    edge_ratio = np.sum(bigger) / np.sum(edge)
    edge *= np.exp(edge_ratio) * 10

    # `weights` should > 0
    # `targets * -log(sigmoid(logits)) * pos_weight + (1 - targets) * -log(1 - sigmoid(logits))`
    return weights + edge + 1
项目:DeepCellSeg    作者:arbellea    | 项目源码 | 文件源码
def plot_segmentation(I,GT,Seg, fig=None):

    I = np.squeeze(I)
    GT = np.squeeze(GT)
    Seg = np.squeeze(Seg)

    GTC = np.logical_and(GT, np.logical_not(ndimage.binary_erosion(GT)))
    SegC = np.logical_and(Seg, np.logical_not(ndimage.binary_erosion(Seg)))

    plt.figure(fig)
    maskedGT = np.ma.masked_where(GTC == 0, GTC)
    maskedSeg = np.ma.masked_where(SegC == 0, SegC)
    plt.imshow(I, cmap=cm.gray)
    plt.imshow(maskedGT, cmap=cm.jet, interpolation='none')
    plt.imshow(maskedSeg*100, cmap=cm.hsv, interpolation='none')
项目:imagepy    作者:Image-Py    | 项目源码 | 文件源码
def run(self, ips, snap, img, para = None):
        strc = np.ones((para['h'], para['w']), dtype=np.uint8)
        ndimg.binary_erosion(snap, strc, output=img)
        img *= 255
项目:imagepy    作者:Image-Py    | 项目源码 | 文件源码
def run(self, ips, imgs, para = None):
        strc = np.ones((para['r'], para['r'], para['r']), dtype=np.uint8)
        imgs[:] = ndimg.binary_erosion(imgs, strc)
        imgs *= 255
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def generate_synthetic_data():
    """ Synthetic binary data """
    rs = np.random.RandomState(0)
    n_pts = 36.
    x, y = np.ogrid[0:l, 0:l]
    mask_outer = (x - l / 2) ** 2 + (y - l / 2) ** 2 < (l / 2) ** 2
    mask = np.zeros((l, l))
    points = l * rs.rand(2, n_pts)
    mask[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
    mask = ndimage.gaussian_filter(mask, sigma=l / n_pts)
    res = np.logical_and(mask > mask.mean(), mask_outer)
    return res - ndimage.binary_erosion(res)


# Generate synthetic images, and projections
项目:tissue_analysis    作者:VirtualPlants    | 项目源码 | 文件源码
def cells_voxel_layer(self, labels, region_boundingbox = False, single_frame = False):
        """
        This function extract the first layer of voxel surrounding a cell defined by `label`
        Args:
           label: (int|list) - cell-label for which we want to extract the first layer of voxel;
           region_boundingbox: (bool) - if True, consider a boundingbox surrounding all labels, instead of each label alone.
           single_frame: (bool) - if True, return only one array with all voxels position defining cell walls.
        :Output:
         returns a binary image: 1 where the cell-label of interest is, 0 elsewhere
        """
        if isinstance(labels,int):
            labels = [labels]
        if single_frame:
            region_boundingbox=True

        if not isinstance(region_boundingbox,bool):
            if sum([isinstance(s,slice) for s in region_boundingbox])==3:
                bbox = region_boundingbox
            else:
                print "TypeError: Wong type for 'region_boundingbox', should either be bool or la tuple of slices"
                return None
        elif isinstance(region_boundingbox,bool) and region_boundingbox:
            bbox = self.region_boundingbox(labels)
        else:
            bboxes = self.boundingbox(labels, real=False)

        # Generate the smaller eroding structure possible:
        struct = nd.generate_binary_structure(3, 2)
        if single_frame:
            vox_layer = np.zeros_like(self.image[bbox], dtype=int)
        else:
            vox_layer = {}
        for clabel in labels:
            if region_boundingbox:
                bbox_im = self.image[bbox]
            else:
                bbox_im = self.image[bboxes[clabel]]
            # Creating a mask (1 where the cell-label of interest is, 0 elsewhere):
            mask_bbox_im = (bbox_im == clabel)
            # Erode the cell using the structure:
            eroded_mask_bbox_im = nd.binary_erosion(mask_bbox_im, structure=struct)
            if single_frame:
                vox_layer += np.array(mask_bbox_im - eroded_mask_bbox_im, dtype=int)
            else:
                vox_layer[clabel] = np.array(mask_bbox_im - eroded_mask_bbox_im, dtype=int)

        if len(labels)==1:
            return vox_layer[clabel]
        else:
            return vox_layer
项目:wradlib    作者:wradlib    | 项目源码 | 文件源码
def filter_gabella_b(img, thrs=0.):
    r"""Second part of the Gabella filter comparing area to circumference of
    contiguous echo regions.

    Parameters
    ----------
    img : array_like
    thrs : float
        Threshold below which the field values will be considered as no rain

    Returns
    -------
    output : array_like
        contains in each pixel the ratio between area and circumference of the
        meteorological echo it is assigned to or 0 for non precipitation
        pixels.

    See Also
    --------
    filter_gabella_a : the first part of the filter
    filter_gabella : the complete filter

    Examples
    --------

    See :ref:`notebooks/classify/wradlib_clutter_gabella_example.ipynb`.

    """
    conn = np.ones((3, 3))
    # create binary image of the rainfall field
    binimg = img > thrs
    # label objects (individual rain cells, so to say)
    labelimg, nlabels = ndi.label(binimg, conn)
    # erode the image, thus removing the 'boundary pixels'
    binimg_erode = ndi.binary_erosion(binimg, structure=conn)
    # determine the size of each object
    labelhist, edges = np.histogram(labelimg,
                                    bins=nlabels + 1,
                                    range=(-0.5, labelimg.max() + 0.5))
    # determine the size of the eroded objects
    erodelabelhist, edges = np.histogram(np.where(binimg_erode, labelimg, 0),
                                         bins=nlabels + 1,
                                         range=(-0.5, labelimg.max() + 0.5))
    # the boundary is the difference between these two
    boundarypixels = labelhist - erodelabelhist
    # now get the ratio between object size and boundary
    ratio = labelhist.astype(np.float32) / boundarypixels
    # assign it back to the objects
    # first get the indices
    indices = np.digitize(labelimg.ravel(), edges) - 1
    # then produce a new field with the ratios in the right place
    result = ratio[indices.ravel()].reshape(img.shape)

    return result