Python matplotlib.pyplot.gray() Examples

The following are 30 code examples of matplotlib.pyplot.gray(). 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 matplotlib.pyplot , or try the search function .
Example #1
Source File: disptools.py    From RATM with MIT License 6 votes vote down vote up
def dispimsmovie_patchwise(filename, M, inv, patchsize, fps=5, *args,
                           **kwargs):
    numframes = M.shape[0] / inv.shape[1]
    n = M.shape[0] / numframes

    def plotter(i):
        M_ = M[i * n:n * (i + 1)]
        M_ = np.dot(inv, M_)
        image = tile_raster_images(
            M_.T, img_shape=(patchsize, patchsize),
            tile_shape=(10, 10), tile_spacing=(1, 1),
            scale_rows_to_unit_interval=True, output_pixel_vals=True)
        plt.imshow(image, cmap=matplotlib.cm.gray, interpolation='nearest')
        plt.axis('off')

    CreateMovie(filename, plotter, numframes, fps) 
Example #2
Source File: disptools.py    From Emotion-Recognition-RNN with MIT License 6 votes vote down vote up
def dispimsmovie_patchwise(filename, M, inv, patchsize, fps=5, *args,
                           **kwargs):
    numframes = M.shape[0] / inv.shape[1]
    n = M.shape[0]/numframes

    def plotter(i):
        M_ = M[i*n:n*(i+1)]
        M_ = np.dot(inv,M_)
        width = int(np.ceil(np.sqrt(M.shape[1])))
        image = tile_raster_images(
            M_.T, img_shape=(patchsize,patchsize),
            tile_shape=(10,10), tile_spacing = (1,1),
            scale_rows_to_unit_interval = True, output_pixel_vals = True)
        plt.imshow(image,cmap=matplotlib.cm.gray,interpolation='nearest')
        plt.axis('off')

    CreateMovie(filename, plotter, numframes, fps) 
Example #3
Source File: disptools.py    From Emotion-Recognition-RNN with MIT License 6 votes vote down vote up
def dispimsmovie_patchwise(filename, M, inv, patchsize, fps=5, *args,
                           **kwargs):
    numframes = M.shape[0] / inv.shape[1]
    n = M.shape[0]/numframes

    def plotter(i):
        M_ = M[i*n:n*(i+1)]
        M_ = np.dot(inv,M_)
        width = int(np.ceil(np.sqrt(M.shape[1])))
        image = tile_raster_images(
            M_.T, img_shape=(patchsize,patchsize),
            tile_shape=(10,10), tile_spacing = (1,1),
            scale_rows_to_unit_interval = True, output_pixel_vals = True)
        plt.imshow(image,cmap=matplotlib.cm.gray,interpolation='nearest')
        plt.axis('off')

    CreateMovie(filename, plotter, numframes, fps) 
Example #4
Source File: extensions.py    From chainer-wasserstein-gan with MIT License 6 votes vote down vote up
def save_ims(filename, ims, dpi=100):
    n, c, w, h = ims.shape
    x_plots = math.ceil(math.sqrt(n))
    y_plots = x_plots if n % x_plots == 0 else x_plots - 1
    plt.figure(figsize=(w*x_plots/dpi, h*y_plots/dpi), dpi=dpi)

    for i, im in enumerate(ims):
        plt.subplot(y_plots, x_plots, i+1)

        if c == 1:
            plt.imshow(im[0])
        else:
            plt.imshow(im.transpose((1, 2, 0)))

        plt.axis('off')
        plt.gca().set_xticks([])
        plt.gca().set_yticks([])
        plt.gray()
        plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0,
                            hspace=0)

    plt.savefig(filename, dpi=dpi*2, facecolor='black')
    plt.clf()
    plt.close() 
Example #5
Source File: utils.py    From BusinessCardReader with MIT License 6 votes vote down vote up
def display(images):
    '''
    Takes a list of [(name, image, grayscaleImage, (keypoints, descriptor))]
    and displays them in a grid two wide
    '''
    # Calculate the height of the the plt. This is the hundreds digit
    size = int(np.ceil(len(images)/2.))*100
    # Number of images across is the tens digit
    size += 20
    count = 1
    plt.gray()
    for imgName, img in images:
        if len(img.shape) == 3:
            img = img[::,::,::-1]
        plt.subplot(size + count)
        plt.imshow(img)
        plt.title(imgName)
        count += 1
    plt.show() 
