Python skimage.segmentation.find_boundaries() Examples

The following are 28 code examples of skimage.segmentation.find_boundaries(). 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.segmentation , or try the search function .
Example #1
Source File: train_LA_MultiHead_SDF_L1.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #2
Source File: preprocess.py    From 2018DSB with MIT License 5 votes vote down vote up
def enhance(image_batch, mask_batch, max_tries = 10, max_enhance_ratio=.8):
    new_image_batch = image_batch.astype('int16')
    new_mask_batch  = mask_batch.astype('uint8')
    for nb in range(image_batch.shape[0]):   
        image, mask = new_image_batch[nb], new_mask_batch[nb]
        nb_mask = mask.max()
        enhanced = np.zeros(nb_mask+1)
        if nb_mask==0:
            continue
        negative =  np.mean(image[mask>0]) - np.mean(image[mask == 0])  <0
        tries = 0
        if negative:
            while (tries < max_tries and tries < nb_mask/2):
                tries +=1
                id = np.random.randint(1,nb_mask+1)
                if enhanced[id]>0:
                    continue
                enhanced[id]=1
                id_mask = (mask ==id) 
                if np.sum(id_mask)<40:
                    continue
                boundary1 = find_boundaries(id_mask, connectivity=2, mode='outer')
                boundary2 = find_boundaries(id_mask, connectivity=2, mode='inner')
                boundary3 = find_boundaries((id_mask*1.0 - boundary2) >0, connectivity=2, mode='inner')
                weight=id_mask.astype('float32')
                weight[boundary1]=1/4
                weight[boundary2]=1/2
                weight[boundary3]=3/4
                enhance_ratio = (np.random.rand(1)-.1) * np.minimum(max_enhance_ratio, 254.99/(256-np.max(image[id_mask]))-1.1)
                weight = weight * enhance_ratio + 1
                weight=GaussianBlur(weight, (3, 3), sigmaX=10)
                image = 255 -(255 - image) * np.expand_dims(weight,axis=2)
        image[image>255] = 255
        image[image<0] = 0
        new_image_batch[nb] = image
    return new_image_batch 
Example #3
Source File: load.py    From 2018DSB with MIT License 5 votes vote down vote up
def plot_image_boundary(df, ind, save_dir, image_col = 'image', mask_col = 'mask',
                        name_id = False, tag=None):
    image = df.loc[ind, image_col]
    image_b = image.copy()
    cval = image.max()
    if 'is_gray' in df.columns:
        gray = df.loc[ind, 'is_gray']
    else:
        gray = is_gray(image)
    mask = df.loc[ind, mask_col]
    if df.loc[ind, 'nb_instance']:    
        mask = mask_12m(mask)
        boundary = np.sum([find_boundaries(mask[:,:,nb], mode='inner') for 
                           nb in range(mask.shape[2])], 0).astype(np.uint8)
    
        image_b[boundary>0]= cval if gray else [cval,0, 0]
    
    id = df.loc[ind, 'id'] if name_id else ind
    id = id if tag is None else '{}_{}'.format(id, tag)
    if 'cut_id' in df.columns:
        name = '{}_{}_{}'.format(id, df.loc[ind, 'cut_id'], df.loc[ind, 'nb_instance'])
    else: 
        name = '{}_{}'.format(id, df.loc[ind, 'nb_instance'])

    plt.imsave(os.path.join(save_dir, name+'_boundary.png'), image_b, 
               cmap=plt.cm.gray if gray else None)
    plt.imsave(os.path.join(save_dir, name+'.png'), image, 
               cmap = plt.cm.gray if gray else None) 
Example #4
Source File: data.py    From 2018DSB with MIT License 5 votes vote down vote up
def get_isolated(masks):
    res=[]
    for mask in masks:
        nb_mask = mask.max()
        inds = np.zeros((nb_mask+1), dtype='uint8')
        for i in range(nb_mask):
            boundary = find_boundaries(mask==i+1, connectivity=2, mode='outer')
            if np.any(mask[boundary]):
                inds[i+1]=1
        res.append(inds)
    return res 
