Python skimage.morphology.dilation() Examples

The following are 30 code examples of skimage.morphology.dilation(). 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: math.py    From spinalcordtoolbox with MIT License 7 votes vote down vote up
def dilate(data, size, shape, dim=None):
    """
    Dilate data using ball structuring element
    :param data: Image or numpy array: 2d or 3d array
    :param size: int: If shape={'square', 'cube'}: Corresponds to the length of an edge (size=1 has no effect).
    If shape={'disk', 'ball'}: Corresponds to the radius, not including the center element (size=0 has no effect).
    :param shape: {'square', 'cube', 'disk', 'ball'}
    :param dim: {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if
    you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2.
    :return: numpy array: data dilated
    """
    if isinstance(data, Image):
        im_out = data.copy()
        im_out.data = dilate(data.data, size, shape, dim)
        return im_out
    else:
        return dilation(data, selem=_get_selem(shape, size, dim), out=None) 
Example #2
Source File: inference.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) - gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    img_color = np.dstack((img, img, img))

    img_hsv = color.rgb2hsv(img_color)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #3
Source File: preparation.py    From open-solution-data-science-bowl-2018 with MIT License 6 votes vote down vote up
def overlay_cut_masks(images_dir, subdir_name, target_dir, cut_size=1):
    train_dir = os.path.join(images_dir, subdir_name)
    for mask_dirname in tqdm(glob.glob('{}/*/masks'.format(train_dir))):
        masks = []
        for ind, image_filepath in enumerate(glob.glob('{}/*'.format(mask_dirname))):
            image = np.asarray(Image.open(image_filepath))
            image = np.where(image > 0, ind + 1, 0)
            masks.append(image)
        labeled_masks = np.sum(masks, axis=0)
        overlayed_masks = np.where(labeled_masks, 1, 0)

        watershed_mask = watershed(overlayed_masks.astype(np.bool), labeled_masks, watershed_line=True)
        if watershed_mask.max() == watershed_mask.min():
            cut_masks = overlayed_masks
        else:
            borders = (watershed_mask == 0) & overlayed_masks
            selem = rectangle(cut_size, cut_size)
            dilated_borders = dilation(borders, selem=selem)
            cut_masks = np.where(dilated_borders, 0, overlayed_masks)

        target_filepath = '/'.join(mask_dirname.replace(images_dir, target_dir).split('/')[:-1]) + '.png'
        os.makedirs(os.path.dirname(target_filepath), exist_ok=True)
        imwrite(target_filepath, cut_masks) 
Example #4
Source File: inferences.py    From Global_Convolutional_Network with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape[:2]
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) ^ gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    
    img_hsv = color.rgb2hsv(img)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #5
Source File: composition.py    From pytorch_connectomics with MIT License 6 votes vote down vote up
def smooth_edge(self, data):
        smoothed_label = data['label'].copy()

        for z in range(smoothed_label.shape[0]):
            temp = smoothed_label[z].copy()
            for idx in np.unique(temp):
                if idx != 0:
                    binary = (temp==idx).astype(np.uint8)
                    for _ in range(2):
                        binary = dilation(binary)
                        binary = gaussian(binary, sigma=2, preserve_range=True)
                        binary = dilation(binary)
                        binary = (binary > 0.8).astype(np.uint8)
            
                    temp[np.where(temp==idx)]=0
                    temp[np.where(binary==1)]=idx
            smoothed_label[z] = temp

        data['label'] = smoothed_label
        return data 
Example #6
Source File: evaluate.py    From Global_Convolutional_Network with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape[:2]
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) ^ gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    
    img_hsv = color.rgb2hsv(img)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #7
Source File: input_pipeline.py    From SketchySceneColorization with MIT License 6 votes vote down vote up
def thicken_drawings(image):
    """
    :param image: [H, W, 3], np.float32
    :return:
    """
    img = np.array(image[:, :, 0], dtype=np.uint8)

    img = 255 - img
    dilated_img = sm.dilation(img, sm.square(2))
    dilated_img = 255 - dilated_img  # [H, W]

    rst_img3 = np.zeros([dilated_img.shape[0], dilated_img.shape[1], 3], dtype=np.uint8)
    for i in range(3):
        rst_img3[:, :, i] = dilated_img

    return rst_img3 
