Python skimage.morphology.remove_small_holes() Examples

The following are 12 code examples of skimage.morphology.remove_small_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 skimage.morphology , or try the search function .
Example #1
Source File: MorphologyModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def fillSmallHoles(s, params):
    logging.info(f"{s['filename']} - \tfillSmallHoles")
    min_size = int(params.get("min_size", 64))
    img_reduced = morphology.remove_small_holes(s["img_mask_use"], min_size=min_size)
    img_small = img_reduced & np.invert(s["img_mask_use"])

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_small_fill.png", img_as_ubyte(img_small))
    s["img_mask_small_removed"] = (img_small * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = img_reduced

    s.addToPrintList("percent_small_tissue_filled",
                     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 MorphologyModule.fillSmallHoles: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.fillSmallHoles: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail")
    return 
Example #2
Source File: evaluate.py    From Global_Convolutional_Network with MIT License 5 votes vote down vote up
def remove_small_regions(img, size):
    """Morphologically removes small (less than size) connected regions of 0s or 1s."""
    img = morphology.remove_small_objects(img, size)
    img = morphology.remove_small_holes(img, size)
    return img 
Example #3
Source File: data_skeleton.py    From pytorch_connectomics with MIT License 4 votes vote down vote up
def skeleton_transform(label, relabel=True):
    resolution = (1.0, 1.0)
    alpha = 1.0
    beta = 0.8

    if relabel == True: # run connected component
        label = morphology.label(label, background=0)
    
    label_id = np.unique(label)
    # print(np.unique(label_id))
    skeleton = np.zeros(label.shape, dtype=np.uint8)
    distance = np.zeros(label.shape, dtype=np.float32)
    Temp = np.zeros(label.shape, dtype=np.uint8)
    if len(label_id) == 1: # only one object within current volume
        if label_id[0] == 0:
            return distance, skeleton
        else:
            temp_id = label_id
    else:
        temp_id = label_id[1:]

    for idx in temp_id:
        temp1 = (label == idx)
        temp2 = morphology.remove_small_holes(temp1, 16, connectivity=1)

        #temp3 = erosion(temp2)
        temp3 = temp2.copy()
        Temp += temp3
        skeleton_mask = skeletonize(temp3).astype(np.uint8)
        skeleton += skeleton_mask

        skeleton_edt = ndimage.distance_transform_edt(
            1-skeleton_mask, resolution)
        dist_max = np.max(skeleton_edt*temp3)
        dist_max = np.clip(dist_max, a_min=2.0, a_max=None)
        skeleton_edt = skeleton_edt / (dist_max*alpha)
        skeleton_edt = skeleton_edt**(beta)

        reverse = 1.0-(skeleton_edt*temp3)
        distance += reverse*temp3

    # generate boundary
    distance[np.where(Temp == 0)] = -1.0

    return distance, skeleton 
Example #4
Source File: inferences.py    From Global_Convolutional_Network with MIT License 4 votes vote down vote up
def remove_small_regions(img, size):
    """Morphologically removes small (less than size) connected regions of 0s or 1s."""
    img = morphology.remove_small_objects(img, size)
    img = morphology.remove_small_holes(img, size)
    return img 
Example #5
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 
Example #6
Source File: run_ovary_egg-segmentation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
def segment_active_contour(img, centers):
    """ segmentation using acive contours

    :param ndarray img: input image / segmentation
    :param [[int, int]] centers: position of centres / seeds
    :return (ndarray, [[int, int]]): resulting segmentation, updated centres
    """
    logging.debug('segment: active_contour...')
    # http://scikit-image.org/docs/dev/auto_examples/edges/plot_active_contours.html
    segm = np.zeros(img.shape[:2])
    img_smooth = ndimage.filters.gaussian_filter(img, 5)
    center_circles, _, _ = create_circle_center(img.shape[:2], centers)
    for i, snake in enumerate(center_circles):
        snake = segmentation.active_contour(img_smooth, snake.astype(float),
                                            alpha=0.015, beta=10, gamma=0.001,
                                            w_line=0.0, w_edge=1.0,
                                            max_px_move=1.0,
                                            max_iterations=2500,
                                            convergence=0.2)
        seg = np.zeros(segm.shape, dtype=bool)
        x, y = np.array(snake).transpose().tolist()
        # rr, cc = draw.polygon(x, y)
        seg[map(int, x), map(int, y)] = True
        seg = morphology.binary_dilation(seg, selem=morphology.disk(3))
        bb_area = int((max(x) - min(x)) * (max(y) - min(y)))
        logging.debug('bounding box area: %d', bb_area)
        seg = morphology.remove_small_holes(seg, min_size=bb_area)
        segm[seg] = i + 1
    return segm, centers, None 
Example #7
Source File: submit.py    From dsb2018_topcoders with MIT License 3 votes vote down vote up
def wsh(mask_img, threshold, border_img, seeds):
    img_copy = np.copy(mask_img)
    m = seeds * border_img# * dt
    img_copy[m <= threshold + 0.35] = 0
    img_copy[m > threshold + 0.35] = 1
    img_copy = img_copy.astype(np.bool)
    img_copy = remove_small_objects(img_copy, 10).astype(np.uint8)

    mask_img[mask_img <= threshold] = 0
    mask_img[mask_img > threshold] = 1
    mask_img = mask_img.astype(np.bool)
    mask_img = remove_small_holes(mask_img, 1000)
    mask_img = remove_small_objects(mask_img, 8).astype(np.uint8)
    # cv2.imwrite('t.png', (mask_img * 255).astype(np.uint8))
    # cv2.imwrite('t2.png', (img_copy * 255).astype(np.uint8))
    labeled_array = my_watershed(mask_img, mask_img, img_copy)
    return labeled_array 
Example #8
Source File: MorphologyModule.py    From HistoQC with BSD 3-Clause Clear License 3 votes vote down vote up
def remove_large_objects(img, max_size):
    # code taken from morphology.remove_small_holes, except switched < with >
    selem = ndi.generate_binary_structure(img.ndim, 1)
    ccs = np.zeros_like(img, dtype=np.int32)
    ndi.label(img, selem, output=ccs)
    component_sizes = np.bincount(ccs.ravel())
    too_big = component_sizes > max_size
    too_big_mask = too_big[ccs]
    img_out = img.copy()
    img_out[too_big_mask] = 0
    return img_out 
Example #9
Source File: MorphologyModule.py    From HistoQC with BSD 3-Clause Clear License 2 votes vote down vote up
def removeFatlikeTissue(s, params):
    logging.info(f"{s['filename']} - \tremoveFatlikeTissue")
    fat_cell_size = int(params.get("fat_cell_size", 64))
    kernel_size = int(params.get("kernel_size", 3))
    max_keep_size = int(params.get("max_keep_size", 1000))

    img_reduced = morphology.remove_small_holes(s["img_mask_use"], min_size=fat_cell_size)
    img_small = img_reduced & np.invert(s["img_mask_use"])
    img_small = ~morphology.remove_small_holes(~img_small, min_size=9)

    mask_dilate = morphology.dilation(img_small, selem=np.ones((kernel_size, kernel_size)))
    mask_dilate_removed = remove_large_objects(mask_dilate, max_keep_size)

    mask_fat = mask_dilate & ~mask_dilate_removed

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_fatlike.png", img_as_ubyte(mask_fat))
    s["img_mask_fatlike"] = (mask_fat * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = prev_mask & ~mask_fat

    s.addToPrintList("percent_fatlike_tissue_removed",
                     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 MorphologyModule.removeFatlikeTissue: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.removeFatlikeTissue: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail") 
Example #10
Source File: inference.py    From lung-segmentation-2d with MIT License 2 votes vote down vote up
def remove_small_regions(img, size):
    """Morphologically removes small (less than size) connected regions of 0s or 1s."""
    img = morphology.remove_small_objects(img, size)
    img = morphology.remove_small_holes(img, size)
    return img 
Example #11
Source File: postprocess0.py    From 2018DSB with MIT License 1 votes vote down vote up
def postprocess(preds, config):
    assert preds.shape[2]==5
    ldelta = delta(preds[:,:,1:])
    #ldelta = delta0(preds[:,:,5:])
    connected = np.all(ldelta>config.GRADIENT_THRES, 2)
    base = connected * (preds[:,:,0]>config.MASK_THRES)
    
    wall = np.sum(np.abs(preds[:,:,1:]),axis = -1)   
    base_label = label(base) 
    vals, counts = np.unique(base_label[base_label>0], return_counts=True)
    for val in vals[(counts<config.CLIP_AREA_LOW)]:
        base_label[base_label==val]=0
    vals = vals[(counts>=config.CLIP_AREA_LOW)]

    for val in vals:
        
        label_mask = base_label == val   
        if np.sum(label_mask)==0:
            continue
        label_mask = remove_small_holes(label_mask)
        label_mask = basin(label_mask, wall)
        label_mask = remove_small_holes(label_mask)

        '''
        label_bdr = label_mask^binary_erosion(label_mask)
        min_wall = np.min(wall[label_mask])
        ave_bdr_wall = np.mean(wall[label_bdr])
        if ave_bdr_wall < min_wall + config.WALL_DEPTH:
            label_mask = 0
        '''
        base_label[label_mask] = val

    vals, counts = np.unique(base_label[base_label>0], return_counts=True)
    for val in vals[(counts<config.CLIP_AREA_LOW)]:
        base_label[base_label==val]=0        
    return base_label 
Example #12
Source File: demo.py    From lung-segmentation-2d with MIT License 1 votes vote down vote up
def remove_small_regions(img, size):
    """Morphologically removes small (less than size) connected regions of 0s or 1s."""
    img = morphology.remove_small_objects(img, size)
    img = morphology.remove_small_holes(img, size)
    return img