Python skimage.segmentation.mark_boundaries() Examples

The following are 10 code examples of skimage.segmentation.mark_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: _ml.py    From pydatalab with Apache License 2.0 6 votes vote down vote up
def visualize(self, label_index):
    image, mask = self._exp.get_image_and_mask(
        label_index,
        positive_only=self._positive_only,
        num_features=self._num_features, hide_rest=False)
    fig = plt.figure()
    fig.suptitle('Image Column "%s"' % self._col_name, fontsize=16)
    plt.grid(False)
    plt.imshow(mark_boundaries(image, mask))
    plt.close(fig)
    IPython.display.display(fig) 
Example #2
Source File: model.py    From facade-segmentation with MIT License 5 votes vote down vote up
def plot(self, overlay_alpha=0.5):
        import pylab as pl
        #pl.imshow(self.image)
        tinted = ((1-overlay_alpha)*self.image
                  + overlay_alpha*colorize(np.argmax(self.features, 0), self.colors))
        from skimage.segmentation import mark_boundaries
        tinted = mark_boundaries(tinted.clip(0, 255).astype(np.uint8), np.argmax(self.features, 0))
        pl.imshow(tinted) 
Example #3
Source File: MR.py    From mr_saliency with GNU General Public License v2.0 5 votes vote down vote up
def MR_showsuperpixel(self,img=None):
        if img == None:
            img = cv2.cvtColor(camera(),cv2.COLOR_RGB2BGR)
        img = self._MR_saliency__MR_readimg(img)
        labels = self._MR_saliency__MR_superpixel(img)

        plt.axis('off')
        plt.imshow(mark_boundaries(img,labels))
        plt.show() 
Example #4
Source File: run_overlap_images_segms.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visualise_overlap(path_img, path_seg, path_out,
                      b_img_scale=BOOL_IMAGE_RESCALE_INTENSITY,
                      b_img_contour=BOOL_SAVE_IMAGE_CONTOUR,
                      b_relabel=BOOL_ANNOT_RELABEL,
                      segm_alpha=MIDDLE_ALPHA_OVERLAP):
    img, _ = tl_data.load_image_2d(path_img)
    seg, _ = tl_data.load_image_2d(path_seg)

    # normalise alpha in range (0, 1)
    segm_alpha = tl_visu.norm_aplha(segm_alpha)

    if b_relabel:
        seg, _, _ = segmentation.relabel_sequential(seg)

    if img.ndim == 2:  # for gray images of ovary
        img = np.rollaxis(np.tile(img, (3, 1, 1)), 0, 3)

    if b_img_scale:
        p_low, p_high = np.percentile(img, q=(3, 98))
        # plt.imshow(255 - img, cmap='Greys')
        img = exposure.rescale_intensity(img, in_range=(p_low, p_high),
                                         out_range='uint8')

    if b_img_contour:
        path_im_visu = os.path.splitext(path_out)[0] + '_contour.png'
        img_contour = segmentation.mark_boundaries(img[:, :, :3], seg,
                                                   color=COLOR_CONTOUR, mode='subpixel')
        plt.imsave(path_im_visu, img_contour)
    # else:  # for colour images of disc
    #     mask = (np.sum(img, axis=2) == 0)
    #     img[mask] = [255, 255, 255]

    fig = tl_visu.figure_image_segm_results(img, seg, SIZE_SUB_FIGURE,
                                            mid_labels_alpha=segm_alpha,
                                            mid_image_gray=MIDDLE_IMAGE_GRAY)
    fig.savefig(path_out)
    plt.close(fig) 