Example #5
Source File: train_LA_BD.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    """

    img_gt = img_gt.astype(np.uint8)

    gt_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(1, out_shape[1]):
            posmask = img_gt[b]
            negmask = 1-posmask
            posdis = distance(posmask)
            negdis = distance(negmask)
            boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
            sdf = negdis - posdis
            sdf[boundary==1] = 0
            gt_sdf[b][c] = sdf

    return gt_sdf 
Example #6
Source File: train_LA_BD.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf1_1(img_gt, out_shape):
    """
    compute the normalized signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1, 1]
    """

    img_gt = img_gt.astype(np.uint8)

    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
            # ignore background
        for c in range(1, out_shape[1]):
            posmask = img_gt[b]
            negmask = 1-posmask
            posdis = distance(posmask)
            negdis = distance(negmask)
            boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
            sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
            sdf[boundary==1] = 0
            normalized_sdf[b][c] = sdf
            assert np.min(sdf) == -1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))
            assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #7
Source File: train_LA_Rec_SDF_L1PlusL2.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #8
Source File: train_LITS_Rec_SDF_L1.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf

    return normalized_sdf 
Example #9
Source File: train_LITS_Rec_SDF_L2.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf

    return normalized_sdf 
Example #10
Source File: train_LA_MultiHead_SDF_L2.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #11
Source File: train_LiTS_MultiHead_SDF_L1.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis))*negmask - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))*posmask
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf

    return normalized_sdf 
Example #12
Source File: train_LA_Rec_SDF_L2.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #13
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 #14
Source File: losses.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf1_1(segmentation):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, class, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdm(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation

    """
    # print(type(segmentation), segmentation.shape)

    segmentation = segmentation.astype(np.uint8)
    if len(segmentation.shape) == 4: # 3D image
        segmentation = np.expand_dims(segmentation, 1)
    normalized_sdf = np.zeros(segmentation.shape)
    if segmentation.shape[1] == 1:
        dis_id = 0
    else:
        dis_id = 1
    for b in range(segmentation.shape[0]): # batch size
        for c in range(dis_id, segmentation.shape[1]): # class_num
            # ignore background
            posmask = segmentation[b][c]
            negmask = ~posmask
            posdis = distance(posmask)
            negdis = distance(negmask)
            boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
            sdf = negdis/np.max(negdis) - posdis/np.max(posdis)
            sdf[boundary>0] = 0
            normalized_sdf[b][c] = sdf
    return normalized_sdf 