Example #8
Source File: utils.py    From DRFNS with MIT License 6 votes vote down vote up
def generate_wsl(ws):
    """
    Generates watershed line. In particular, useful for seperating object
    in ground thruth as they are labeled by different intergers.
    """
    se = square(3)
    ero = ws.copy()
    ero[ero == 0] = ero.max() + 1
    ero = erosion(ero, se)
    ero[ws == 0] = 0

    grad = dilation(ws, se) - ero
    grad[ws == 0] = 0
    grad[grad > 0] = 255
    grad = grad.astype(np.uint8)
    return grad 
Example #9
Source File: postprocessing.py    From open-solution-mapping-challenge with MIT License 6 votes vote down vote up
def dilate_image(mask, dilate_selem_size):
    """Dilate mask.

    Args:
        mask (numpy.ndarray): Mask of shape (H x W) or multiple masks of shape (C x H x W).
        dilate_selem_size (int): Size of rectangle structuring element used for dilation.

    Returns:
        numpy.ndarray: dilated Mask of shape (H x W) or multiple masks of shape (C x H x W).

    """
    if not dilate_selem_size > 0:
        return mask
    selem = rectangle(dilate_selem_size, dilate_selem_size)
    if mask.ndim == 2:
        dilated_image = dilation(mask, selem=selem)
    else:
        dilated_image = []
        for category_mask in mask:
            dilated_image.append(dilation(category_mask, selem=selem))
        dilated_image = np.stack(dilated_image)
    return dilated_image 
Example #10
Source File: sample_patches.py    From THU-DeepHypergraph with MIT License 6 votes vote down vote up
def threshold_segmentation(img):
    # calculate the overview level size and retrieve the image
    img_hsv = img.convert('HSV')
    img_hsv_np = np.array(img_hsv)

    # dilate image and then threshold the image
    schannel = img_hsv_np[:, :, 1]
    mask = np.zeros(schannel.shape)

    schannel = dilation(schannel, star(3))
    schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0)
    threshold_global = threshold_otsu(schannel)

    mask[schannel > threshold_global] = FOREGROUND
    mask[schannel <= threshold_global] = BACKGROUND

    return mask 
Example #11
Source File: prepro.py    From super-resolution-videos with The Unlicense 6 votes vote down vote up
def dilation(x, radius=3):
    """ Return greyscale morphological dilation of an image,
    see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`_.

    Parameters
    -----------
    x : 2D array image.
    radius : int for the radius of mask.
    """
    from skimage.morphology import disk, dilation
    mask = disk(radius)
    x = dilation(x, selem=mask)
    return x




## Sequence 
Example #12
Source File: prepro.py    From LapSRN-tensorflow with Apache License 2.0 6 votes vote down vote up
def dilation(x, radius=3):
    """ Return greyscale morphological dilation of an image,
    see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`_.

    Parameters
    -----------
    x : 2D array image.
    radius : int for the radius of mask.
    """
    from skimage.morphology import disk, dilation
    mask = disk(radius)
    x = dilation(x, selem=mask)
    return x




## Sequence 
Example #13
Source File: S2PixelCloudDetector.py    From sentinel2-cloud-detector with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def get_mask_from_prob(self, cloud_probs, threshold=None):
        """
        Returns cloud mask by applying morphological operations -- convolution and dilation --
        to input cloud probabilities.

        :param cloud_probs: cloud probability map
        :type cloud_probs: numpy array of cloud probabilities (shape n_images x n x m)
        :param threshold: A float from [0,1] specifying threshold
        :type threshold: float
        :return: raster cloud mask
        :rtype: numpy array (shape n_images x n x m)
        """
        threshold = self.threshold if threshold is None else threshold

        if self.average_over:
            cloud_masks = np.asarray([convolve(cloud_prob, self.conv_filter) > threshold
                                      for cloud_prob in cloud_probs], dtype=np.int8)
        else:
            cloud_masks = (cloud_probs > threshold).astype(np.int8)

        if self.dilation_size:
            cloud_masks = np.asarray([dilation(cloud_mask, self.dilation_filter) for cloud_mask in cloud_masks],
                                     dtype=np.int8)
        return cloud_masks 