Example #6
Source File: plot_aug.py    From medical_image_segmentation with MIT License 6 votes vote down vote up
def plot_figures(names, figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in enumerate(names):
        img = np.squeeze(figures[title])
        if len(img.shape)==2:
            axeslist.ravel()[ind].imshow(img, cmap=plt.gray())#, cmap=plt.gray()
        else:
            axeslist.ravel()[ind].imshow(img)


        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional

    plt.show() 
Example #7
Source File: cv_utils.py    From GANimation with GNU General Public License v3.0 6 votes vote down vote up
def show_images_row(imgs, titles, rows=1):
    '''
       Display grid of cv2 images image
       :param img: list [cv::mat]
       :param title: titles
       :return: None
    '''
    assert ((titles is None) or (len(imgs) == len(titles)))
    num_images = len(imgs)

    if titles is None:
        titles = ['Image (%d)' % i for i in range(1, num_images + 1)]

    fig = plt.figure()
    for n, (image, title) in enumerate(zip(imgs, titles)):
        ax = fig.add_subplot(rows, np.ceil(num_images / float(rows)), n + 1)
        if image.ndim == 2:
            plt.gray()
        plt.imshow(image)
        ax.set_title(title)
        plt.axis('off')
    plt.show() 
Example #8
Source File: analyse_orderless_NADE.py    From NADE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_examples(nade, dataset, shape, name, rows=5, cols=10):    
    #Show some samples
    images = list()
    for row in xrange(rows):                     
        for i in xrange(cols):
            nade.setup_n_orderings(n=1)
            sample = dataset.sample_data(1)[0].T
            dens = nade.logdensity(sample)
            images.append((sample, dens))
    images.sort(key=lambda x: -x[1])
    
    plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100)
    plt.gray()            
    for row in xrange(rows):                     
        for col in xrange(cols):
            i = row*cols+col
            sample, dens = images[i]
            plt.subplot(rows, cols, i+1)
            plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper")
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04)
    type_1_font()
    plt.savefig(os.path.join(DESTINATION_PATH, name)) 
Example #9
Source File: analyse_orderless_NADE.py    From NADE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_samples(nade, shape, name, rows=5, cols=10):    
    #Show some samples
    images = list()
    for row in xrange(rows):                     
        for i in xrange(cols):
            nade.setup_n_orderings(n=1)
            sample = nade.sample(1)[:,0]
            dens = nade.logdensity(sample[:, np.newaxis])
            images.append((sample, dens))
    images.sort(key=lambda x: -x[1])
    
    plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100)
    plt.gray()            
    for row in xrange(rows):                     
        for col in xrange(cols):
            i = row*cols+col
            sample, dens = images[i]
            plt.subplot(rows, cols, i+1)
            plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper")
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04)
    type_1_font()
    plt.savefig(os.path.join(DESTINATION_PATH, name))                
    #plt.show() 
Example #10
Source File: analyse_orderless_NADE.py    From NADE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def inpaint_digits_(dataset, shape, model, n_examples = 5, delete_shape = (10,10), n_samples = 5, name = "inpaint_digits"):    
    #Load a few digits from the test dataset (as rows)
    data = dataset.sample_data(1000)[0]
    
    #data = data[[1,12,17,81,88,102],:]
    data = data[range(20,40),:]
    n_examples = data.shape[0]
    
    #Plot it all
    matplotlib.rcParams.update({'font.size': 8})
    plt.figure(figsize=(5,5), dpi=100)
    plt.gray()
    cols = 2 + n_samples
    for row in xrange(n_examples):
        # Original
        plt.subplot(n_examples, cols, row*cols+1)
        plot_sample(data[row,:], shape, origin="upper")        
    plt.subplots_adjust(left=0.01, right=0.99, top=0.95, bottom=0.01, hspace=0.40, wspace=0.04)
    plt.savefig(os.path.join(DESTINATION_PATH, "kk.pdf")) 
Example #11
Source File: Display.py    From Pic-Numero with MIT License 5 votes vote down vote up
def save_image(filename, image, title="", isGray=True):
    fig, ax = plt.subplots()
    plt.axis('off')
    if(isGray == True):
        plt.gray();
    ax.imshow(image, interpolation='nearest')
    ax.set_title(title)
    plt.savefig(filename)
    plt.close(fig) 