Example #5
Source File: nlc.py    From videoseg with MIT License 5 votes vote down vote up
def superpixels(im, maxsp=200, vis=False, redirect=False):
    """
    Get Slic Superpixels
    Input: im: (h,w,c) or (n,h,w,c): 0-255: np.uint8: RGB
    Output: sp: (h,w) or (n,h,w): 0-indexed regions, #regions <= maxsp
    """
    sTime = time.time()
    if im.ndim < 4:
        im = im[None, ...]
    sp = np.zeros(im.shape[:3], dtype=np.int)
    for i in range(im.shape[0]):
        # slic needs im: float in [0,1]
        sp[i] = slic(im[i].astype(np.float) / 255., n_segments=maxsp, sigma=5)
        if not redirect:
            sys.stdout.write('Superpixel computation: [% 5.1f%%]\r' %
                                (100.0 * float((i + 1) / im.shape[0])))
            sys.stdout.flush()
    eTime = time.time()
    print('Superpixel computation finished: %.2f s' % (eTime - sTime))

    if vis and False:
        # TODO: set directory to save
        from skimage.segmentation import mark_boundaries
        for i in range(im.shape[0]):
            Image.fromarray((mark_boundaries(im[i], sp[i]))).save('.jpg')

    if im.ndim < 4:
        return sp[0]
    return sp 
Example #6
Source File: segmentation.py    From graph-based-image-classification with MIT License 4 votes vote down vote up
def draw_image(image, segmentation, adjacency, neighborhood):
    neighborhood = list(neighborhood)

    image = mark_boundaries(image, segmentation, (0, 0, 0))

    graph = nx.from_numpy_matrix(adjacency)

    segmentation += np.ones_like(segmentation)
    segments = regionprops(segmentation)

    # Save the centroids in the node properties.
    for (n, data), segment in zip(graph.nodes_iter(data=True), segments):
        data['centroid'] = segment['centroid']

    # Iterate over all edges and draw them.
    for n1, n2, data in graph.edges_iter(data=True):
        y1, x1 = map(int, graph.node[n1]['centroid'])
        y2, x2 = map(int, graph.node[n2]['centroid'])
        line = draw.line(y1, x1, y2, x2)

        n1_idx = neighborhood.index(n1) if n1 in neighborhood else -1
        n2_idx = neighborhood.index(n2) if n2 in neighborhood else -1
        if abs(n1_idx - n2_idx) == 1 and n1_idx != -1 and n2_idx != -1:
            image[line] = [1, 0, 0]
        else:
            image[line] = [0, 1, 0]

    # Draw a circle at the root node.
    for i in range(0, len(neighborhood)):
        if neighborhood[i] < 0:
            continue

        y1, x1 = graph.node[neighborhood[i]]['centroid']
        circle = draw.circle(y1, x1, 2)

        if i == 0:
            image[circle] = [1, 1, 0]
        else:
            j = (i-1)/(len(neighborhood) - 2)
            image[circle] = [j, j, j]

    return image 
