Python skimage.morphology.binary_opening() Examples

The following are 9 code examples of skimage.morphology.binary_opening(). 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 skimage.morphology , or try the search function .
Example #1
Source File: BasicModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def finalProcessingSpur(s, params):
    logging.info(f"{s['filename']} - \tfinalProcessingSpur")
    disk_radius = int(params.get("disk_radius", "25"))
    selem = disk(disk_radius)
    mask = s["img_mask_use"]
    mask_opened = binary_opening(mask, selem)
    mask_spur = ~mask_opened & mask

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_spur.png", img_as_ubyte(mask_spur))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = mask_opened

    s.addToPrintList("spur_pixels",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail") 
Example #2
Source File: megafacade.py    From facade-segmentation with MIT License 5 votes vote down vote up
def extract_boxes_as_dictionaries(image, threshold=0.5, se=disk(3)):
    mask = image > threshold
    mask = binary_opening(mask, selem=se)
    try:
        props = regionprops(label(mask))
        def _tag(tlbr):
            t, l, b, r = tlbr
            return dict(top=int(t), left=int(l), bottom=int(b), right=int(r))
        result = [_tag(r.bbox) for r in props]
    except (ValueError, TypeError) as e:
        result = []
    return result 
Example #3
Source File: postprocessing.py    From open-solution-data-science-bowl-2018 with MIT License 5 votes vote down vote up
def clean_mask(m, c):
    # threshold
    m_thresh = threshold_otsu(m)
    c_thresh = threshold_otsu(c)
    m_b = m > m_thresh
    c_b = c > c_thresh

    # combine contours and masks and fill the cells
    m_ = np.where(m_b | c_b, 1, 0)
    m_ = ndi.binary_fill_holes(m_)

    # close what wasn't closed before
    area, radius = mean_blob_size(m_b)
    struct_size = int(1.25 * radius)
    struct_el = morph.disk(struct_size)
    m_padded = pad_mask(m_, pad=struct_size)
    m_padded = morph.binary_closing(m_padded, selem=struct_el)
    m_ = crop_mask(m_padded, crop=struct_size)

    # open to cut the real cells from the artifacts
    area, radius = mean_blob_size(m_b)
    struct_size = int(0.75 * radius)
    struct_el = morph.disk(struct_size)
    m_ = np.where(c_b & (~m_b), 0, m_)
    m_padded = pad_mask(m_, pad=struct_size)
    m_padded = morph.binary_opening(m_padded, selem=struct_el)
    m_ = crop_mask(m_padded, crop=struct_size)

    # join the connected cells with what we had at the beginning
    m_ = np.where(m_b | m_, 1, 0)
    m_ = ndi.binary_fill_holes(m_)

    # drop all the cells that weren't present at least in 25% of area in the initial mask
    m_ = drop_artifacts(m_, m_b, min_coverage=0.25)

    return m_ 
Example #4
Source File: freesurfer.py    From niworkflows with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
    """
    Grow mask including pixels that have a high likelihood.

    GM tissue parameters are sampled in image patches of ``ww`` size.
    This is inspired on mindboggle's solution to the problem:
    https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660

    """
    selem = sim.ball(bw)

    if ants_segs is None:
        ants_segs = np.zeros_like(aseg, dtype=np.uint8)

    aseg[aseg == 42] = 3  # Collapse both hemispheres
    gm = anat.copy()
    gm[aseg != 3] = 0

    refined = refine_aseg(aseg)
    newrefmask = sim.binary_dilation(refined, selem) - refined
    indices = np.argwhere(newrefmask > 0)
    for pixel in indices:
        # When ATROPOS identified the pixel as GM, set and carry on
        if ants_segs[tuple(pixel)] == 2:
            refined[tuple(pixel)] = 1
            continue

        window = gm[
            pixel[0] - ww:pixel[0] + ww,
            pixel[1] - ww:pixel[1] + ww,
            pixel[2] - ww:pixel[2] + ww,
        ]
        if np.any(window > 0):
            mu = window[window > 0].mean()
            sigma = max(window[window > 0].std(), 1.0e-5)
            zstat = abs(anat[tuple(pixel)] - mu) / sigma
            refined[tuple(pixel)] = int(zstat < zval)

    refined = sim.binary_opening(refined, selem)
    return refined 
Example #5
Source File: run_create_annotation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_correct_segm(path_img):
    """ load segmentation and correct it with simple morphological operations

    :param str path_img:
    :return (ndarray, ndarray):
    """
    assert os.path.isfile(path_img), 'missing: %s' % path_img
    logging.debug('loading image: %s', path_img)
    img = tl_data.io_imread(path_img)
    seg = (img > 0)
    seg = morphology.binary_opening(seg, selem=morphology.disk(25))
    seg = morphology.remove_small_objects(seg)
    seg_lb = measure.label(seg)
    seg_lb[seg == 0] = 0
    return seg, seg_lb 
Example #6
Source File: run_create_annotation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def segm_set_center_levels(name, seg_labels, path_out, levels=DISTANCE_LEVELS):
    """ set segmentation levels according distance inside object imsegm

    :param str name: image name
    :param ndarray seg_labels:
    :param str path_out: path for output
    :param [float] levels: distance levels fro segmentation levels
    """
    seg = np.zeros_like(seg_labels)

    # set bourders to 0
    # seg_labels = set_boundary_values(seg_labels)

    for obj_id in range(1, seg_labels.max() + 1):
        im_bin = (seg_labels == obj_id)
        if np.sum(im_bin) == 0:
            continue
        distance = ndimage.distance_transform_edt(im_bin)
        probab = distance / np.max(distance)
        pos_center = ndimage.measurements.center_of_mass(im_bin)
        # logging.debug('object %i with levels: %s', obj_id, repr(levels))
        for i, level in enumerate(levels):
            mask = probab > level
            if i > 0:
                radius = int(np.sqrt(np.sum(mask) / np.pi))
                im_level = draw_circle(pos_center, radius, mask.shape)
                mask = np.logical_and(mask, im_level)
                sel = morphology.disk(int(radius * 0.15))
                mask = morphology.binary_opening(mask, sel)
            seg[mask] = i + 1

    path_seg = os.path.join(path_out, name)
    tl_data.io_imsave(path_seg, seg.astype(np.uint8)) 
Example #7
Source File: opening.py    From plantcv with MIT License 5 votes vote down vote up
def opening(gray_img, kernel=None):
    """Wrapper for scikit-image opening functions. Opening can remove small bright spots (i.e. salt).

    Inputs:
    gray_img = input image (grayscale or binary)
    kernel   = optional neighborhood, expressed as an array of 1s and 0s. If None, use cross-shaped structuring element.

    :param gray_img: ndarray
    :param kernel = ndarray
    :return filtered_img: ndarray
    """

    params.device += 1

    # Make sure the image is binary/grayscale
    if len(np.shape(gray_img)) != 2:
        fatal_error("Input image must be grayscale or binary")

    # If image is binary use the faster method
    if len(np.unique(gray_img)) == 2:
        bool_img = morphology.binary_opening(gray_img, kernel)
        filtered_img = np.copy(bool_img.astype(np.uint8) * 255)
    # Otherwise use method appropriate for grayscale images
    else:
        filtered_img = morphology.opening(gray_img, kernel)

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

    return filtered_img 
Example #8
Source File: SDS_preprocess.py    From CoastSat with GNU General Public License v3.0 4 votes vote down vote up
def create_cloud_mask(im_QA, satname, cloud_mask_issue):
    """
    Creates a cloud mask using the information contained in the QA band.

    KV WRL 2018

    Arguments:
    -----------
    im_QA: np.array
        Image containing the QA band
    satname: string
        short name for the satellite: ```'L5', 'L7', 'L8' or 'S2'```
    cloud_mask_issue: boolean
        True if there is an issue with the cloud mask and sand pixels are being
        erroneously masked on the images

    Returns:
    -----------
    cloud_mask : np.array
        boolean array with True if a pixel is cloudy and False otherwise
        
    """

    # convert QA bits (the bits allocated to cloud cover vary depending on the satellite mission)
    if satname == 'L8':
        cloud_values = [2800, 2804, 2808, 2812, 6896, 6900, 6904, 6908]
    elif satname == 'L7' or satname == 'L5' or satname == 'L4':
        cloud_values = [752, 756, 760, 764]
    elif satname == 'S2':
        cloud_values = [1024, 2048] # 1024 = dense cloud, 2048 = cirrus clouds

    # find which pixels have bits corresponding to cloud values
    cloud_mask = np.isin(im_QA, cloud_values)

    # remove cloud pixels that form very thin features. These are beach or swash pixels that are
    # erroneously identified as clouds by the CFMASK algorithm applied to the images by the USGS.
    if sum(sum(cloud_mask)) > 0 and sum(sum(~cloud_mask)) > 0:
        morphology.remove_small_objects(cloud_mask, min_size=10, connectivity=1, in_place=True)

        if cloud_mask_issue:
            elem = morphology.square(3) # use a square of width 3 pixels
            cloud_mask = morphology.binary_opening(cloud_mask,elem) # perform image opening
            # remove objects with less than 25 connected pixels
            morphology.remove_small_objects(cloud_mask, min_size=25, connectivity=1, in_place=True)

    return cloud_mask 
Example #9
Source File: run_ovary_egg-segmentation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def segment_watershed(seg, centers, post_morph=False):
    """ perform watershed segmentation on input imsegm
    and optionally run some postprocessing using morphological operations

    :param ndarray seg: input image / segmentation
    :param [[int, int]] centers: position of centres / seeds
    :param bool post_morph: apply morphological postprocessing
    :return ndarray, [[int, int]]: resulting segmentation, updated centres
    """
    logging.debug('segment: watershed...')
    seg_binary = (seg > 0)
    seg_binary = ndimage.morphology.binary_fill_holes(seg_binary)
    # thr_area = int(0.05 * np.sum(seg_binary))
    # seg_binary = morphology.remove_small_holes(seg_binary, min_size=thr_area)
    distance = ndimage.distance_transform_edt(seg_binary)
    markers = np.zeros_like(seg)
    for i, pos in enumerate(centers):
        markers[int(pos[0]), int(pos[1])] = i + 1
    segm = morphology.watershed(-distance, markers, mask=seg_binary)

    # if morphological postprocessing was not selected, ends here
    if not post_morph:
        return segm, centers, None

    segm_clean = np.zeros_like(segm)
    for lb in range(1, np.max(segm) + 1):
        seg_lb = (segm == lb)
        # some morphology operartion for cleaning
        seg_lb = morphology.binary_closing(seg_lb, selem=morphology.disk(5))
        seg_lb = ndimage.morphology.binary_fill_holes(seg_lb)
        # thr_area = int(0.15 * np.sum(seg_lb))
        # seg_lb = morphology.remove_small_holes(seg_lb, min_size=thr_area)
        seg_lb = morphology.binary_opening(seg_lb, selem=morphology.disk(15))
        segm_clean[seg_lb] = lb
    return segm_clean, centers, None