Python matplotlib.pyplot.gray() Examples

The following are code examples for showing how to use matplotlib.pyplot.gray(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 6 votes vote down vote up
def mmontage( d, cmap=gray ):

    slices, rows, cols = d.shape

    N = round( math.sqrt( slices ) )

    im_cols = N
    im_rows = N
    
    if im_rows*im_cols < slices:
        im_rows = im_rows + 1

    extra = im_cols * im_rows - slices

    ii = 0
    d2 = zeros( (im_rows*rows, im_cols*cols), dtype=d.dtype)

    s1 = time.time()
    for ri in arange(0, im_rows):
        for ci in arange(0, im_cols):
            if ii == slices: break
            d2[ri*rows:(ri+1)*rows,ci*cols:(ci+1)*cols] = d[ii,:,:]
            ii = ii + 1

    mimage(d2, cmap) 
Example 2
Project: autoencoders_using_numpy   Author: Hadisalman   File: autoencoder.py    MIT License 6 votes vote down vote up
def visualize_decoded(self,x_test):
		n=10 # number of digits to test on
		ind = np.random.choice(x_test.shape[0], n)

		plt.figure(figsize=(20, 4))
		for i in range(n):

			# display original
			ax = plt.subplot(2, n, i + 1)
			plt.imshow(x_test[ind[i]].reshape(28, 28))
			plt.gray()
			ax.get_xaxis().set_visible(False)
			ax.get_yaxis().set_visible(False)

			# display reconstruction
			ax = plt.subplot(2, n, i + 1 + n)
			decoded = self.decode(x_test[ind[i]])
			plt.imshow(decoded.reshape(28, 28))
			plt.gray()
			ax.get_xaxis().set_visible(False)
			ax.get_yaxis().set_visible(False)
		plt.show() 
Example 3
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def subplots(images,num,cols,figsize=(8,9), colormap=plt.cm.gray):
    #fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=figsize)
    fig=plt.figure(num=num,figsize=figsize)
    images=np.squeeze(images)
    ax=[]
    #plt.setp(axes.flat, xticks=[], yticks=[])
    Numimgs=images.shape[0]
    gs = gridspec.GridSpec(Numimgs // cols, cols)
    for i in range(Numimgs):
        row = (i // cols)
        col = i % cols
        ax.append(fig.add_subplot(gs[row, col]))
        img = images[i,:, :]
        #axlog[-1].set_title('markevery=%s' % str(case))
        #ax[-1].set_xscale('log')
        #ax[-1].set_yscale('log')
        ax[-1].imshow(img.astype(np.uint8), cmap=colormap)
        ax[-1].axis('off')
    plt.tight_layout(pad=0.01, w_pad=0.01, h_pad=0.01)
   # fig.subplots_adjust(bottom=0.05, right=0.95)

    plt.show() 
Example 4
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def SuperPatchshow(testCord,PatchNorm,superpixel,slice_entro,labelslice,color='b',stride=32):
    from skimage.segmentation import mark_boundaries
    fig = plt.figure(figsize=(9, 5))
    ax = fig.add_subplot(111)
    #plt.gray()
    ax.imshow(mark_boundaries(PatchNorm, superpixel))
    figcolor=ax.imshow(slice_entro, cmap='rainbow',alpha=0.5)
    ax.imshow(labelslice, cmap='hot', alpha=0.5)
    fig.colorbar(figcolor, ax=ax)
   #ax.imshow(PatchNorm)
    ax.plot(np.transpose(np.array(testCord))[1],np.transpose(np.array(testCord))[0],'yo',lw=15)
    for c in range(len(testCord)):
         ax.add_patch(patches.Rectangle((testCord[c][1]-int(stride/2), testCord[c][0]-int(stride/2)),# (x,y)
                                                        stride,          # width
                                                        stride,          # heigh
                                                        fill=False,lw=5,edgecolor=color
                                                        ))

    ax.axis('off')
    plt.show() 
Example 5
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def PixelPatchshow(testCord,PatchNorm,labelslice,color='b',stride=32):
    from skimage.segmentation import mark_boundaries
    fig = plt.figure(figsize=(9, 5))
    ax = fig.add_subplot(111)
    #plt.gray()
    ax.imshow(PatchNorm,cmap=plt.cm.gray)
    ax.imshow(labelslice, cmap='hot', alpha=0.5)

   #ax.imshow(PatchNorm)
    ax.plot(np.transpose(np.array(testCord))[1],np.transpose(np.array(testCord))[0],'yo',lw=15)
    # for c in range(len(testCord)):
    #      ax.add_patch(patches.Rectangle((testCord[c][1]-int(stride/2), testCord[c][0]-int(stride/2)),# (x,y)
    #                                                     stride,          # width
    #                                                     stride,          # heigh
    #                                                     fill=False,lw=5,edgecolor=color
    #                                                     ))

    ax.axis('off')
    plt.show() 
Example 6
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_filters(W, file_name):

    size = int(np.sqrt(W.shape[0] * W.shape[1])) + 1
    W = W.reshape(W.shape[0] * W.shape[1], W.shape[2], W.shape[3])

    width = W.shape[1]

    plt.figure(figsize=(15, 18))
    for i in xrange(W.shape[0]):
        plt.subplot(size, size, i+1)
        Z = W[i,:,:]
        plt.xlim(0, width)
        plt.ylim(0, width)
        #plt.axes().set_aspect('auto')
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 7
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_filters_sq(W, file_name, show_num_filters):

    size_in = W.shape[1]

    image_size = W.shape[2]

    plt.figure(figsize=(24, 15))
    for i in xrange(show_num_filters * size_in):
        plt.subplot(show_num_filters, size_in, i+1)
        Z = W[int(i / size_in), i % size_in,:,:]
        plt.xlim(0, image_size)
        plt.ylim(0, image_size)
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 8
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_image(h, file_name):
    
    num_images = h.shape[0] * h.shape[1]
    width = h.shape[2]
    height = h.shape[3]
    graph_size = int(np.sqrt(h.shape[0] * h.shape[1])) + 1
    h = h.reshape((num_images, h.shape[2], h.shape[3]))

    plt.figure(figsize=(18, 18))
    for i in xrange(num_images):
        plt.subplot(graph_size, graph_size, i+1)
        Z = h[i,::-1,:]
        plt.xlim(0, width)
        plt.ylim(0, height)
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 9
Project: GANimation   Author: albertpumarola   File: cv_utils.py    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 10
Project: medical_image_segmentation   Author: CVxTz   File: plot_aug.py    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 11
Project: BusinessCardReader   Author: agundy   File: utils.py    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 12
Project: Emotion-Recognition-RNN   Author: saebrahimi   File: disptools.py    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 13
Project: Emotion-Recognition-RNN   Author: saebrahimi   File: disptools.py    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 14
Project: chainer-wasserstein-gan   Author: hvy   File: extensions.py    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 15
Project: st_analysis   Author: jfnavarro   File: align_sections.py    MIT License 6 votes vote down vote up
def plot_images(image_list, is_gray=False, filename=None):
    columns = int(round(np.sqrt(len(image_list))))
    rows = int(np.ceil(np.sqrt(len(image_list))))
    fig = plt.figure(figsize = (16, 16))
    for i in range(1, columns*rows + 1):
        try:
            img = image_list[i - 1]
            ax = fig.add_subplot(rows, columns, i)
            if is_gray:
                plt.gray()
            ax.imshow(img)
        except:
            continue
    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show()
    plt.clf()
    plt.cla() 
Example 16
Project: Recognition-of-Instruments   Author: Deep-Learning-Spring-2018   File: mpr.py    MIT License 6 votes vote down vote up
def mpr_plot(self, mpr_image, audio_index=5) -> None:
        """Plot mpr image for showing

        :mpr_image: TODO
        :returns: None

        """
        # Now plot for a test

        plt.gray()
        plt.figure(figsize=(12, 16))
        for points in range(self._temporal_point):
            for layers in range(self._max_layers):
                plt.subplot(self._temporal_point, self._max_layers,
                            points * self._max_layers + (layers + 1))
                plt.imshow(mpr_image[audio_index][points, layers, :, :, 0])
                plt.axis('off')
                plt.tight_layout()
                plt.subplots_adjust(wspace=0.4, hspace=0.4)
        plt.savefig('RP1.png')
        plt.close() 
Example 17
Project: NADE   Author: MarcCote   File: analyse_orderless_NADE.py    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 18
Project: NADE   Author: MarcCote   File: analyse_orderless_NADE.py    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 19
Project: NADE   Author: MarcCote   File: analyse_orderless_NADE.py    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 20
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    MIT License 6 votes vote down vote up
def plot_labeled_images_random(image_list, label_list, categories, n, title_str, ypixels, xpixels, seed, filename):
    random.seed(seed)
    index_sample = random.sample(range(len(image_list)), n)
    plt.figure(figsize=(2*n, 2))
    #plt.suptitle(title_str)
    for i, ind in enumerate(index_sample):
        ax = plt.subplot(1, n, i + 1)
        plt.imshow(image_list[ind].reshape(ypixels, xpixels))
        plt.gray()
        ax.set_title(categories[label_list[ind]], fontsize=20)
        ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False)
    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_unlabeled_images_random: plots unlabeled images at random 
Example 21
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    MIT License 6 votes vote down vote up
def plot_unlabeled_images_random(image_list, n, title_str, ypixels, xpixels, seed, filename):
    random.seed(seed)
    index_sample = random.sample(range(len(image_list)), n)
    plt.figure(figsize=(2*n, 2))
    plt.suptitle(title_str)
    for i, ind in enumerate(index_sample):
        ax = plt.subplot(1, n, i + 1)
        plt.imshow(image_list[ind].reshape(ypixels, xpixels))
        plt.gray()
        ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False)
    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_compare: given test images and their reconstruction, we plot them for visual comparison 
Example 22
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    MIT License 6 votes vote down vote up
def plot_compare(x_test, decoded_imgs, filename):
    n = 10
    plt.figure(figsize=(2*n, 4))
    for i in range(n):
        # display original
        ax = plt.subplot(2, n, i + 1)
        plt.imshow(x_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        # display reconstruction
        ax = plt.subplot(2, n, i + 1 + n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_img: plots greyscale image 
Example 23
Project: Malware-Image-Analysis   Author: skycckk   File: convert_exe_to_image.py    MIT License 6 votes vote down vote up
def convert_exe_to_image(file, save_path):
    """

    :param file: exe file
    :param save_path: folder where to save images, eg:C:/images/
    :return: image in grayscale
    """
    names = file.split('/')
    filename = names[-1]
    filesize = file_size(file)
    width = get_width(filesize)
    f = open(file, 'r+b')
    alist = []
    for each in f:
        for item in each:
            alist.append(item)
    myarray = np.asarray(alist)
    length = myarray.shape
    height = length[0] // width
    myarray = myarray[:height * width]
    img = np.reshape(myarray, (height, width))
    plt.gray()
    plt.imshow(img)
    plt.imsave(save_path + filename + '.png', img) 
Example 24
Project: jamespy_py3   Author: jskDr   File: mnist_r0.py    MIT License 6 votes vote down vote up
def imshow(self):
        (_, _), (x_test_in, x_test) = self.Data
        x_test_in, x_test = update2(x_test_in, x_test)
        autoencoder = self.autoencoder
        decoded_imgs = autoencoder.predict(x_test_in)

        n = 10
        plt.figure(figsize=(20, 4))
        for i in range(n):
            # display original
            ax = plt.subplot(2, n, i + 1)
            plt.imshow(x_test[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            # display reconstruction
            ax = plt.subplot(2, n, i + n + 1)
            plt.imshow(decoded_imgs[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)
        plt.show() 
Example 25
Project: jamespy_py3   Author: jskDr   File: mnist.py    MIT License 6 votes vote down vote up
def imshow(self):
        (_, _), (x_test_in, x_test) = self.Data
        x_test_in, x_test = update2(x_test_in, x_test)
        autoencoder = self.autoencoder
        decoded_imgs = autoencoder.predict(x_test_in)

        n = 10
        plt.figure(figsize=(20, 4))
        for i in range(n):
            # display original
            ax = plt.subplot(2, n, i + 1)
            plt.imshow(x_test[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            # display reconstruction
            ax = plt.subplot(2, n, i + n + 1)
            plt.imshow(decoded_imgs[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)
        plt.show() 
Example 26
Project: mPyPl   Author: shwars   File: image.py    MIT License 6 votes vote down vote up
def show_images(images, cols = 1, titles = None):
    """
    Show a list of images using matplotlib
    :param images: list of images (or any sequence with len and indexing defined)
    :param cols: number of columns to use
    :param titles: list of titles to use or None
    """
    assert((titles is None)or (len(images) == len(titles)))
    if not isinstance(images,list):
        images = list(images)
    n_images = len(images)
    if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
    fig = plt.figure()
    for n, (image, title) in enumerate(zip(images, titles)):
        a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
        if image.ndim == 2:
            plt.gray()
        plt.imshow(image)
        a.set_title(title)
        plt.xticks([]), plt.yticks([])
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
    plt.tight_layout()
    plt.show()

# Taken from https://stackoverflow.com/questions/31400769/bounding-box-of-numpy-array 
Example 27
Project: imtools   Author: mjirik   File: tools.py    MIT License 6 votes vote down vote up
def seeds2superpixels(seed_mask, superpixels, debug=False, im=None):
    seeds = np.argwhere(seed_mask)
    superseeds = np.zeros_like(seed_mask)

    for s in seeds:
        label = superpixels[s[0], s[1]]
        superseeds = np.where(superpixels==label, 1, superseeds)

    if debug:
        plt.figure(), plt.gray()
        plt.subplot(121), plt.imshow(im), plt.hold(True), plt.plot(seeds[:,1], seeds[:,0], 'ro'), plt.axis('image')
        plt.subplot(122), plt.imshow(im), plt.hold(True), plt.plot(seeds[:,1], seeds[:,0], 'ro'),
        plt.imshow(mark_boundaries(im, superseeds, color=(1,0,0))), plt.axis('image')
        plt.show()

    return superseeds


#----------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------- 
Example 28
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def mimage(d, cmap=gray):
    imshow( d )
    axis('image') # needed so that ginput doesn't resize the image
    clim([ prctile(d,1) , prctile(d, 99) ])
    xticks([])
    yticks([])
#    gca().get_axes().set_position([0,0,1,1]) #commented out by ny temporarily 
Example 29
Project: kvae   Author: simonkamronn   File: movie.py    MIT License 5 votes vote down vote up
def save_frames_to_png(images, filepath):
    num_sequences, n_steps, w, h = images.shape

    if not os.path.exists(filepath):
        os.makedirs(filepath)

    for i in range(n_steps):
        f = plt.figure(figsize=[12, 12])
        plt.imshow(images[0, i], cmap=plt.gray(), interpolation='none')
        plt.savefig(filepath + '/img_%d.png' % i, format='png', bbox_inches='tight', dpi=80)
        plt.close(f) 
Example 30
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def combine_channels(ims, titles, nrows, ncols, name):
    plt.figure(figsize=(8,8))
    plt.gray()
    for i in range(ncols * nrows):
        ax = plt.subplot(nrows, ncols, i + 1)
        ax.matshow(ims[i])
        plt.xticks([]); plt.yticks([])
        plt.title(titles[i])
    plt.savefig("feature_maps/" + name + ".jpeg", dpi=150) 
Example 31
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def combine_channels(ims, titles, nrows, ncols, name, digit):
    plt.figure(figsize=(8,8))
    plt.gray()
    for i in range(ncols * nrows):
        ax = plt.subplot(nrows, ncols, i + 1)
        ax.matshow(ims[i])
        plt.xticks([]); plt.yticks([])
        plt.title(titles[i])
    plt.savefig("combined_feature_maps/" + str(digit) + "/" + name + ".jpeg", dpi=150) 
Example 32
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def combine_channels(ims, titles, nrows, ncols, name, digit):
    plt.figure(figsize=(8,8))
    plt.gray()
    for i in range(ncols * nrows):
        ax = plt.subplot(nrows, ncols, i + 1)
        ax.matshow(ims[i])
        plt.xticks([]); plt.yticks([])
        plt.title(titles[i])
    plt.savefig("combined_feature_maps/" + str(digit) + "/" + name + ".jpeg", dpi=150) 
Example 33
Project: autoencoders_using_numpy   Author: Hadisalman   File: autoencoder.py    MIT License 5 votes vote down vote up
def visualize_weights(self, title):
		weights = self.model['W1']
		reshaped_weights = np.reshape(weights,(28,28,self.layers[1]))
		plt.figure(1)
		for i in range(self.layers[1]):
			ax = plt.subplot(np.sqrt(self.layers[1]),np.sqrt(self.layers[1]),i+1)	
			ax.imshow(reshaped_weights[:,:,i],cmap = 'gray')
			plt.axis('off')
		plt.pause(1) 
Example 34
Project: autoencoders_using_numpy   Author: Hadisalman   File: autoencoder.py    MIT License 5 votes vote down vote up
def add_noise(self, X, display=False):
		ind0 = np.random.choice(X.shape[0], int(np.floor(0.1*X.size)))
		ind1 = np.random.choice(X.shape[1], int(np.floor(0.1*X.size)))
		X_noisy = X.copy()
		X_noisy[ind0,ind1] = 0
		X_noisy = X_noisy + np.random.normal(0, 0.1,X_noisy.shape)
		
		if display:
			n=10 # number of digits to test on
			ind = np.random.choice(X.shape[0], n)

			plt.figure(figsize=(20, 4))
			for i in range(n):
				# display original
				ax = plt.subplot(2, n, i + 1)
				plt.imshow(X[ind[i]].reshape(28, 28))
				plt.gray()
				ax.get_xaxis().set_visible(False)
				ax.get_yaxis().set_visible(False)
				
				# display reconstruction
				ax = plt.subplot(2, n, i + 1 + n)
				plt.imshow(X_noisy[ind[i]].reshape(28, 28))
				plt.gray()
				ax.get_xaxis().set_visible(False)
				ax.get_yaxis().set_visible(False)
			plt.show()
		return X_noisy 
Example 35
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 5 votes vote down vote up
def imshow(image,num=1,titlename=None,colormap=plt.cm.gray):
  # display the 2D image
    fig=plt.figure(num)
  # Remove the first empty dimension
    image = np.squeeze(image)
    plt.imshow(image.astype(np.uint8),cmap=colormap)
    plt.title(titlename)
    plt.show() 
Example 36
Project: Variational-AutoEncoder-For-Novelty-Detection   Author: LordAlucard90   File: helper.py    GNU General Public License v3.0 5 votes vote down vote up
def show_reconstrunction(self, vae=True, hidden=2, reg_val=None, drp_val=None, imgs=5):
        m_generator = ModelGenerator(vae=vae, hidden=hidden, reg_val=reg_val, drp_val=drp_val)
        m_generator.load_best_w(self.models_dir)
        model = m_generator.get_model()

        decoded_imgs = model.predict(self.Tst[:imgs], verbose=0)

        plt.figure(figsize=(imgs, 2.5))
        for i in range(imgs):
            ax = plt.subplot(2, imgs, i + 1)
            if i == 2:
                ax.title.set_text('Original')
            plt.imshow(self.Tst[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

            ax = plt.subplot(2, imgs, i + 1 + imgs)
            if i == 2:
                ax.title.set_text('Recostruction')
            plt.imshow(decoded_imgs[i].reshape(28, 28))
            plt.gray()
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

        plt.show()
        plt.clf()
        plt.cla()
        plt.close() 
Example 37
Project: self-driving-donkey-car   Author: andrew-houghton   File: PCA_image_analyse.py    MIT License 5 votes vote down vote up
def plot_eigenvectors():
    V, EV, immean = pca(X)
    plt.gray()
    plt.subplot(2, 4, 1)
    plt.imshow(immean.reshape(m, n))
    for i in range(7):
        plt.subplot(2, 4, i + 2)
        plt.imshow(EV[:, i].reshape(m, n))
    plt.show() 
Example 38
Project: STGAN   Author: csmliu   File: basic.py    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 39
Project: STGAN   Author: csmliu   File: basic.py    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 40
Project: STGAN   Author: csmliu   File: basic.py    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 41
Project: STGAN   Author: csmliu   File: basic.py    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 42
Project: RPGOne   Author: RTHMaK   File: plot_local_binary_pattern.py    Apache License 2.0 5 votes vote down vote up
def plot_lbp_model(ax, binary_values):
    """Draw the schematic for a local binary pattern."""
    # Geometry spec
    theta = np.deg2rad(45)
    R = 1
    r = 0.15
    w = 1.5
    gray = '0.5'

    # Draw the central pixel.
    plot_circle(ax, (0, 0), radius=r, color=gray)
    # Draw the surrounding pixels.
    for i, facecolor in enumerate(binary_values):
        x = R * np.cos(i * theta)
        y = R * np.sin(i * theta)
        plot_circle(ax, (x, y), radius=r, color=str(facecolor))

    # Draw the pixel grid.
    for x in np.linspace(-w, w, 4):
        ax.axvline(x, color=gray)
        ax.axhline(x, color=gray)

    # Tweak the layout.
    ax.axis('image')
    ax.axis('off')
    size = w + 0.2
    ax.set_xlim(-size, size)
    ax.set_ylim(-size, size) 
Example 43
Project: PyIntroduction   Author: tody411   File: color_space.py    MIT License 5 votes vote down vote up
def showImageGray(image_file):
    image_gray = cv2.imread(image_file, 0)
    plt.title('Gray')
    plt.gray()
    plt.imshow(image_gray)
    plt.axis('off')
    plt.show()


# HSVチャンネルの表示 
Example 44
Project: PyIntroduction   Author: tody411   File: color_space.py    MIT License 5 votes vote down vote up
def showImageHSV(image_file):
    image_bgr = cv2.imread(image_file)
    image_hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)

    H = image_hsv[:, :, 0]
    S = image_hsv[:, :, 1]
    V = image_hsv[:, :, 2]

    plt.subplot(1, 3, 1)
    plt.title('Hue')
    plt.gray()
    plt.imshow(H)
    plt.axis('off')

    plt.subplot(1, 3, 2)
    plt.title('Saturation')
    plt.gray()
    plt.imshow(S)
    plt.axis('off')

    plt.subplot(1, 3, 3)
    plt.title('Value')
    plt.gray()
    plt.imshow(V)
    plt.axis('off')

    plt.show()


# Labチャンネルの表示 
Example 45
Project: PyIntroduction   Author: tody411   File: color_space.py    MIT License 5 votes vote down vote up
def showImageLab(image_file):
    image_bgr = cv2.imread(image_file)
    image_Lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)

    L = image_Lab[:, :, 0]
    a = image_Lab[:, :, 1]
    b = image_Lab[:, :, 2]

    plt.subplot(1, 3, 1)
    plt.title('L')
    plt.gray()
    plt.imshow(L)
    plt.axis('off')

    plt.subplot(1, 3, 2)
    plt.title('a')
    plt.gray()
    plt.imshow(a)
    plt.axis('off')

    plt.subplot(1, 3, 3)
    plt.title('b')
    plt.gray()
    plt.imshow(b)
    plt.axis('off')

    plt.show() 
Example 46
Project: PyIntroduction   Author: tody411   File: display_image.py    MIT License 5 votes vote down vote up
def pltShowImageGray(image_file):
    image_gray = cv2.imread(image_file, 0)
    plt.title('image')
    plt.gray()
    plt.imshow(image_gray)
    plt.axis('off')
    plt.show() 
Example 47
Project: MNIST-Deep-Learning   Author: dan59314   File: PlotFunctions.py    GNU General Public License v3.0 5 votes vote down vote up
def Plot_Figures(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
    """
    
    
    nImg = len(figures)
    nrows = int(nImg / ncols) + (1 * (nImg%ncols>0) )

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    
    for ind,title in zip(range(nImg), figures):
        figures[title] = np.array(figures[title], dtype='uint8')
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.gray())
        #axeslist.ravel()[ind].set_title(title)
        #img.set_cmap('hot') #讓圖形呈現紅色調
        axeslist.ravel()[ind].set_axis_off()
        
    for ind in range(nImg,nrows*ncols):
        axeslist.ravel()[ind].imshow([[]], cmap=plt.gray())
        #axeslist.ravel()[ind].set_title(title)
        #img.set_cmap('hot') #讓圖形呈現紅色調
        axeslist.ravel()[ind].set_axis_off()
        
    plt.tight_layout() # optional 
Example 48
Project: Finding-Similar-Images-using-Locality-Sensitive-Hashing   Author: prakhardogra921   File: LocalitySensitiveHashing.py    MIT License 5 votes vote down vote up
def show_images(images, cols = 1, titles = None):
    assert((titles is None)or (len(images) == len(titles)))
    n_images = len(images)
    if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
    fig = plt.figure()
    for n, (image, title) in enumerate(zip(images, titles)):
        a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
        if image.ndim == 2:
            plt.gray()
        plt.imshow(image)
        a.set_title(title)
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
    plt.show() 
Example 49
Project: Hackathon2015   Author: wbap   File: utils.py    Apache License 2.0 5 votes vote down vote up
def draw_weight(data, size):
    Z = data.reshape(size).T
    plt.imshow(Z, interpolation='none')
    plt.xlim(0,size[0])
    plt.ylim(0,size[1])
    plt.gray()
    plt.tick_params(labelbottom="off")
    plt.tick_params(labelleft="off")

## make small movies from all movies 
Example 50
Project: Hackathon2015   Author: wbap   File: test_check.py    Apache License 2.0 5 votes vote down vote up
def draw_weight(data, size):
    Z = data.reshape(size).T
    plt.imshow(Z, interpolation='none')
    plt.xlim(0,size[0])
    plt.ylim(0,size[1])
    plt.gray()
    plt.tick_params(labelbottom="off")
    plt.tick_params(labelleft="off")