Example #7
Source File: run_segm_slic_classif_graphcut.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def load_image_annot_compute_features_labels(idx_row, params,
                                             show_debug_imgs=SHOW_DEBUG_IMAGES):
    """ load image and annotation, and compute superpixel features and labels

    :param (int, {...}) idx_row: row from table with paths
    :param dict params: segmentation parameters
    :param bool show_debug_imgs: whether show debug images
    :return (...):
    """
    def _path_out_img(params, dir_name, name):
        return os.path.join(params['path_exp'], dir_name, name + '.png')

    idx, row = idx_row
    idx_name = get_idx_name(idx, row['path_image'])
    img = load_image(row['path_image'], params['img_type'])
    annot = load_image(row['path_annot'], '2d_segm')
    logging.debug('.. processing: %s', idx_name)
    assert img.shape[:2] == annot.shape[:2], \
        'individual size of image %r and seg_pipe %r for "%s" - "%s"' % \
        (img.shape, annot.shape, row['path_image'], row['path_annot'])
    if show_debug_imgs:
        plt.imsave(_path_out_img(params, FOLDER_IMAGE, idx_name), img,
                   cmap=plt.cm.gray)
        plt.imsave(_path_out_img(params, FOLDER_ANNOT, idx_name), annot)

    # duplicate gray band to be as rgb
    # if img.ndim == 2:
    #     img = np.rollaxis(np.tile(img, (3, 1, 1)), 0, 3)
    slic = seg_spx.segment_slic_img2d(img, sp_size=params['slic_size'],
                                      relative_compact=params['slic_regul'])
    img = tl_data.convert_img_color_from_rgb(img, params.get('clr_space', 'rgb'))
    logging.debug('computed SLIC with %i labels', slic.max())
    if show_debug_imgs:
        img_rgb = use_rgb_image(img)
        img_slic = segmentation.mark_boundaries(img_rgb, slic,
                                                color=(1, 0, 0),
                                                mode='subpixel')
        plt.imsave(_path_out_img(params, FOLDER_SLIC, idx_name),
                   np.clip(img_slic, 0, 1))
    slic_label_hist = seg_label.histogram_regions_labels_norm(slic, annot)
    labels = np.argmax(slic_label_hist, axis=1)
    slic_annot = labels[slic]
    if show_debug_imgs:
        plt.imsave(_path_out_img(params, FOLDER_SLIC_ANNOT, idx_name),
                   np.clip(slic_annot, 0, slic_annot.max()))

    features, feature_names = seg_fts.compute_selected_features_img2d(
        img, slic, params['features'])
    return idx_name, img, annot, slic, features, labels, slic_label_hist, feature_names 