Example #15
Source File: losses.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf01(segmentation):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, class, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdm(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation

    """
    # print(type(segmentation), segmentation.shape)

    segmentation = segmentation.astype(np.uint8)
    if len(segmentation.shape) == 4: # 3D image
        segmentation = np.expand_dims(segmentation, 1)
    normalized_sdf = np.zeros(segmentation.shape)
    if segmentation.shape[1] == 1:
        dis_id = 0
    else:
        dis_id = 1
    for b in range(segmentation.shape[0]): # batch size
        for c in range(dis_id, segmentation.shape[1]): # class_num
            # ignore background
            posmask = segmentation[b][c]
            negmask = ~posmask
            posdis = distance(posmask)
            negdis = distance(negmask)
            boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
            sdf = negdis/np.max(negdis)/2 - posdis/np.max(posdis)/2 + 0.5
            sdf[boundary>0] = 0.5
            normalized_sdf[b][c] = sdf
    return normalized_sdf 
Example #16
Source File: train_LA_AAAISDF.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #17
Source File: train_LITS_BD.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    """

    img_gt = img_gt.astype(np.uint8)

    gt_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(1, out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = negdis - posdis
                sdf[boundary==1] = 0
                gt_sdf[b][c] = sdf

    return gt_sdf 
Example #18
Source File: train_LITS_BD.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf1_1(img_gt, out_shape):
    """
    compute the normalized signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1, 1]
    """

    img_gt = img_gt.astype(np.uint8)

    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
            # ignore background
        for c in range(1, out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf

    return normalized_sdf 
Example #19
Source File: train_LA_SDF.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf1_1(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdm(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation

    """
    # print(type(segmentation), segmentation.shape)

    img_gt = img_gt.astype(np.uint8)
    if img_gt.shape != out_shape:
        img_gt = np.expand_dims(img_gt, 1)
    print('img_gt.shape: ', img_gt.shape)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
            # ignore background
        for c in range(out_shape[1]):
            posmask = img_gt[b][c]
            negmask = 1-posmask
            posdis = distance(posmask)
            negdis = distance(negmask)
            boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
            sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
            sdf[boundary==1] = 0
            normalized_sdf[b][c] = sdf
            assert np.min(sdf) == -1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))
            assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #20
Source File: train_LA_AAAISDF_L1.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #21
Source File: train_LA_MultiHead_SDF_L1PlusL2.py    From SegWithDistMap with Apache License 2.0 5 votes vote down vote up
def compute_sdf(img_gt, out_shape):
    """
    compute the signed distance map of binary mask
    input: segmentation, shape = (batch_size,c, x, y, z)
    output: the Signed Distance Map (SDM) 
    sdf(x) = 0; x in segmentation boundary
             -inf|x-y|; x in segmentation
             +inf|x-y|; x out of segmentation
    normalize sdf to [-1,1]

    """

    img_gt = img_gt.astype(np.uint8)
    normalized_sdf = np.zeros(out_shape)

    for b in range(out_shape[0]): # batch size
        for c in range(out_shape[1]):
            posmask = img_gt[b].astype(np.bool)
            if posmask.any():
                negmask = ~posmask
                posdis = distance(posmask)
                negdis = distance(negmask)
                boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
                sdf = (negdis-np.min(negdis))/(np.max(negdis)-np.min(negdis)) - (posdis-np.min(posdis))/(np.max(posdis)-np.min(posdis))
                sdf[boundary==1] = 0
                normalized_sdf[b][c] = sdf
                assert np.min(sdf) == -1.0, print(np.min(posdis), np.max(posdis), np.min(negdis), np.max(negdis))
                assert np.max(sdf) ==  1.0, print(np.min(posdis), np.min(negdis), np.max(posdis), np.max(negdis))

    return normalized_sdf 
Example #22
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def figure_segm_boundary_dist(segm_ref, segm, subfig_size=9):
    """ visualise the boundary distances between two segmentation

    :param ndarray segm_ref: reference segmentation
    :param ndarray segm: estimated segmentation
    :param int subfig_size: maximal sub-figure size
    :return Figure:

    >>> seg = np.zeros((100, 100))
    >>> seg[35:80, 10:65] = 1
    >>> fig = figure_segm_boundary_dist(seg, seg.T)
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    assert segm_ref.shape == segm.shape, \
        'ref segm %r and segm %r should match' % (segm_ref.shape, segm.shape)
    segr_boundary = segmentation.find_boundaries(segm_ref, mode='thick')
    segm_boundary = segmentation.find_boundaries(segm, mode='thick')
    segm_distance = ndimage.distance_transform_edt(~segm_boundary)

    norm_size = np.array(segm_ref.shape[:2]) / float(np.max(segm_ref.shape))
    fig_size = norm_size[::-1] * subfig_size * np.array([2, 1])
    fig, axarr = plt.subplots(ncols=2, figsize=fig_size)

    axarr[0].set_title('boundary distances with reference contour')
    im = axarr[0].imshow(segm_distance, cmap=plt.cm.Greys)
    plt.colorbar(im, ax=axarr[0])
    axarr[0].contour(segm_ref, cmap=plt.cm.jet)

    segm_distance[~segr_boundary] = 0
    axarr[1].set_title('distance projected to ref. boundary')
    im = axarr[1].imshow(segm_distance, cmap=plt.cm.Reds)
    plt.colorbar(im, ax=axarr[1])

    return fig 
Example #23
Source File: labeling.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_boundary_distances(segm_ref, segm):
    """ compute distances among boundaries of two segmentation

    :param ndarray segm_ref: reference segmentation
    :param ndarray segm: input segmentation
    :return ndarray:

    >>> segm_ref = np.zeros((6, 10), dtype=int)
    >>> segm_ref[3:4, 4:5] = 1
    >>> segm = np.zeros((6, 10), dtype=int)
    >>> segm[:, 2:9] = 1
    >>> pts, dist = compute_boundary_distances(segm_ref, segm)
    >>> pts
    array([[2, 4],
           [3, 3],
           [3, 4],
           [3, 5],
           [4, 4]])
    >>> dist.tolist()
    [2.0, 1.0, 2.0, 3.0, 2.0]
    """
    assert segm_ref.shape == segm.shape, 'Ref. segm %r and segm %r should match' \
                                         % (segm_ref.shape, segm.shape)
    grid_y, grid_x = np.meshgrid(range(segm_ref.shape[1]),
                                 range(segm_ref.shape[0]))
    segr_boundary = sk_segm.find_boundaries(segm_ref, mode='thick')
    points = np.array([grid_x[segr_boundary].ravel(),
                       grid_y[segr_boundary].ravel()]).T
    segm_boundary = sk_segm.find_boundaries(segm, mode='thick')
    segm_distance = ndimage.distance_transform_edt(~segm_boundary)
    dist = segm_distance[segr_boundary].ravel()

    assert len(points) == len(dist), \
        'number of points and distances should be equal'
    return points, dist 
Example #24
Source File: lcfcn_loss.py    From LCFCN with Apache License 2.0 5 votes vote down vote up
def watersplit(_probs, _points):
    points = _points.copy()

    points[points != 0] = np.arange(1, points.sum()+1)
    points = points.astype(float)

    probs = ndimage.black_tophat(_probs.copy(), 7)
    seg = watershed(probs, points)

    return find_boundaries(seg) 
Example #25
Source File: mask_pos.py    From 2018DSB with MIT License 4 votes vote down vote up
def mask_localpos(mask, tp='all', labels0=None, coords=None):
    """Compute bounding boxes from masks.
    mask: [height, width, num_instances]. Mask pixels are either 1 or 0.

    Returns: bbox array [num_instances, (y1, x1, y2, x2)].
    """
    nb_mask = mask.max()
    nb_feature = 4 if tp=='all' else 2
    nb_start = 2 if tp=='di' else 0
    if nb_mask==0:
        return np.zeros(mask.shape+(nb_feature,), dtype='float32')
    else:
        if labels0 is None:
            labels0 = get_labels(mask.shape[0])
        if coords is None:
            coords = get_coords(mask.shape[0])
        mask0 = np.zeros((mask.shape[0]+2, mask.shape[0]+2), dtype=mask.dtype)
        mask0[1:-1,1:-1] = mask
        
        local_mask = np.zeros(mask.shape+(8,), dtype='float32')
        bbox = extract_bboxes_4di(mask0, tp)   
        for i in range(nb_mask):
            y1, y2, x1, x2 = bbox[i, :4]
            boundary = find_boundaries(mask0[y1-1:y2+2, x1-1:x2+2]==i+1, mode='outer',
                                       connectivity=2)
            boundary_label = labels0[y1-1:y2+2,x1-1:x2+2][boundary]
            mask_label = labels0[y1:y2+1,x1:x2+1][mask0[y1:y2+1,x1:x2+1]==i+1]
            index_mask = mask==i+1
            for nb in range(4):
                boundary_sort = np.sort(boundary_label[:,nb])
                order = np.searchsorted(boundary_sort, mask_label[:,nb], side='right')
                local_mask[index_mask, 2*nb] = coords[(boundary_sort[order-1]+1).astype('int32'), nb]
                local_mask[index_mask, 2*nb+1] = coords[np.ceil(boundary_sort[order]-1).astype('int32'), nb]
                

        h, w = mask.shape
        x, y = np.meshgrid(np.arange(w), np.arange(h))
        x, y = x.astype('float32'), y.astype('float32')
        x[mask==0]=0
        y[mask==0]=0
        dr,dl = x+y, y-x
  
        res = [y, x, dr, dl][nb_start:nb_start+nb_feature]   
        
        index_mask = mask!=0
        mask_x, mask_y = x[index_mask].astype('int32'), y[index_mask].astype('int32')
        for i in range(nb_feature):
            delta = local_mask[mask_y, mask_x,2*i+1]-local_mask[mask_y, mask_x, 2*i]
            if np.sum(delta==0):
                mask_x_nb, mask_y_nb = mask_x[delta!=0], mask_y[delta!=0]
                res[i][mask_y_nb, mask_x_nb] = 2*(res[i][mask_y_nb, mask_x_nb] - 
                                           local_mask[mask_y_nb, mask_x_nb,2*i])/delta[delta!=0]-1
                res[i][mask_y[delta==0], mask_x[delta==0]] = 1e-7
            else:
                res[i][mask_y, mask_x] = 2*(res[i][mask_y, mask_x] - 
                                           local_mask[mask_y, mask_x,2*i])/delta-1
        return np.stack(res, axis=2) 
Example #26
Source File: compute_scores.py    From netwarp_public with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def eval_seg_parallel(datatype, gt_label_folder, result_label_folder, imgname, trimap, count):
    max_label = 34
    ignore_label = 255

    tp = np.zeros((max_label))
    fp = np.zeros((max_label))
    fn = np.zeros((max_label))

    edge_tp = np.zeros((max_label))
    edge_fp = np.zeros((max_label))
    edge_fn = np.zeros((max_label))

    print str(count) + ". Image Name: " + imgname
    gt_file = gt_label_folder + imgname + '.png'
    gt_file = os.path.join(gt_label_folder, datatype.lower(), imgname.split('_')[0], imgname + '_gtFine_labelTrainIds.png')
    result_file = result_label_folder + imgname + '.png'

    gt_labels = np.array(Image.open(gt_file))
    gt_labels = get_reindexed_image(gt_labels)
    result_labels = np.array(Image.open(result_file))

    if (np.max(result_labels) > (max_label - 1) and np.max(result_labels)!=255):
        print('Result has invalid labels: ', np.max(result_labels))
    else:
        edge_mask = find_boundaries(gt_labels, connectivity=1)
        edge_mask = binary_dilation(edge_mask, np.ones((trimap, trimap)))
        edge_gt_labels = gt_labels.copy()
        edge_result_labels = result_labels.copy()
        edge_gt_labels[np.equal(edge_mask,0)] = ignore_label
        edge_result_labels[np.equal(edge_mask,0)] = ignore_label
        # For each class
        for class_id in range(0, max_label):
            class_gt = np.equal(gt_labels, class_id)
            class_result = np.equal(result_labels, class_id)
            # import pdb; pdb.set_trace();
            class_result[np.equal(gt_labels, ignore_label)] = 0
            tp[class_id] = tp[class_id] +\
                np.count_nonzero(class_gt & class_result)
            fp[class_id] = fp[class_id] +\
                np.count_nonzero(class_result & ~class_gt)
            fn[class_id] = fn[class_id] +\
                np.count_nonzero(~class_result & class_gt)

            edge_class_gt = np.equal(edge_gt_labels, class_id)
            edge_class_result = np.equal(edge_result_labels, class_id)
            # import pdb; pdb.set_trace();
            edge_class_result[np.equal(edge_gt_labels, ignore_label)] = 0
            edge_tp[class_id] = edge_tp[class_id] +\
                np.count_nonzero(edge_class_gt & edge_class_result)
            edge_fp[class_id] = edge_fp[class_id] +\
                np.count_nonzero(edge_class_result & ~edge_class_gt)
            edge_fn[class_id] = edge_fn[class_id] +\
                np.count_nonzero(~edge_class_result & edge_class_gt)
    return [tp, fp, fn, edge_tp,  edge_fp, edge_fn] 
Example #27
Source File: data.py    From 2018DSB with MIT License 4 votes vote down vote up
def get_mark_properties(images, masks):
    sharps = []
    roughs = []
    intens = []
    areas  = []
    limits = []
    no_boarder=np.zeros_like(masks[0])
    no_boarder[1:-1,1:-1]=1
    w, h = np.shape(masks)[1:]
    xs, ys = np.meshgrid(np.arange(w), np.arange(h))
    for image, mask in zip(images, masks):
        nb_mask = mask.max()
        intensity=np.zeros((nb_mask+1),dtype='float32')
        sharpness=np.zeros((nb_mask+1),dtype='float32')
        roughness=np.zeros((nb_mask+1),dtype='float32')
        area_mask=np.zeros((nb_mask+1),dtype='float32')
        limits_mask = []
        limits_mask.append(np.asarray([0,h-1,0,w-1]))
        gray_scale = np.mean(image, axis = 2)
        intensity[0]=np.mean(gray_scale[mask==0])
        roughness[0]=np.std(gray_scale[mask==0])
        area_mask[0] =np.sum(mask==0)
        for i in range(1,nb_mask+1):
            intensity[i] = np.mean(gray_scale[mask==i])
            roughness[i] = np.std(gray_scale[mask==i])
            boundary = find_boundaries(mask==i, connectivity=2, mode='inner') 
            limits_mask.append(np.asarray([np.min(xs[boundary])-1,np.max(xs[boundary])+2,\
                                           np.min(ys[boundary])-1,np.max(ys[boundary])+2]))            
            boundary = boundary * no_boarder >0
            gradients = []
            for y,x in zip(xs[boundary],ys[boundary]):
                pass
                gx = gray_scale[x+1,y  ] * 2+  gray_scale[x+1,y+1] + gray_scale[x+1,y-1] -\
                     gray_scale[x-1,y  ] * 2-  gray_scale[x-1,y+1] - gray_scale[x-1,y-1]
                gy = gray_scale[x  ,y+1] * 2+  gray_scale[x+1,y+1] + gray_scale[x-1,y+1] -\
                     gray_scale[x  ,y-1] * 2-  gray_scale[x+1,y-1] - gray_scale[x-1,y-1]
                gradients.append(np.sqrt(gx*gx + gy*gy))
            sharpness[i] = np.mean(gradients)                                 
            area_mask[i] = np.sum(mask==i)            
        sharps.append(sharpness)
        roughs.append(roughness)
        intens.append(intensity)
        areas.append(area_mask)
        limits.append(limits_mask)        
    return sharps, roughs, intens, areas, limits 
Example #28
Source File: data_segmentation.py    From pytorch_connectomics with MIT License 4 votes vote down vote up
def weight_unet2d(seg, w0=10, sigma=5):
    """
    Generate the weight maps as specified in the UNet paper
    for a multi-instance seg map.
    
    Parameters
    ----------
    seg: array-like
        A 2D array of shape (image_height, image_width)

    Returns
    -------
    array-like
        A 2D array of shape (image_height, image_width)
    
    """    
    seg_ids = np.unique(seg)
    seg_ids = seg_ids[seg_ids>0]
    nrows, ncols = seg.shape    
    distMap = np.ones((nrows * ncols, 2))*(nrows+ncols)
    X1, Y1 = np.meshgrid(range(ncols), range(nrows))
    X1, Y1 = X1.reshape(1,-1), Y1.reshape(1,-1)
    for i, seg_id in enumerate(seg_ids):
        # find the boundary of each mask,
        # compute the distance of each pixel from this boundary
        bounds = find_boundaries(seg==seg_id, mode='inner')
        Y2, X2 = np.nonzero(bounds)
        dist = np.sqrt((X2.reshape(-1,1) - X1) ** 2 + (Y2.reshape(-1,1) - Y1) ** 2).min(axis=0)
        m1 = dist<distMap[:,0]
        distMap[m1,1] = distMap[m1,0]
        distMap[m1,0] = dist[m1]
        m2 = (dist>distMap[:,0])*(dist<distMap[:,1])*np.logical_not(m1)
        distMap[m2,1] = dist[m2]
    if len(seg_ids) == 1:
        loss_map = w0 * np.exp((-1 * distMap[:,0] ** 2) / (2 * (sigma ** 2)))
    else:        
        loss_map = w0 * np.exp((-1 * distMap.sum(axis=1) ** 2) / (2 * (sigma ** 2)))
    
    loss_map = loss_map.reshape((nrows,ncols))
    # add class weight map    
    wc_1 = (seg==0).mean()
    wc_0 = 1 - wc_1
    loss_map[seg>0] += wc_1
    loss_map[seg==0] += wc_0
    return loss_map