Example #12
Source File: disptools.py    From Emotion-Recognition-RNN with MIT License 5 votes vote down vote up
def dispims_white(invwhitening, M, height, width, border=0, bordercolor=0.0,
                  layout=None, **kwargs):
    """ Display a whole stack (colunmwise) of vectorized matrices. Useful
        eg. to display the weights of a neural network layer.
    """
    numimages = M.shape[1]
    M = np.dot(invwhitening, M)
    if layout is None:
        n0 = int(np.ceil(np.sqrt(numimages)))
        n1 = int(np.ceil(np.sqrt(numimages)))
    else:
        n0, n1 = layout
    im = bordercolor * np.ones(((height+border)*n0+border,
                                (width+border)*n1+border), dtype='<f8')
    for i in range(n0):
        for j in range(n1):
            if i*n1+j < M.shape[1]:
                im[i*(height+border)+border:(i+1)*(height+border)+border,
                   j*(width+border)+border :(j+1)*(width+border)+border] =\
                        np.vstack((
                            np.hstack((
                                np.reshape(M[:, i*n1+j],
                                           (height, width)),
                                bordercolor*np.ones((height, border),
                                                    dtype=float))),
                            bordercolor*np.ones((border, width+border),
                                                dtype=float)))
    plt.imshow(im, cmap=matplotlib.cm.gray, interpolation='nearest', **kwargs) 
Example #13
Source File: Display.py    From Pic-Numero with MIT License 5 votes vote down vote up
def show_image(image, title="", isGray=True):
    fig, ax = plt.subplots()
    if(isGray == True):
        plt.gray();
    ax.imshow(image, interpolation='nearest')
    ax.set_title(title)
    plt.show() 