Example #14
Source File: demo.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def masked(img, gt, mask, alpha=1):
    """Returns image with GT lung field outlined with red, predicted lung field
    filled with blue."""
    rows, cols = img.shape
    color_mask = np.zeros((rows, cols, 3))
    boundary = morphology.dilation(gt, morphology.disk(3)) - gt
    color_mask[mask == 1] = [0, 0, 1]
    color_mask[boundary == 1] = [1, 0, 0]
    img_color = np.dstack((img, img, img))

    img_hsv = color.rgb2hsv(img_color)
    color_mask_hsv = color.rgb2hsv(color_mask)

    img_hsv[..., 0] = color_mask_hsv[..., 0]
    img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

    img_masked = color.hsv2rgb(img_hsv)
    return img_masked 
Example #15
Source File: prepro.py    From super-resolution-videos with The Unlicense 5 votes vote down vote up
def binary_dilation(x, radius=3):
    """ Return fast binary morphological dilation of an image.
    see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`_.

    Parameters
    -----------
    x : 2D array image.
    radius : int for the radius of mask.
    """
    from skimage.morphology import disk, binary_dilation
    mask = disk(radius)
    x = binary_dilation(image, selem=mask)
    return x 
Example #16
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def TF_dilation(img):
    return dilation(img) 
Example #17
Source File: cityscapes.py    From Bayesian-CycleGAN with MIT License 5 votes vote down vote up
def make_boundaries(label, thickness=None):
        """
        Input is an image label, output is a numpy array mask encoding the boundaries of the objects
        Extract pixels at the true boundary by dilation - erosion of label.
        Don't just pick the void label as it is not exclusive to the boundaries.
        """
        assert(thickness is not None)
        import skimage.morphology as skm
        void = 255
        mask = np.logical_and(label > 0, label != void)[0]
        selem = skm.disk(thickness)
        boundaries = np.logical_xor(skm.dilation(mask, selem),
                                    skm.erosion(mask, selem))
        return boundaries 
Example #18
Source File: vision.py    From geoseg with MIT License 5 votes vote down vote up
def pair_to_rgb(gen_img, tar_img, background='black', use_dilation=False, disk_value=2):
    """
    args:
        gen_img: (ndarray) in [img_rows, img_cols], dytpe=unit8
        tar_img: (ndarray) in [img_rows, img_cols], dytpe=unit8
        background: (str) ['black', 'white']
    return:
        rgb_img: red -> false positive;
                 green -> true positive;
                 blue -> false positive;
    """
    # enhance outline border
    if use_dilation:
        gen_img = dilation(gen_img, disk(disk_value))
        tar_img = dilation(tar_img, disk(disk_value))

    if background == "black":
        # saving rgb results
        rgb_img = np.zeros((gen_img.shape[0], gen_img.shape[1], 3), np.uint8)
        # assign false negative as red channel
        rgb_img[:, :, 0][np.logical_and(gen_img == 255, tar_img == 0)] = 255
        # assign true positive as green channel
        rgb_img[:, :, 1][np.logical_and(gen_img == 255, tar_img == 255)] = 255
        # assign false positive as blue channel
        rgb_img[:, :, 2][np.logical_and(gen_img == 0, tar_img == 255)] = 255
    else:
        # saving rgb results
        rgb_img = np.ones(
            (gen_img.shape[0], gen_img.shape[1], 3), np.uint8) * 255
        # assign false negative as red channel
        rgb_img[:, :, 1][np.logical_and(gen_img == 255, tar_img == 0)] = 0
        rgb_img[:, :, 2][np.logical_and(gen_img == 255, tar_img == 0)] = 0
        # assign true positive as green channel
        rgb_img[:, :, 0][np.logical_and(gen_img == 255, tar_img == 255)] = 0
        rgb_img[:, :, 2][np.logical_and(gen_img == 255, tar_img == 255)] = 0
        # assign false positive as blue channel
        rgb_img[:, :, 0][np.logical_and(gen_img == 0, tar_img == 255)] = 0
        rgb_img[:, :, 1][np.logical_and(gen_img == 0, tar_img == 255)] = 0
    return rgb_img 
