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

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

项目:CancerImageAnalyzer2    作者:byeungchun    | 项目源码 | 文件源码
def findRemSmObjValue(_biImageFile="E:/workspace/jinyoung/CancerImageAnalyzer/img/ppimg1601101508/thimg1601101511/BF_position020100_time0001hVal0.4thVal0.9.png"):
    _remSmObjOutputPath = '/remSmObjImg'+datetime.datetime.today().strftime('%y%m%d%H%M')+'/'
    remSmObjImageFileName = os.path.basename(_biImageFile)
    biImageFilePath = os.path.dirname(_biImageFile)

    reSmObjImageFilePath = biImageFilePath + _remSmObjOutputPath

    biImg = imread(_biImageFile)
    biImgRsize = biImg.shape[0] * 0.1
    biImgCsize = biImg.shape[1] * 0.1
    biImg = biImg[biImgRsize:-biImgRsize, biImgCsize:-biImgCsize]
    biImg = ndimage.binary_fill_holes(biImg)
    for smObjVal in np.arange(0,100000,10000):
        filledImg = cia.removeSmallObject(biImg, minSize=smObjVal)
        if not os.path.exists(reSmObjImageFilePath):
            os.mkdir(reSmObjImageFilePath)
        biImageFileName = remSmObjImageFileName[:remSmObjImageFileName.rfind('.')]+'smObjVal'+str(smObjVal)+'.png'
        imsave(reSmObjImageFilePath+biImageFileName, filledImg)



#findHvalue()
项目:pyAFQ    作者:yeatmanlab    | 项目源码 | 文件源码
def patch_up_roi(roi):
    """
    After being non-linearly transformed, ROIs tend to have holes in them.
    We perform a couple of computational geometry operations on the ROI to
    fix that up.

    Parameters
    ----------
    roi : 3D binary array
        The ROI after it has been transformed

    Returns
    -------
    ROI after dilation and hole-filling
    """
    return ndim.binary_fill_holes(ndim.binary_dilation(roi).astype(int))
项目:TC-Lung_nodules_detection    作者:Shicoder    | 项目源码 | 文件源码
def get_segmented_lungs(im, plot=False):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is    to keep nodules attached to the lung wall.
    selem = disk(10) # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
项目:CancerImageAnalyzer2    作者:byeungchun    | 项目源码 | 文件源码
def convertBinaryImage(preprocessingImg, threshold=0.9):
    markers = np.zeros_like(preprocessingImg)
    markers[preprocessingImg < threshold] = 1
    filledImg = ndimage.binary_fill_holes(markers)
    return filledImg
项目:pyem    作者:asarnow    | 项目源码 | 文件源码
def main(args):
    if args.threshold is None:
        print("Please provide a binarization threshold")
        return 1
    data, hdr = read(args.input, inc_header=True)
    mask = data >= args.threshold
    if args.minvol is not None:
        mask = binary_volume_opening(mask, args.minvol)
    if args.fill:
        mask = binary_fill_holes(mask)
    if args.extend is not None and args.extend > 0:
        if args.relion:
            se = binary_sphere(args.extend, False)
            mask = binary_dilation(mask, structure=se, iterations=1)
        else:
            dt = distance_transform_edt(~mask)
            mask = mask | (dt <= args.edge_width)
    if args.close:
        se = binary_sphere(args.extend, False)
        mask = binary_closing(mask, structure=se, iterations=1)
    final = mask.astype(np.single)
    if args.edge_width is not None:
        dt = distance_transform_edt(~mask)  # Compute *outward* distance transform of mask.
        idx = (dt <= args.edge_width) & (dt > 0)  # Identify edge points by distance from mask.
        x = np.arange(1, args.edge_width + 1)  # Domain of the edge profile.
        if "sin" in args.edge_profile:
            y = np.sin(np.linspace(np.pi/2, 0, args.edge_width + 1))  # Range of the edge profile.
        f = interp1d(x, y[1:])
        final[idx] = f(dt[idx])  # Insert edge heights interpolated at distance transform values.
    write(args.output, final, psz=hdr["xlen"] / hdr["nx"])
    return 0
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
def __init__(self, raw_image, putative_nuclei_image, putative_somata_image, centers_of_mass=None):
        super(DonutCells, self).__init__(putative_nuclei_image, raw_image, centers_of_mass)
        self.putative_somata_image = putative_somata_image
        self.putative_nuclei_image = ndimage.binary_fill_holes(self.putative_nuclei_image)
        self.watershed_image = np.logical_or(self.putative_nuclei_image, self.putative_somata_image)
        self.segmentation_labels = calculate_distance(self.centers_of_mass, self.watershed_image)
        self.labelled_nuclei = calculate_distance(self.centers_of_mass, self.putative_nuclei_image)
        self.roi_masks = create_roi_masks(self.centers_of_mass, self.putative_nuclei_image, self.putative_somata_image)