Example #14
Source File: disptools.py    From Emotion-Recognition-RNN with MIT License 5 votes vote down vote up
def visualizefacenet(fname, imgs, patches_left, patches_right,
                     true_label, predicted_label):
    """Builds a plot of facenet with attention per RNN step and
    classification result
    """
    nsamples = imgs.shape[0]
    nsteps = patches_left.shape[1]
    is_correct = true_label == predicted_label
    w = nsteps + 2 + (nsteps % 2)
    h = nsamples * 2
    plt.clf()
    plt.gray()
    for i in range(nsamples):
        plt.subplot(nsamples, w//2, i*w//2 + 1)
        plt.imshow(imgs[i])
        msg = ('Prediction: ' + predicted_label[i] + ' TrueLabel: ' +
               true_label[i])
        if is_correct[i]:
            plt.title(msg,color='green')
        else:
            plt.title(msg,color='red')
        plt.axis('off')
        for j in range(nsteps):
            plt.subplot(h, w, i*2*w + 2 + 1 + j)
            plt.imshow(patches_left[i, j])
            plt.axis('off')
            plt.subplot(h, w, i*2*w + 2 + 1 + j + w)
            plt.imshow(patches_right[i, j])
            plt.axis('off')
    plt.show()
    plt.savefig(fname) 
Example #15
Source File: use_intermediate_functions.py    From hyperas with MIT License 5 votes vote down vote up
def visualization_mnist(x_data,n=10):
    plt.figure(figsize=(20, 4))
    for i in range(n):
        # display digit
        ax = plt.subplot(1, n, i+1)
        plt.imshow(x_data[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    plt.show() 
Example #16
Source File: train_catastrophe_model_human.py    From human-rl with MIT License 5 votes vote down vote up
def display_example(x,i):
    # imsize=42*42
    # observation = x[2:imsize+2].reshape([42,42])
    # observation2 = x[imsize+2:].reshape([42,42])
    # print(observation.shape)
    # Plot the grid
    x = x.reshape(42,42)
    plt.imshow(x)
    plt.gray()
    #plt.show()
    plt.savefig('/tmp/catastrophe/frame_{}.png'.format(i)) 
Example #17
Source File: disp_fig.py    From Video-Inpainting with MIT License 5 votes vote down vote up
def figure(self):
        # Display video frames using 8 subplot
        for i in range(8):
            ax = plt.subplot(1, 8, i+1)
            image = self.video[0][i]
            plt.imshow(image)
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False) 
Example #18
Source File: agent.py    From DRLwithTL with MIT License 5 votes vote down vote up
def get_depth(self):
        responses = self.client.simGetImages([airsim.ImageRequest(2, airsim.ImageType.DepthVis, False, False)])
        depth = []
        img1d = np.fromstring(responses[0].image_data_uint8, dtype=np.uint8)
        depth = img1d.reshape(responses[0].height, responses[0].width, 3)[:, :, 0]

        # To make sure the wall leaks in the unreal environment doesn't mess up with the reward function
        thresh = 50
        super_threshold_indices = depth > thresh
        depth[super_threshold_indices] = thresh
        depth = depth / thresh
        # plt.imshow(depth)
        # # plt.gray()
        # plt.show()
        return depth, thresh 
Example #19
Source File: eval.py    From MultiRobustness with MIT License 5 votes vote down vote up
def show_images(images, cols=1, figpath="figure.png"):
    """Display a list of images in a single figure with matplotlib.

    Parameters
    ---------
    images: List of np.arrays compatible with plt.imshow.

    cols (Default = 1): Number of columns in figure (number of rows is
                        set to np.ceil(n_images/float(cols))).

    titles: List of titles corresponding to each image. Must have
            the same length as titles.
    """
    n_images = len(images)
    fig = plt.figure()
    for n, image in enumerate(images):
        a = fig.add_subplot(cols, np.ceil(n_images / float(cols)), n + 1)
        if image.ndim == 2:
            plt.gray()
        if np.max(image) > 1.0:
            image = image.astype(np.uint8)

        plt.imshow(image)
    plt.savefig(figpath)
    plt.close()


# A function for evaluating a single checkpoint 
Example #20
Source File: facial_expression_rec.py    From EmotionClassifier with GNU General Public License v3.0 5 votes vote down vote up
def emotion_analysis(emotions):
    objects = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
    y_pos = np.arange(len(objects))

    plt.bar(y_pos, emotions, align='center', alpha=0.5)
    plt.xticks(y_pos, objects)
    plt.ylabel('percentage')
    plt.title('emotion')

    plt.show()


# ------------------------------
# ------------------------------
# make prediction for custom image out of test set

# img = image.load_img("C:/Users/IS96273/Desktop/jackman.png", grayscale=True, target_size=(48, 48))
#
# x = image.img_to_array(img)
# x = np.expand_dims(x, axis=0)
#
# x /= 255
#
# custom = model.predict(x)
# emotion_analysis(custom[0])
#
# x = np.array(x, 'float32')
# x = x.reshape([48, 48])
#
# plt.gray()
# plt.imshow(x)
# plt.show()
# ------------------------------ 
Example #21
Source File: demo_mp_async.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_depth(dev, data, timestamp):
    global image_depth
    data = frame_convert.pretty_depth(data)
    mp.gray()
    mp.figure(1)
    if image_depth:
        image_depth.set_data(data)
    else:
        image_depth = mp.imshow(data, interpolation='nearest', animated=True)
    mp.draw() 
Example #22
Source File: disptools.py    From RATM with MIT License 5 votes vote down vote up
def dispims_white(invwhitening, M, height, width, border=0, bordercolor=0.0,
                  layout=None, **kwargs):
    """ Display a whole stack (colunmwise) of vectorized matrices. Useful
        eg. to display the weights of a neural network layer.
    """
    numimages = M.shape[1]
    M = np.dot(invwhitening, M)
    if layout is None:
        n0 = int(np.ceil(np.sqrt(numimages)))
        n1 = int(np.ceil(np.sqrt(numimages)))
    else:
        n0, n1 = layout
    im = bordercolor * np.ones(((height + border) * n0 + border,
                                (width + border) * n1 + border), dtype='<f8')
    for i in range(n0):
        for j in range(n1):
            if i * n1 + j < M.shape[1]:
                im[i * (height + border) + border:(i + 1) * (height + border) + border,
                   j * (width + border) + border:(j + 1) * (width + border) + border] =\
                    np.vstack((
                        np.hstack((
                            np.reshape(M[:, i * n1 + j],
                                       (height, width)),
                            bordercolor * np.ones((height, border),
                                                  dtype=float))),
                        bordercolor * np.ones((border, width + border),
                                              dtype=float)))
    plt.imshow(im, cmap=matplotlib.cm.gray, interpolation='nearest', **kwargs) 
Example #23
Source File: disptools.py    From RATM with MIT License 5 votes vote down vote up
def visualizefacenet(fname, imgs, patches_left, patches_right,
                     true_label, predicted_label):
    """Builds a plot of facenet with attention per RNN step and
    classification result
    """
    nsamples = imgs.shape[0]
    nsteps = patches_left.shape[1]
    is_correct = true_label == predicted_label
    w = nsteps + 2 + (nsteps % 2)
    h = nsamples * 2
    plt.clf()
    plt.gray()
    for i in range(nsamples):
        plt.subplot(nsamples, w // 2, i * w // 2 + 1)
        plt.imshow(imgs[i])
        msg = ('Prediction: ' + predicted_label[i] + ' TrueLabel: ' +
               true_label[i])
        if is_correct[i]:
            plt.title(msg, color='green')
        else:
            plt.title(msg, color='red')
        plt.axis('off')
        for j in range(nsteps):
            plt.subplot(h, w, i * 2 * w + 2 + 1 + j)
            plt.imshow(patches_left[i, j])
            plt.axis('off')
            plt.subplot(h, w, i * 2 * w + 2 + 1 + j + w)
            plt.imshow(patches_right[i, j])
            plt.axis('off')
    plt.show()
    plt.savefig(fname) 
Example #24
Source File: disptools.py    From Emotion-Recognition-RNN with MIT License 5 votes vote down vote up
def dispims_white(invwhitening, M, height, width, border=0, bordercolor=0.0,
                  layout=None, **kwargs):
    """ Display a whole stack (colunmwise) of vectorized matrices. Useful
        eg. to display the weights of a neural network layer.
    """
    numimages = M.shape[1]
    M = np.dot(invwhitening, M)
    if layout is None:
        n0 = int(np.ceil(np.sqrt(numimages)))
        n1 = int(np.ceil(np.sqrt(numimages)))
    else:
        n0, n1 = layout
    im = bordercolor * np.ones(((height+border)*n0+border,
                                (width+border)*n1+border), dtype='<f8')
    for i in range(n0):
        for j in range(n1):
            if i*n1+j < M.shape[1]:
                im[i*(height+border)+border:(i+1)*(height+border)+border,
                   j*(width+border)+border :(j+1)*(width+border)+border] =\
                        np.vstack((
                            np.hstack((
                                np.reshape(M[:, i*n1+j],
                                           (height, width)),
                                bordercolor*np.ones((height, border),
                                                    dtype=float))),
                            bordercolor*np.ones((border, width+border),
                                                dtype=float)))
    plt.imshow(im, cmap=matplotlib.cm.gray, interpolation='nearest', **kwargs) 
Example #25
Source File: plot.py    From deskew with MIT License 5 votes vote down vote up
def display_hough(h: float, a: List[float], d: List[float]) -> None:  # pylint: disable=invalid-name
    plt.imshow(
        np.log(1 + h),
        extent=[np.rad2deg(a[-1]), np.rad2deg(a[0]), d[-1], d[0]],
        cmap=plt.gray,
        aspect=1.0 / 90
    )
    plt.show() 
Example #26
Source File: basic.py    From STGAN with MIT License 5 votes vote down vote up
def imwrite(image, path):
    """Save an [-1.0, 1.0] image."""
    if image.ndim == 3 and image.shape[2] == 1:  # for gray image
        image = np.array(image, copy=True)
        image.shape = image.shape[0:2]
    return scipy.misc.imsave(path, to_range(image, 0, 255, np.uint8)) 
Example #27
Source File: basic.py    From STGAN with MIT License 5 votes vote down vote up
def imshow(image):
    """Show a [-1.0, 1.0] image."""
    if image.ndim == 3 and image.shape[2] == 1:  # for gray image
        image = np.array(image, copy=True)
        image.shape = image.shape[0:2]
    plt.imshow(to_range(image), cmap=plt.gray()) 
Example #28
Source File: basic.py    From STGAN with MIT License 5 votes vote down vote up
def imwrite(image, path):
    """Save an [-1.0, 1.0] image."""
    if image.ndim == 3 and image.shape[2] == 1:  # for gray image
        image = np.array(image, copy=True)
        image.shape = image.shape[0:2]
    return scipy.misc.imsave(path, to_range(image, 0, 255, np.uint8)) 
Example #29
Source File: basic.py    From STGAN with MIT License 5 votes vote down vote up
def imshow(image):
    """Show a [-1.0, 1.0] image."""
    if image.ndim == 3 and image.shape[2] == 1:  # for gray image
        image = np.array(image, copy=True)
        image.shape = image.shape[0:2]
    plt.imshow(to_range(image), cmap=plt.gray()) 
Example #30
Source File: NN_ConvNet.py    From Deep_MRI_brain_extraction with MIT License 5 votes vote down vote up
def show_multiple_figures_add(fig, n, i, image, title, isGray=True):
    """ add <i>th (of n, start: 0) image to figure <fig> as subplot (GRAY)"""

    x = int(np.sqrt(n)+0.9999)
    y = int(n/x+0.9999)
    if(x*y<n):
        if x<y:
            x+=1
        else:
            y+=1

    ax = fig.add_subplot(x, y, i) #ith subplot in grid x,y
    ax.set_title(title)
    if isGray:
        plot.gray()
    ax.imshow(image,interpolation='nearest')

    return 0





#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------