Example #19
Source File: utils.py    From CMCS-Temporal-Action-Localization with MIT License 5 votes vote down vote up
def detect_with_thresholding(metric,
                             thrh_type,
                             thrh_value,
                             proc_type,
                             proc_value,
                             debug_file=None):

    assert (thrh_type in ['max', 'mean'])
    assert (proc_type in ['dilation', 'median'])

    out_detections = []

    if thrh_type == 'max':
        mask = metric > thrh_value

    elif thrh_type == 'mean':
        mask = metric > (thrh_value * metric.mean())

    if proc_type == 'dilation':
        mask = dilation(mask, np.array([[1] for _ in range(proc_value)]))
    elif proc_type == 'median':
        mask = medfilt(mask[:, 0], kernel_size=proc_value)
        # kernel_size should be odd
        mask = np.expand_dims(mask, axis=1)

    return mask


################ Output Detection To Files ################ 
Example #20
Source File: cityscapes.py    From 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement with MIT License 5 votes vote down vote up
def make_boundaries(label, thickness=None):
        """
        Input is an image label, output is a numpy array mask encoding the boundaries of the objects
        Extract pixels at the true boundary by dilation - erosion of label.
        Don't just pick the void label as it is not exclusive to the boundaries.
        """
        assert(thickness is not None)
        import skimage.morphology as skm
        void = 255
        mask = np.logical_and(label > 0, label != void)[0]
        selem = skm.disk(thickness)
        boundaries = np.logical_xor(skm.dilation(mask, selem),
                                    skm.erosion(mask, selem))
        return boundaries 
Example #21
Source File: mask_utils.py    From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 5 votes vote down vote up
def create_separation(labels):
    tmp = dilation(labels > 0, square(12))
    tmp2 = watershed(tmp, labels, mask=tmp, watershed_line=True) > 0
    tmp = tmp ^ tmp2
    tmp = dilation(tmp, square(3))

    props = measure.regionprops(labels)

    msk1 = np.zeros_like(labels, dtype='bool')

    for y0 in range(labels.shape[0]):
        for x0 in range(labels.shape[1]):
            if not tmp[y0, x0]:
                continue
            if labels[y0, x0] == 0:
                sz = 5
            else:
                sz = 7
                if props[labels[y0, x0] - 1].area < 300:
                    sz = 5
                elif props[labels[y0, x0] - 1].area < 2000:
                    sz = 6
            uniq = np.unique(labels[max(0, y0 - sz):min(labels.shape[0], y0 + sz + 1),
                             max(0, x0 - sz):min(labels.shape[1], x0 + sz + 1)])
            if len(uniq[uniq > 0]) > 1:
                msk1[y0, x0] = True
    return msk1 
Example #22
Source File: test_panoptic.py    From seamseg with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_prediction_image(_, panoptic_pred, img_info, out_dir, colors, num_stuff):
    msk, cat, obj, iscrowd = panoptic_pred

    img = Image.open(img_info["abs_path"])

    # Prepare folders and paths
    folder, img_name = path.split(img_info["rel_path"])
    img_name, _ = path.splitext(img_name)
    out_dir = path.join(out_dir, folder)
    ensure_dir(out_dir)
    out_path = path.join(out_dir, img_name + ".jpg")

    # Render semantic
    sem = cat[msk].numpy()
    crowd = iscrowd[msk].numpy()
    sem[crowd == 1] = 255

    sem_img = Image.fromarray(colors[sem])
    sem_img = sem_img.resize(img_info["original_size"][::-1])

    # Render contours
    is_background = (sem < num_stuff) | (sem == 255)
    msk = msk.numpy()
    msk[is_background] = 0

    contours = find_boundaries(msk, mode="outer", background=0).astype(np.uint8) * 255
    contours = dilation(contours)

    contours = np.expand_dims(contours, -1).repeat(4, -1)
    contours_img = Image.fromarray(contours, mode="RGBA")
    contours_img = contours_img.resize(img_info["original_size"][::-1])

    # Compose final image and save
    out = Image.blend(img, sem_img, 0.5).convert(mode="RGBA")
    out = Image.alpha_composite(out, contours_img)
    out.convert(mode="RGB").save(out_path) 
