Python skimage.color.gray2rgb() Examples

The following are 21 code examples of skimage.color.gray2rgb(). 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.color , or try the search function .
Example #1
Source File: enhancer_gan.py    From ImageEnhancer with MIT License 6 votes vote down vote up
def _corrupt(self, source):
        """ corrupt the input with specific corruption method
            :param source: original data set
            :return: corrupted data set, if noise type is not defined, the original data set will return
        """
        if self.corrupt_type is None:
            return source
        noised = np.zeros((np.shape(source)[0],) + self.shape['in'])
        for i, raw in enumerate(source):
            if self.corrupt_type == 'GSN':
                noised[i] = random_noise(raw, 'gaussian', var=self.corrupt_ratio)
            elif self.corrupt_type == 'MSN':
                noised[i] = random_noise(raw, 'pepper', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'SPN':
                noised[i] = random_noise(raw, 's&p', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'GSB':
                noised[i] = gaussian(raw, sigma=self.corrupt_ratio, multichannel=True)
            elif self.corrupt_type == 'GRY':
                noised[i] = gray2rgb(rgb2gray(raw))
            elif self.corrupt_type == 'BLK':
                rad = int(self.corrupt_ratio)
                row = random.randint(rad, self.shape['in'][0] - rad - 1)
                col = random.randint(rad, self.shape['in'][1] - rad - 1)
                noised[i] = np.copy(raw)
                noised[i][circle(row, col, self.corrupt_ratio)] = 0
            elif self.corrupt_type == 'ZIP':
                noised[i] = rescale(raw, 0.5, mode='constant')
        return noised 
Example #2
Source File: data_io.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_image(path_image, force_rgb=True):
    """ load the image in value range (0, 1)

    :param str path_image: path to the image
    :param bool force_rgb: convert RGB image
    :return ndarray: np.array<height, width, ch>

    >>> img = np.random.random((50, 50))
    >>> save_image('./test_image.jpg', img)
    >>> img2 = load_image('./test_image.jpg')
    >>> img2.max() <= 1.
    True
    >>> os.remove('./test_image.jpg')
    """
    assert os.path.isfile(path_image), 'missing image "%s"' % path_image
    image = np.array(Image.open(path_image))
    while image.max() > 1.5:
        image = image / 255.
    if force_rgb and (image.ndim == 2 or image.shape[2] == 1):
        image = image[:, :, 0] if image.ndim == 3 else image
        image = gray2rgb(image)
    return image.astype(np.float32) 
Example #3
Source File: segmentation_test.py    From DRFNS with MIT License 6 votes vote down vote up
def output_blob_detection(self, img, blobs):
        colim = color.gray2rgb(img)
        
        for blob in blobs:
            x, y, r = blob
                        
            rr, cc = skimage.draw.circle(x,y,r)
            colorvalue = (255, 0, 0)
            
            if np.min(rr) < 0 or np.min(cc) < 0 or np.max(rr) >= img.shape[0]  or np.max(cc) >= img.shape[1]:
                continue
            
            for i, col in enumerate(colorvalue):
                colim[rr,cc,i] = col
 
        return colim 
Example #4
Source File: generator.py    From ad-versarial with MIT License 6 votes vote down vote up
def get_resized_image(file, ratio):
    img = util.img_as_float(io.imread(file))
    if len(img.shape) >= 3 and img.shape[2] == 4:
        img = color.rgba2rgb(img)
    if len(img.shape) == 2:
        img = color.gray2rgb(img)

    eimg = filters.sobel(color.rgb2gray(img))
    width = img.shape[1]
    height = img.shape[0]

    mode, rm_paths = get_lines_to_remove((width, height), ratio)
    if mode:
        logger.debug("Carving %s %s paths ", rm_paths, mode)
        outh = transform.seam_carve(img, eimg, mode, rm_paths)
        return outh
    else:
        return img 
Example #5
Source File: segmentation_labelling.py    From kaggle-heart with MIT License 5 votes vote down vote up
def add_cross_to_image(im, xx, yy):
    image = color.gray2rgb(im.copy())
    for h in range(-4, 5, 1):
        image[xx,yy+h] = (0, 1, 0)

    for v in range(-4, 5, 1):
        image[xx+v,yy] = (0, 1, 0)
    return image 
Example #6
Source File: c3d.py    From Recipes with MIT License 5 votes vote down vote up
def rgb2caffe(im, out_size=(128, 171)):
    '''
    Converts an RGB image to caffe format and downscales it as needed by C3D

    Parameters
    ----------
    im numpy array
        an RGB image
    downscale

    Returns
    -------
    a caffe image (channel,height, width) in BGR format

    '''
    im=np.copy(im)
    if len(im.shape)==2: # Make sure the image has 3 channels
        im = color.gray2rgb(im)

    h, w, _ = im.shape
    im = skimage.transform.resize(im, out_size, preserve_range=True)
    im = np.swapaxes(np.swapaxes(im, 1, 2), 0, 1)

    # Convert to BGR
    im = im[::-1, :, :]

    return np.array(im,theano.config.floatX) 
Example #7
Source File: training_utils.py    From deep-koalarization with MIT License 5 votes vote down vote up
def l_to_rgb(img_l):
    """
    Convert a numpy array (l channel) into an rgb image
    :param img_l:
    :return:
    """
    lab = np.squeeze(255 * (img_l + 1) / 2)
    return color.gray2rgb(lab) / 255 
Example #8
Source File: enhancer.py    From ImageEnhancer with MIT License 5 votes vote down vote up
def _corrupt(self, source):
        """ corrupt the input with specific corruption method
            :param source: original data set
            :return: corrupted data set, if noise type is not defined, the original data set will return
        """
        if self.corrupt_type is None:
            return source
        noised = np.zeros((np.shape(source)[0],) + self.shape['in'])
        for i, raw in enumerate(source):
            if self.corrupt_type == 'GSN':
                noised[i] = random_noise(raw, 'gaussian', var=self.corrupt_ratio)
            elif self.corrupt_type == 'MSN':
                noised[i] = random_noise(raw, 'pepper', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'SPN':
                noised[i] = random_noise(raw, 's&p', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'GSB':
                noised[i] = gaussian(raw, sigma=self.corrupt_ratio, multichannel=True)
            elif self.corrupt_type == 'GRY':
                noised[i] = gray2rgb(rgb2gray(raw))
            elif self.corrupt_type == 'BLK':
                rad = int(self.corrupt_ratio)
                row = random.randint(rad, self.shape['in'][0] - rad - 1)
                col = random.randint(rad, self.shape['in'][1] - rad - 1)
                noised[i] = np.copy(raw)
                noised[i][circle(row, col, self.corrupt_ratio)] = 0
            elif self.corrupt_type == 'ZIP':
                noised[i] = rescale(raw, 0.5, mode='constant')
        return noised 
Example #9
Source File: mc_dataset.py    From DCCM with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, idx):
		filename = self.root_dir + '/' + self.metas[idx][0]
		cls = self.metas[idx][1]
		img = io.imread(filename)
		img = color.gray2rgb(img)
		if self.transform:
			img = self.transform(img)
		return img, cls 
Example #10
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def figure_used_samples(img, labels, slic, used_samples, fig_size=12):
    """ draw used examples (superpixels)

    :param ndarray img: input image for background
    :param list(int) labels: labels associated for superpixels
    :param ndarray slic: superpixel segmentation
    :param list(bool) used_samples: used samples for training
    :param int fig_size: figure size
    :return Figure:

    >>> img = np.random.random((50, 75, 3))
    >>> labels = [-1, 0, 2]
    >>> used = [1, 0, 0]
    >>> seg = np.random.randint(0, 3, img.shape[:2])
    >>> fig = figure_used_samples(img, labels, seg, used)
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    w_samples = np.asarray(used_samples)[slic]
    img = color.gray2rgb(img) if img.ndim == 2 else img

    fig, axarr = create_figure_by_image(img.shape[:2], fig_size,
                                        nb_subfigs=2, extend=0.15)
    axarr[0].imshow(np.asarray(labels)[slic], cmap=plt.cm.jet)
    axarr[0].contour(slic, levels=np.unique(slic), colors='w', linewidths=0.5)
    axarr[0].axis('off')

    axarr[1].imshow(img)
    axarr[1].contour(slic, levels=np.unique(slic), colors='w', linewidths=0.5)
    cax = axarr[1].imshow(w_samples, cmap=plt.cm.RdYlGn, vmin=0, vmax=1, alpha=0.5)
    cbar = plt.colorbar(cax, ticks=[0, 1], boundaries=[-0.5, 0.5, 1.5])
    cbar.ax.set_yticklabels(['drop', 'used'])
    axarr[1].axis('off')

    fig.tight_layout()
    return fig 
Example #11
Source File: run_segm_slic_classif_graphcut.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def use_rgb_image(img, clr='rgb'):
    # clr = params.get('clr_space', 'rgb').lower()
    if img.ndim == 3 and img.shape[-1] in (3, 4):
        img_rgb = tl_data.convert_img_color_to_rgb(img, clr)
    elif img.ndim == 2:
        img_rgb = sk_color.gray2rgb(img)
    else:
        img_rgb = img.copy()
    return img_rgb 
Example #12
Source File: segmentation_test.py    From DRFNS with MIT License 5 votes vote down vote up
def overlay(self, img, imbin, contour=False):
        colim = color.gray2rgb(img)
        colorvalue = (0, 100, 200)
        if contour:
            se = morphology.diamond(2)
            ero = morphology.erosion(imbin, se)
            grad = imbin - ero
            colim[grad > 0] = colorvalue
        else:
            colim[imbin>0] = colorvalue
            
        return colim 
Example #13
Source File: data_augmentation.py    From dataset_loaders with GNU General Public License v3.0 5 votes vote down vote up
def my_label2rgboverlay(labels, cmap, image, bglabel=None,
                        bg_color=(0., 0., 0.), alpha=0.2):
    '''Superimpose a mask over an image

    Convert a label mask to RGB applying a color map and superimposing it
    over an image as a transparent overlay'''
    image_float = gray2rgb(img_as_float(rgb2gray(image)))
    label_image = my_label2rgb(labels, cmap, bglabel=bglabel,
                               bg_color=bg_color)
    output = image_float * alpha + label_image * (1 - alpha)
    return output 
Example #14
Source File: anno_helper.py    From lost with MIT License 5 votes vote down vote up
def crop_boxes(annos, types, img, context=0.0, draw_annotations=False):
    '''Crop a bounding boxes for TwoDAnnos from image.
    
    Args:
        annos (list): List of annotations.
        types (list): List of types.
        img (numpy.array): The image where boxes should be cropped from.
        context (float): The context that should be added to the box.
        draw_annotations (bool): If true, annotation will be painted inside
            the crop.
    
    Return:
        (list of numpy.array, list of list of float): 
            A tuple that contains a list of image crops and a 
            list of bboxes [[xc,yc,w,h],...]
    '''
    if annos:
        crops = []
        new_img = img
        anno_boxes = calc_box_for_anno(annos, types)
        boxes = trans_boxes_to(anno_boxes)
        if len(img.shape) < 3:
            img = gray2rgb(img)
        img_h, img_w, _ = img.shape
        boxes = to_abs(boxes, ['bbox']*len(boxes), (img_w,img_h))
        if context != 0.0:
            boxes = _add_context(boxes, context, (img_w, img_h))
        boxes = np.array(boxes, dtype=int).tolist()
        for idx, box in enumerate(boxes):
            if draw_annotations:
                new_img = img.copy()
                draw_annos([annos[idx]], [types[idx]], new_img)
            # image[y_min:y_max, x_min:x_max]
            crops.append(new_img[box[1]:box[3], box[0]:box[2]])
        return crops, anno_boxes
    else:
        return [], [] 
Example #15
Source File: draw.py    From skan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _normalise_image(image, *, image_cmap=None):
    image = img_as_float(image)
    if image.ndim == 2:
        if image_cmap is None:
            image = gray2rgb(image)
        else:
            image = plt.get_cmap(image_cmap)(image)[..., :3]
    return image 
Example #16
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def figure_image_segm_results(img, seg, subfig_size=9, mid_labels_alpha=0.2,
                              mid_image_gray=True):
    """ creating subfigure with original image, overlapped segmentation contours
    and clean result segmentation...
    it turns the sequence in vertical / horizontal according major image dim

    :param ndarray img: image as background
    :param ndarray seg: segmentation
    :param int subfig_size: max image size
    :param fool mid_image_gray: used color image as bacround in middele
    :param float mid_labels_alpha: alpha for middle segmentation overlap
    :return Figure:

    >>> img = np.random.random((100, 150, 3))
    >>> seg = np.random.randint(0, 2, (100, 150))
    >>> fig = figure_image_segm_results(img, seg)
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    assert img.shape[:2] == seg.shape[:2], \
        'different image %r & seg_pipe %r sizes' % (img.shape, seg.shape)
    if img.ndim == 2:  # for gray images of ovary
        # img = np.rollaxis(np.tile(img, (3, 1, 1)), 0, 3)
        img = color.gray2rgb(img)

    fig, axarr = create_figure_by_image(img.shape[:2], subfig_size,
                                        nb_subfigs=3)
    axarr[0].set_title('original image')
    axarr[0].imshow(img)

    # visualise the 3th label
    axarr[1].set_title('original image w. segment overlap')
    img_bg = color.rgb2gray(img) if mid_image_gray else img
    axarr[1].imshow(img_bg, cmap=plt.cm.Greys_r)
    axarr[1].imshow(seg, alpha=mid_labels_alpha, cmap=plt.cm.jet)
    axarr[1].contour(seg, levels=np.unique(seg), linewidths=2, cmap=plt.cm.jet)

    axarr[2].set_title('segmentation - all labels')
    axarr[2].imshow(seg, cmap=plt.cm.jet)

    for ax in axarr:
        ax.axis('off')
        ax.axes.get_xaxis().set_ticklabels([])
        ax.axes.get_yaxis().set_ticklabels([])

    fig.subplots_adjust(wspace=0.01, hspace=0.01)
    fig.tight_layout()
    return fig 
Example #17
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 #18
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 
Example #19
Source File: anno_helper.py    From lost with MIT License 4 votes vote down vote up
def draw_annos(annos, types, img, color=(255,0,0), point_r=2):
    '''Draw annotations inside a image

    Args:
        annos (list): List of annotations.
        types (list): List of types.
        img (numpy.array): The image to draw annotations in.
        color (tuple): (R,G,B) color that is used for drawing.
    
    Note:
        The given image will be directly edited!

    Returns:
        numpy.array: Image with drawn annotations
    '''
    if annos:
        if len(img.shape) < 3: 
            img = gray2rgb(img)
        img_h, img_w, _ = img.shape
        for anno, t in zip(annos, types):
            if t == 'bbox':
                anno = trans_boxes_to([anno])[0]
                anno = to_abs([anno], [t], (img_w, img_h))[0]
                xmin, ymin, xmax, ymax = anno
                rr, cc = polygon_perimeter([ymin, ymin, ymax, ymax],
                    [xmin, xmax, xmax, xmin ], shape=img.shape)
            elif t == 'polygon':
                anno = to_abs([anno], [t], (img_w, img_h))[0]
                anno = np.array(anno)
                rr, cc = polygon_perimeter(anno[:,1].tolist(),
                    anno[:,0].tolist(), shape=img.shape)
            elif t == 'point':
                anno = to_abs([anno], [t], (img_w, img_h))[0]
                rr, cc = circle(anno[1], anno[0], point_r, shape=img.shape)
            elif t == 'line':
                anno = to_abs([anno], [t], (img_w, img_h))[0]
                for i, point in enumerate(anno):
                    if i >= (len(anno)-1):
                        break
                    rr, cc = line(point[1], point[0], 
                        anno[i+1][1], anno[i+1][0])
                    img[rr,cc] = color
            else:
                raise ValueError('Unknown annotation type: {}'.format(t))
            img[rr,cc] = color
        return img
    else:
        return [] 
Example #20
Source File: points.py    From wallgen with MIT License 4 votes vote down vote up
def genSmartPoints(image):
	width = image.shape[1]
	height = image.shape[0]

	edges = sobel(image)

	# convert to RGB compatible image
	with warnings.catch_warnings():
		warnings.simplefilter('ignore')
		rgb_img = img_as_ubyte(color.gray2rgb(edges))

	# convert to PIL image
	pimg = Image.fromarray(rgb_img)
	idata = pimg.load()

	edges_data = []

	# get image pixel data and pass through a filter to get only prominent edges

	for x in range(pimg.width):
		for y in range(pimg.height):
			if sum(idata[x,y])/3 > 10:
				edges_data.append((x,y))

	# print(len(edges_data))
	
	# sometimes edges detected wont pass ^ this required case
	if len(edges_data) < 1:
		raise Exception("EdgeDetectionError")
		sys.exit(1)

	# get a n/5 number of points rather than all of the points
	sample = np.random.choice(len(edges_data), len(edges_data)//5 if len(edges_data)/5 < 50000 else 50000)
	edges_data = [edges_data[x] for x in sample]

	# print(len(edges_data))

	points = []
	radius = int(0.1 * (width+height)/2)

	# print(radius)
		
	points = edges_data

	ws = width//50
	hs = height//50

	for x in range(0, width+ws, ws):
		points.append((x,0))
		points.append((x,height))

	for y in range(0, height+hs, hs):
		points.append((0,y))
		points.append((width,y))

	tri = Delaunay(points) # calculate D triangulation of points
	delaunay_points = tri.points[tri.simplices] # find all groups of points

	return delaunay_points 
Example #21
Source File: extract_seqframes.py    From simba with GNU Lesser General Public License v3.0 4 votes vote down vote up
def convertseqVideo(videos,outtype='mp4',clahe=False,startF=None,endF=None):
    import os
    import io
    import cv2
    from tqdm import tqdm
    from PIL import Image
    from skimage import color
    from skimage.util import img_as_ubyte
    '''Convert videos to contrast adjusted videos of other formats'''
    ## get videos into a list in video folder
    videoDir = videos
    videolist = []
    for i in os.listdir(videoDir):
        if i.endswith('.seq'):
            videolist.append(os.path.join(videoDir,i))


    for video in videolist:
        vname = str(video)[:-4]
        f = open(video,'rb')
        info = readHeader(f)
        nframes = info.numFrames
        pos,frameSize = posFrame(f,nframes)
        fps=info.fps
        size = (info.width, info.height)
        extra=4
        if startF is None:
            startF=0
        if endF is None:
            endF=nframes
        if outtype=='avi':
            print('Coming soon')
        if outtype=='mp4':
            outname=os.path.join(vname + '.mp4')
            videowriter=cv2.VideoWriter(outname,cv2.VideoWriter_fourcc('m','p','4','v'),fps,size,isColor=True)
        for index in tqdm(range(startF,endF)):
            f.seek(pos[index]+extra*(index+1),0)
            imgdata=f.read(frameSize[index])
            image=Image.open(io.BytesIO(imgdata))
            image=img_as_ubyte(image)
            if clahe:
                image=cv2.createCLAHE(clipLimit=2,tileGridSize=(16,16)).apply(image)
            image=color.gray2rgb(image)
            frame=image
            videowriter.write(frame)
        f.close()
        videowriter.release()

    print('Finish conversion.')