Python scipy.ndimage.morphology.binary_fill_holes() Examples

The following are 5 code examples of scipy.ndimage.morphology.binary_fill_holes(). 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: freesurfer.py    From niworkflows with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def refine_aseg(aseg, ball_size=4):
    """
    Refine the ``aseg.mgz`` mask of Freesurfer.

    First step to reconcile ANTs' and FreeSurfer's brain masks.
    Here, the ``aseg.mgz`` mask from FreeSurfer is refined in two
    steps, using binary morphological operations:

      1. With a binary closing operation the sulci are included
         into the mask. This results in a smoother brain mask
         that does not exclude deep, wide sulci.

      2. Fill any holes (typically, there could be a hole next to
         the pineal gland and the corpora quadrigemina if the great
         cerebral brain is segmented out).

    """
    # Read aseg data
    bmask = aseg.copy()
    bmask[bmask > 0] = 1
    bmask = bmask.astype(np.uint8)

    # Morphological operations
    selem = sim.ball(ball_size)
    newmask = sim.binary_closing(bmask, selem)
    newmask = binary_fill_holes(newmask.astype(np.uint8), selem).astype(np.uint8)

    return newmask.astype(np.uint8) 
Example #2
Source File: postprocessing.py    From spinalcordtoolbox with MIT License 5 votes vote down vote up
def fill_holes_2d(z_slice):
    """
    Fill holes in the segmentation.
    :param z_slice: int 2d-array: Input 2D segmentation.
    :return: int 2d-array: Output segmentation with holes filled
    """
    assert z_slice.dtype == np.dtype('int')
    return binary_fill_holes(z_slice, structure=np.ones((3, 3))).astype(np.int) 
Example #3
Source File: fill_holes.py    From plantcv with MIT License 5 votes vote down vote up
def fill_holes(bin_img):
    """Flood fills holes in a binary mask

    Inputs:
    bin_img      = Binary image data

    Returns:
    filtered_img = image with objects filled

    :param bin_img: numpy.ndarray
    :return filtered_img: numpy.ndarray
    """
    params.device += 1

    # Make sure the image is binary
    if len(np.shape(bin_img)) != 2 or len(np.unique(bin_img)) != 2:
        fatal_error("Image is not binary")

    # Cast binary image to boolean
    bool_img = bin_img.astype(bool)

    # Flood fill holes
    bool_img = binary_fill_holes(bool_img)

    # Cast boolean image to binary and make a copy of the binary image for returning
    filtered_img = np.copy(bool_img.astype(np.uint8) * 255)

    if params.debug == 'print':
        print_image(filtered_img, os.path.join(params.debug_outdir, str(params.device) + '_fill_holes' + '.png'))
    elif params.debug == 'plot':
        plot_image(filtered_img, cmap='gray')

    return filtered_img 
Example #4
Source File: image_utils.py    From visualqc with Apache License 2.0 4 votes vote down vote up
def mask_image(input_img,
               update_factor=0.5,
               init_percentile=2,
               iterations_closing=5,
               return_inverse=False,
               out_dtype=None):
    """
    Estimates the foreground mask for a given image.
    Similar to 3dAutoMask from AFNI.


    iterations_closing : int
        Number of iterations of binary_closing to apply at the end.

    """

    prev_clip_level = np.percentile(input_img, init_percentile)
    while True:
        mask_img = input_img >= prev_clip_level
        cur_clip_level = update_factor * np.median(input_img[mask_img])
        if np.isclose(cur_clip_level, prev_clip_level, rtol=0.05):
            break
        else:
            prev_clip_level = cur_clip_level

    if len(input_img.shape) == 3:
        se = ndimage.generate_binary_structure(3, 6)
    elif len(input_img.shape) == 2:
        se = ndimage.generate_binary_structure(2, 4)
    else:
        raise ValueError('Image must be 2D or 3D')

    mask_img = binary_closing(mask_img, se, iterations=iterations_closing)
    mask_img = binary_fill_holes(mask_img, se)

    if return_inverse:
        mask_img = np.logical_not(mask_img)

    if out_dtype is not None:
        mask_img = mask_img.astype(out_dtype)

    return mask_img

# alias 
Example #5
Source File: nilearn.py    From niworkflows with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _run_interface(self, runtime):

        in_files = self.inputs.in_files

        if self.inputs.enhance_t2:
            in_files = [_enhance_t2_contrast(f, newpath=runtime.cwd) for f in in_files]

        masknii = compute_epi_mask(
            in_files,
            lower_cutoff=self.inputs.lower_cutoff,
            upper_cutoff=self.inputs.upper_cutoff,
            connected=self.inputs.connected,
            opening=self.inputs.opening,
            exclude_zeros=self.inputs.exclude_zeros,
            ensure_finite=self.inputs.ensure_finite,
            target_affine=self.inputs.target_affine,
            target_shape=self.inputs.target_shape,
        )

        if self.inputs.closing:
            closed = sim.binary_closing(
                np.asanyarray(masknii.dataobj).astype(np.uint8), sim.ball(1)
            ).astype(np.uint8)
            masknii = masknii.__class__(closed, masknii.affine, masknii.header)

        if self.inputs.fill_holes:
            filled = binary_fill_holes(
                np.asanyarray(masknii.dataobj).astype(np.uint8), sim.ball(6)
            ).astype(np.uint8)
            masknii = masknii.__class__(filled, masknii.affine, masknii.header)

        if self.inputs.no_sanitize:
            in_file = self.inputs.in_files
            if isinstance(in_file, list):
                in_file = in_file[0]
            nii = nb.load(in_file)
            qform, code = nii.get_qform(coded=True)
            masknii.set_qform(qform, int(code))
            sform, code = nii.get_sform(coded=True)
            masknii.set_sform(sform, int(code))

        self._results["out_mask"] = fname_presuffix(
            self.inputs.in_files[0], suffix="_mask", newpath=runtime.cwd
        )
        masknii.to_filename(self._results["out_mask"])
        return runtime