Example #23
Source File: preparation.py    From open-solution-data-science-bowl-2018 with MIT License 5 votes vote down vote up
def overlay_masks_with_borders_json(images_dir, subdir_name, target_dir, borders_size=3, dilation_size=5):
    train_dir = os.path.join(images_dir, subdir_name)
    for mask_dirname in tqdm(glob.glob('{}/*/masks'.format(train_dir))):
        masks = []
        for ind, image_filepath in enumerate(glob.glob('{}/*'.format(mask_dirname))):
            image = np.asarray(Image.open(image_filepath))
            image = np.where(image > 0, ind + 1, 0)
            masks.append(image)
        labeled_masks = np.sum(masks, axis=0)
        overlayed_masks = np.where(labeled_masks, 1, 0)

        selem = rectangle(dilation_size, dilation_size)
        dilated_mask = dilation(overlayed_masks, selem=selem)
        watershed_mask = watershed((dilated_mask >= 0).astype(np.bool), labeled_masks, watershed_line=True)

        if watershed_mask.max() == watershed_mask.min():
            dilated_borders = np.zeros_like(overlayed_masks)
        else:
            borders = (watershed_mask == 0) & (dilated_mask > 0)
            selem = rectangle(borders_size, borders_size)
            dilated_borders = dilation(borders, selem=selem)

        nuclei = prepare_class_encoding(overlayed_masks)
        borders = prepare_class_encoding(dilated_borders)

        target_filepath = '/'.join(mask_dirname.replace(images_dir, target_dir).split('/')[:-1]) + '.json'
        os.makedirs(os.path.dirname(target_filepath), exist_ok=True)
        save_target_masks(target_filepath, nuclei, borders) 
Example #24
Source File: postprocessing.py    From DRFNS with MIT License 5 votes vote down vote up
def GetContours(img):
    """
    Returns only the contours of the image.
    The image has to be a binary image 
    """
    img[img > 0] = 1
    return dilation(img, disk(2)) - erosion(img, disk(2)) 
Example #25
Source File: segmentation_test.py    From DRFNS with MIT License 5 votes vote down vote up
def get_rough_detection(self, img, bigsize=40.0, smallsize=4.0, thresh = 0):
        diff = self.difference_of_gaussian(-img, bigsize, smallsize)
        diff[diff>thresh] = 1
        
        se = morphology.square(4)
        ero = morphology.erosion(diff, se)
        
        labimage = label(ero)
        #rec = morphology.reconstruction(ero, img, method='dilation').astype(np.dtype('uint8'))
        
        # connectivity=1 corresponds to 4-connectivity.
        morphology.remove_small_objects(labimage, min_size=600, connectivity=1, in_place=True)
        #res = np.zeros(img.shape)
        ero[labimage==0] = 0
        ero = 1 - ero
        labimage = label(ero)
        morphology.remove_small_objects(labimage, min_size=400, connectivity=1, in_place=True)
        ero[labimage==0] = 0
        res = 1 - ero
        res[res>0] = 255
        
        #temp = 255 - temp
        #temp = morphology.remove_small_objects(temp, min_size=400, connectivity=1, in_place=True)
        #res = 255 - temp
        
        return res 