Example #8
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def figure_segm_graphcut_debug(images, subfig_size=9):
    """ creating subfigure with slic, graph edges and results in the first row
    and individual class unary terms in the second row

    :param dict images: dictionary composed from name and image array
    :param int subfig_size: maximal sub-figure size
    :return Figure:

    >>> images = {
    ...     'image': np.random.random((100, 150, 3)),
    ...     'slic': np.random.randint(0, 2, (100, 150)),
    ...     'slic_mean': np.random.random((100, 150, 3)),
    ...     'img_graph_edges': np.random.random((100, 150, 3)),
    ...     'img_graph_segm': np.random.random((100, 150, 3)),
    ...     'imgs_unary_cost': [np.random.random((100, 150, 3))],
    ... }
    >>> fig = figure_segm_graphcut_debug(images)
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    assert all(n in images for n in [
        'image', 'slic', 'slic_mean', 'img_graph_edges', 'img_graph_segm', 'imgs_unary_cost'
    ]), 'missing keys in debug structure %r' % tuple(images.keys())
    nb_cols = max(3, len(images['imgs_unary_cost']))
    img = images['image']
    if img.ndim == 2:  # for gray images of ovary
        img = color.gray2rgb(img)
    norm_size = np.array(img.shape[:2]) / float(np.max(img.shape))

    fig_size = norm_size[::-1] * subfig_size * np.array([nb_cols, 2])
    fig, axarr = plt.subplots(2, nb_cols, figsize=fig_size)

    img_slic = segmentation.mark_boundaries(img, images['slic'],
                                            mode='subpixel')
    axarr[0, 0].set_title('SLIC')
    axarr[0, 0].imshow(img_slic)
    for i, k in enumerate(['img_graph_edges', 'img_graph_segm']):
        axarr[0, i + 1].set_title(k)
        axarr[0, i + 1].imshow(images[k])
    for i, im_uc in enumerate(images['imgs_unary_cost']):
        axarr[1, i].set_title('unary cost #%i' % i)
        axarr[1, i].imshow(im_uc)

    for j in range(2):
        for i in range(nb_cols):
            axarr[j, i].axis('off')
            axarr[j, i].axes.get_xaxis().set_ticklabels([])
            axarr[j, i].axes.get_yaxis().set_ticklabels([])
    fig.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0.05, hspace=0.05)
    return fig 
Example #9
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def draw_image_segm_points(ax, img, points, labels=None, slic=None,
                           color_slic='w', lut_label_marker=DICT_LABEL_MARKER,
                           seg_contour=None):
    """ on plane draw background image or segmentation, overlap with SLIC
     contours, add contour of adative segmentation like annot. for centers
     plot point with specific property (shape and colour) according label

    :param ax: figure axis
    :param ndarray img: image
    :param list(tuple(int,int)) points: collection of points
    :param list(int) labels: LUT labels for superpixels
    :param ndarray slic: superpixel segmentation
    :param str color_slic: color dor superpixels
    :param dict lut_label_marker: dictionary {int: (str, str)} of label and markers
    :param ndarray seg_contour: segmentation contour

    >>> img = np.random.randint(0, 256, (100, 100))
    >>> points = np.random.randint(0, 100, (25, 2))
    >>> labels = np.random.randint(0, 5, len(points))
    >>> slic = np.random.randint(0, 256, (100, 100))
    >>> draw_image_segm_points(plt.Figure().gca(), img, points, labels, slic)
    """
    # background image or segmentation
    if img.ndim == 2:
        ax.imshow(img, alpha=0.3, cmap=plt.cm.gist_earth)
    else:
        ax.imshow(img)

    if slic is not None:
        ax.contour(slic, levels=np.unique(slic), alpha=0.5, colors=color_slic,
                   linewidths=0.5)
    # fig.gca().imshow(mark_boundaries(img, slic))
    if seg_contour is not None and isinstance(seg_contour, np.ndarray):
        assert img.shape[:2] == seg_contour.shape[:2], \
            'image size %r and segm. %r should match' % (img.shape, seg_contour.shape)
        ax.contour(seg_contour, linewidths=3, levels=np.unique(seg_contour))
    if labels is not None:
        assert len(points) == len(labels), \
            'number of points (%i) and labels (%i) should match' \
            % (len(points), len(labels))
        for lb in lut_label_marker:
            marker, clr = lut_label_marker[lb]
            ax.plot(points[(labels == lb), 1], points[(labels == lb), 0],
                    marker, color=clr)
    else:
        ax.plot(points[:, 1], points[:, 0], 'o', color=COLOR_ORANGE)
    ax.set(xlim=[0, img.shape[1]], ylim=[img.shape[0], 0]) 
Example #10
Source File: Segmentation_Models.py    From brain_segmentation with MIT License 4 votes vote down vote up
def show_segmented_image(self, test_img, modality='t1c', show = False):
        '''
        Creates an image of original brain with segmentation overlay
        INPUT   (1) str 'test_img': filepath to test image for segmentation, including file extension
                (2) str 'modality': imaging modelity to use as background. defaults to t1c. options: (flair, t1, t1c, t2)
                (3) bool 'show': If true, shows output image. defaults to False.
        OUTPUT  (1) if show is True, shows image of segmentation results
                (2) if show is false, returns segmented image.
        '''
        modes = {'flair':0, 't1':1, 't1c':2, 't2':3}

        segmentation = self.predict_image(test_img, show=False)
        img_mask = np.pad(segmentation, (16,16), mode='edge')
        ones = np.argwhere(img_mask == 1)
        twos = np.argwhere(img_mask == 2)
        threes = np.argwhere(img_mask == 3)
        fours = np.argwhere(img_mask == 4)

        test_im = io.imread(test_img)
        test_back = test_im.reshape(5,240,240)[-2]
        # overlay = mark_boundaries(test_back, img_mask)
        gray_img = img_as_float(test_back)

        # adjust gamma of image
        image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
        sliced_image = image.copy()
        red_multiplier = [1, 0.2, 0.2]
        yellow_multiplier = [1,1,0.25]
        green_multiplier = [0.35,0.75,0.25]
        blue_multiplier = [0,0.25,0.9]

        # change colors of segmented classes
        for i in xrange(len(ones)):
            sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
        for i in xrange(len(twos)):
            sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
        for i in xrange(len(threes)):
            sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
        for i in xrange(len(fours)):
            sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier

        if show:
            io.imshow(sliced_image)
            plt.show()

        else:
            return sliced_image