项目:imagepy    作者:Image-Py    | 项目源码 | 文件源码
def run(self, ips, snap, img, para = None):
        ndimg.binary_fill_holes(snap, output=img)
        img *= 255
项目:imagepy    作者:Image-Py    | 项目源码 | 文件源码
def run(self, ips, imgs, para = None):
        imgs[:] = ndimg.binary_fill_holes(imgs)
        imgs *= 255
项目:kaggle_ndsb2017    作者:juliandewit    | 项目源码 | 文件源码
def get_segmented_lungs(im, plot=False):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is    to keep nodules attached to the lung wall.
    selem = disk(10) # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
项目:sudokuextract    作者:hbldh    | 项目源码 | 文件源码
def iter_blob_extremes(image, n=5):
    original_shape = image.shape[::-1]
    if max(original_shape) < 2000:
        size = (500, 500)
        y_scale = original_shape[0] / 500
        x_scale = original_shape[1] / 500
    else:
        size = (1000, 1000)
        y_scale = original_shape[0] / 1000
        x_scale = original_shape[1] / 1000

    img = resize(image, size)
    bimg = gaussian_filter(img, sigma=1.0)
    bimg = threshold_adaptive(bimg, 20, offset=2/255)
    bimg = -bimg
    bimg = ndi.binary_fill_holes(bimg)
    label_image = label(bimg, background=False)
    label_image += 1

    regions = regionprops(label_image)
    regions.sort(key=attrgetter('area'), reverse=True)
    iter_n = 0

    for region in regions:
        try:
            iter_n += 1
            if iter_n > n:
                break

            # Skip small images
            if region.area < int(np.prod(size) * 0.05):
                continue
            coords = get_contours(add_border(label_image == region.label,
                                             size=label_image.shape,
                                             border_size=1,
                                             background_value=False))[0]
            coords = np.fliplr(coords)

            top_left = sorted(coords, key=lambda x: np.linalg.norm(np.array(x)))[0]
            top_right = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [img.shape[1], 0]))[0]
            bottom_left = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [0, img.shape[0]]))[0]
            bottom_right = sorted(coords, key=lambda x: np.linalg.norm(np.array(x) - [img.shape[1], img.shape[0]]))[0]
            scaled_extremes = [(int(x[0] * y_scale), int(x[1]*x_scale)) for x in (top_left, top_right, bottom_left, bottom_right)]

            yield scaled_extremes
        except Exception:
            pass
    raise SudokuExtractError("No suitable blob could be found.")
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def gradient_threshold(in_file, in_segm, thresh=1.0, out_file=None):
    """ Compute a threshold from the histogram of the magnitude gradient image """
    import os.path as op
    import numpy as np
    import nibabel as nb
    from scipy import ndimage as sim

    struc = sim.iterate_structure(sim.generate_binary_structure(3, 2), 2)

    if out_file is None:
        fname, ext = op.splitext(op.basename(in_file))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('{}_gradmask{}'.format(fname, ext))

    imnii = nb.load(in_file)

    hdr = imnii.get_header().copy()
    hdr.set_data_dtype(np.uint8)  # pylint: disable=no-member

    data = imnii.get_data().astype(np.float32)

    mask = np.zeros_like(data, dtype=np.uint8)  # pylint: disable=no-member
    mask[data > 15.] = 1

    segdata = nb.load(in_segm).get_data().astype(np.uint8)
    segdata[segdata > 0] = 1
    segdata = sim.binary_dilation(segdata, struc, iterations=2, border_value=1).astype(np.uint8)  # pylint: disable=no-member
    mask[segdata > 0] = 1

    mask = sim.binary_closing(mask, struc, iterations=2).astype(np.uint8)  # pylint: disable=no-member
    # Remove small objects
    label_im, nb_labels = sim.label(mask)
    artmsk = np.zeros_like(mask)
    if nb_labels > 2:
        sizes = sim.sum(mask, label_im, list(range(nb_labels + 1)))
        ordered = list(reversed(sorted(zip(sizes, list(range(nb_labels + 1))))))
        for _, label in ordered[2:]:
            mask[label_im == label] = 0
            artmsk[label_im == label] = 1

    mask = sim.binary_fill_holes(mask, struc).astype(np.uint8)  # pylint: disable=no-member

    nb.Nifti1Image(mask, imnii.get_affine(), hdr).to_filename(out_file)
    return out_file