Example #26
Source File: data_segmentation.py    From pytorch_connectomics with MIT License 5 votes vote down vote up
def seg_to_targets(label, topts):
    # input: DHW
    # output: CDHW
    # mito/synapse cleft binary: topt = 0 
    # synapse polarity: topt = 1
    out = [None]*len(topts)
    for tid,topt in enumerate(topts):
        if topt == '-1': # direct copy
            out[tid] = label[None,:].astype(np.float32)
        elif topt == '0': # binary
            out[tid] = (label>0)[None,:].astype(np.float32)
        elif topt[0] == '1': 
            # synaptic polarity (multi-channel):
            tmp = [None]*3 
            tmp[0] = np.logical_and((label % 2) == 1, label > 0)
            tmp[1] = np.logical_and((label % 2) == 0, label > 0)
            tmp[2] = (label > 0)
            # concatenate at channel
            out[tid] = np.stack(tmp, 0).astype(np.float32)
        elif topt[0] == '2': # affinity
            out[tid] = seg_to_aff(label)
        elif topt[0] == '3': # small object mask
            # size_thres: 2d threshold for small size
            # zratio: resolution ration between z and x/y
            # mask_dsize: mask dilation size
            _, size_thres, zratio, _ = [int(x) for x in topt.split('-')]
            out[tid] = (seg_to_small_seg(label, size_thres, zratio)>0)[None,:].astype(np.float32)
        elif topt[0] == '4': # instance boundary mask
            _, bd_sz,do_bg = [int(x) for x in topt.split('-')]
            out[tid] = seg_to_instance_bd(label, bd_sz, do_bg)[None,:].astype(np.float32)
    return out 
Example #27
Source File: evaluate_curv.py    From pytorch_connectomics with MIT License 5 votes vote down vote up
def compute_precision_recall(pred, gt):
    pred_skel = skeletonize(pred)
    pred_dil = dilation(pred_skel, square(5))
    gt_skel = skeletonize(gt)
    gt_dil = dilation(gt_skel, square(5))
    return compute_metrics([pred_skel], [gt_skel], [pred_dil], [gt_dil]) 
Example #28
Source File: preparation.py    From open-solution-data-science-bowl-2018 with MIT License 5 votes vote down vote up
def overlay_masks_with_borders(images_dir, subdir_name, target_dir, borders_size=3, dilation_size=5):
    train_dir = os.path.join(images_dir, subdir_name)
    for mask_dirname in tqdm(glob.glob('{}/*/masks'.format(train_dir))):
        masks = []
        for ind, image_filepath in enumerate(glob.glob('{}/*'.format(mask_dirname))):
            image = np.asarray(Image.open(image_filepath))
            image = np.where(image > 0, ind + 1, 0)
            masks.append(image)
        labeled_masks = np.sum(masks, axis=0)
        overlayed_masks = np.where(labeled_masks, 1, 0)

        selem = rectangle(dilation_size, dilation_size)
        dilated_mask = dilation(overlayed_masks, selem=selem)
        watershed_mask = watershed((dilated_mask >= 0).astype(np.bool), labeled_masks, watershed_line=True)

        if watershed_mask.max() == watershed_mask.min():
            masks_with_borders = overlayed_masks
        else:
            borders = (watershed_mask == 0) & (dilated_mask > 0)
            selem = rectangle(borders_size, borders_size)
            dilated_borders = dilation(borders, selem=selem)
            masks_with_borders = np.where(dilated_borders, 2, overlayed_masks)

        target_filepath = '/'.join(mask_dirname.replace(images_dir, target_dir).split('/')[:-1]) + '.png'
        os.makedirs(os.path.dirname(target_filepath), exist_ok=True)
        imwrite(target_filepath, masks_with_borders) 
Example #29
Source File: segmentation_test.py    From DRFNS with MIT License 5 votes vote down vote up
def morpho_rec2(self, img, size=10):
        # internal gradient of the cells: 
        se = morphology.diamond(size)
        dil = morphology.dilation(img, se)
        rec = morphology.reconstruction(dil, img, method='erosion').astype(np.dtype('uint8'))
                
        return rec 
Example #30
Source File: segmentation_test.py    From DRFNS with MIT License 5 votes vote down vote up
def morpho_rec(self, img, size=10):
        # internal gradient of the cells: 
        se = morphology.diamond(size)
        ero = morphology.erosion(img, se)
        rec = morphology.reconstruction(ero, img, method='dilation').astype(np.dtype('uint8'))
                
        return rec