Python matplotlib.cm.Greys_r() Examples

The following are code examples for showing how to use matplotlib.cm.Greys_r(). 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: LifelongVAE   Author: jramapuram   File: run_fashion_dnn_experiment.py    MIT License 6 votes vote down vote up
def _write_images(x_sample, x_reconstruct, vae_name, filename,
                  num_print=5, sup_title=None):
    fig = plt.figure(figsize=(8, 12))
    if sup_title:
        fig.suptitle(sup_title)

    for i in range(num_print):
        if x_sample is not None:
            plt.subplot(num_print, 2, 2*i + 1)
            #plt.imshow(x_sample[i].reshape(32, 32, 3))#, vmin=0, vmax=1)
            plt.imshow(x_sample[i].reshape(28, 28), cmap='Greys')#, vmin=0, vmax=1)
            plt.title("Test input")
            plt.colorbar()

        plt.subplot(num_print, 2, 2*i + 2)
        # plt.imshow(x_reconstruct[i].reshape(32, 32, 3))#, vmin=0, vmax=1)
        plt.imshow(x_reconstruct[i].reshape(28, 28), cmap='Greys')#, vmin=0, vmax=1)
        plt.title("Reconstruction")
        plt.colorbar()

    plt.savefig(filename, bbox_inches='tight', cmap=cm.Greys_r)
    plt.close() 
Example 2
Project: Dropout_BBalpha   Author: YingzhenLi   File: loading_utils.py    MIT License 6 votes vote down vote up
def plot_images(ax, images, shape, color = False):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    # flip 0 to 1
    images = 1.0 - images

    images = reshape_and_tile_images(images, shape, n_cols=len(images))
    if color:
        from matplotlib import cm
        plt.imshow(images, cmap=cm.Greys_r, interpolation='nearest')
    else:
        plt.imshow(images, cmap='Greys')
    ax.axis('off') 
Example 3
Project: med2image   Author: FNNDSC   File: med2image.py    MIT License 6 votes vote down vote up
def slice_save(self, astr_outputFile):
        '''
        Saves a single slice.

        ARGS

        o astr_output
        The output filename to save the slice to.
        '''
        self._log('Outputfile = %s\n' % astr_outputFile)
        fformat = astr_outputFile.split('.')[-1]
        if fformat == 'dcm':
            if self._dcm:
                self._dcm.pixel_array.flat = self._Mnp_2Dslice.flat
                self._dcm.PixelData = self._dcm.pixel_array.tostring()
                self._dcm.save_as(astr_outputFile)
            else:
                raise ValueError('dcm output format only available for DICOM files')
        else:
            pylab.imsave(astr_outputFile, self._Mnp_2Dslice, format=fformat, cmap = cm.Greys_r) 
Example 4
Project: FFNet   Author: shuyueL   File: nn.py    GNU General Public License v3.0 6 votes vote down vote up
def visual_filter(self, dim_row, dim_col):
	    plt.figure()
	    row = -1;
	    num_col = 10 # number of filters in a row
	    first_filter = np.transpose(self.sess.run(self.layers[0].W))
	    for ni in range(min(len(first_filter),100)):
	        img = first_filter[ni].reshape(dim_row,dim_col)
	        col = ni%num_col
	        if col == 0:
	            row += 1
	        plt.imshow(img, cmap=cm.Greys_r, extent=np.array([col*dim_col,(col+1)*dim_col,row*dim_row,(row+1)*dim_row]))
	    plt.xlim(-5,dim_col * num_col + 5)
	    plt.ylim(-5,dim_row * (row+1) + 5)
	    plt.show()

	# display neural network information 
Example 5
Project: variational-continual-learning   Author: nvcuong   File: visualisation.py    Apache License 2.0 6 votes vote down vote up
def plot_images(images, shape, path, filename, n_rows = 10, color = True):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    images = reshape_and_tile_images(images, shape, n_rows)
    if color:
        from matplotlib import cm
        plt.imsave(fname=path+filename+".png", arr=images, cmap=cm.Greys_r)
    else:
        plt.imsave(fname=path+filename+".png", arr=images, cmap='Greys')
    #plt.axis('off')
    #plt.tight_layout()
    #plt.savefig(path + filename + ".png", format="png")
    print "saving image to " + path + filename + ".png"
    plt.close() 
Example 6
Project: structured-output-ae   Author: sbelharbi   File: facedataset.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def debug_plot_over_img(self, img, x, y, bb_d, bb_gt):
        """Plot the landmarks over the image with the bbox."""
        plt.close("all")
        fig = plt.figure()  # , figsize=(15, 10.8), dpi=200
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        ax.imshow(img, aspect="auto", cmap='Greys_r')
        ax.scatter(x, y, s=10, color='r')
        rect1 = patches.Rectangle(
            (bb_d[0], bb_d[1]), bb_d[2]-bb_d[0], bb_d[3]-bb_d[1],
            linewidth=1, edgecolor='r', facecolor='none')
        ax.add_patch(rect1)
        rect2 = patches.Rectangle(
            (bb_gt[0], bb_gt[1]), bb_gt[2]-bb_gt[0], bb_gt[3]-bb_gt[1],
            linewidth=1, edgecolor='b', facecolor='none')
        ax.add_patch(rect2)
        fig.add_axes(ax)

        return fig 
Example 7
Project: structured-output-ae   Author: sbelharbi   File: facedataset.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def debug_draw_set(self, path_f, fd_out):
        if not os.path.exists(fd_out):
            os.makedirs(fd_out)
        with open(path_f, 'r') as f:
            stuff = pkl.load(f)
        for el in stuff:
            img_name = el["img_name"]
            print img_name
            img_gray = el["img_gray"]
            bb_d = el["bb_detector"]
            bb_gt = el["bb_ground_truth"]
            x = el["annox"]
            y = el["annoy"]
            fig = self.debug_plot_over_img(img_gray, x, y, bb_d, bb_gt)
            fig.savefig(
                fd_out+"/"+img_name, bbox_inches='tight', pad_inches=0,
                frameon=False, cmap=cm.Greys_r)
            del fig 
Example 8
Project: structured-output-ae   Author: sbelharbi   File: tools.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def plot_x_y_yhat(x, y, y_hat, xsz, ysz, binz=False):
    """Plot x, y and y_hat side by side."""
    plt.close("all")
    f = plt.figure(figsize=(15, 10.8), dpi=300)
    gs = gridspec.GridSpec(1, 3)
    if binz:
        y_hat = (y_hat > 0.5) * 1.
    ims = [x, y, y_hat]
    tils = [
        "x:" + str(xsz) + "x" + str(xsz),
        "y:" + str(ysz) + "x" + str(ysz),
        "yhat:" + str(ysz) + "x" + str(ysz)]
    for n, ti in zip([0, 1, 2], tils):
        f.add_subplot(gs[n])
        if n == 0:
            plt.imshow(ims[n], cmap=cm.Greys_r)
        else:
            plt.imshow(ims[n], cmap=cm.Greys_r)
        plt.title(ti)

    return f 
Example 9
Project: structured-output-ae   Author: sbelharbi   File: tools.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def plot_x_x_yhat(x, x_hat):
    """Plot x, y and y_hat side by side."""
    plt.close("all")
    f = plt.figure()  # figsize=(15, 10.8), dpi=300
    gs = gridspec.GridSpec(1, 2)
    ims = [x, x_hat]
    tils = [
        "xin:" + str(x.shape[0]) + "x" + str(x.shape[1]),
        "xout:" + str(x.shape[1]) + "x" + str(x_hat.shape[1])]
    for n, ti in zip([0, 1], tils):
        f.add_subplot(gs[n])
        plt.imshow(ims[n], cmap=cm.Greys_r)
        plt.title(ti)
        ax = f.gca()
        ax.set_axis_off()

    return f 
Example 10
Project: aitom   Author: xulabs   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def dsp_img(v, new_figure=True):

    import matplotlib.pyplot as plt

    if new_figure:
        fig = plt.figure()
        ax = fig.add_subplot(111)
    else:
        ax = plt


    import matplotlib.cm as cm
    
    ax_u = ax.imshow(  v, cmap = cm.Greys_r )
    ax.axis('off') # clear x- and y-axes

    plt.pause(0.001)        # calling pause will display the figure without blocking the program, see segmentation.active_contour.morphsnakes.evolve_visual 
Example 11
Project: pydnn   Author: zackriegman   File: img_util.py    MIT License 6 votes vote down vote up
def show_images(images, titles=None, canvas_dims=None):
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import scipy

    titles = [''] * len(images) if titles is None else titles
    rows, cols = (dimensions_to_fit_images(images.shape[0]) if
                  canvas_dims is None else canvas_dims)

    fig = plt.figure()
    for n, (title, image) in enumerate(zip(images, titles)):
        scipy.misc.imshow(image)
        sub = fig.add_subplot(rows, cols, n + 1)
        plt.imshow(image, interpolation='none', cmap=cm.Greys_r)
        sub.set_title('{} ({}x{})'.format(title, image.shape[0], image.shape[1]),
                      size=10)
        sub.axis('off')
    plt.show() 
Example 12
Project: SteinGrad   Author: YingzhenLi   File: utils.py    MIT License 6 votes vote down vote up
def color_plot_images(images, shape, path, filename, n_rows = 10, color = True):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    images = reshape_and_tile_images(images, shape, n_rows)
    if color:
        from matplotlib import cm
        plt.imsave(fname=path+filename+".png", arr=images, cmap=cm.Greys_r)
    else:
        plt.imsave(fname=path+filename+".png", arr=images, cmap='Greys')
    #plt.axis('off')
    #plt.tight_layout()
    #plt.savefig(path + filename + ".png", format="png")
    print "saving image to " + path + filename + ".png"
    plt.close() 
Example 13
Project: ImageQA   Author: codedecde   File: plotAttention.py    MIT License 5 votes vote down vote up
def plotAttention (image_file, question, alpha, smooth=True):
    
    ## Parameters
    #
    # image_file : Path to image file.
    # question   : List of question string words (tokenised)
    # alpha      : NP array of size (len(question), 196) or List of len(question) NP vectors of shape (196, )
    # smooth     : Parameter for scaling alpha
    #

    img = LoadImage(image_file)
    n_words = len(question) + 1
    w = np.round(np.sqrt(n_words))
    h = np.ceil(np.float32(n_words) / w)
            
    plt.subplot(w, h, 1)
    plt.imshow(img)
    plt.axis('off')

    for ii in xrange(alpha.shape[0]):
        plt.subplot(w, h, ii+2)
        lab = question[ii]
        plt.text(0, 1, lab, backgroundcolor='white', fontsize=13)
        plt.text(0, 1, lab, color='black', fontsize=13)
        plt.imshow(img)
        if smooth:
            alpha_img = skimage.transform.pyramid_expand(alpha[ii].reshape(14,14), upscale=32)
        else:
            alpha_img = skimage.transform.resize(alpha[ii].reshape(14,14), [img.shape[0], img.shape[1]])
        plt.imshow(alpha_img, alpha=0.8)
        plt.set_cmap(cm.Greys_r)
        plt.axis('off') 
Example 14
Project: Python-Deep-Learning-SE   Author: ivan-vasilev   File: chapter_04_001.py    MIT License 5 votes vote down vote up
def conv(image, im_filter):
    """
    :param image: grayscale image as a 2-dimensional numpy array
    :param im_filter: 2-dimensional numpy array
    """

    # input dimensions
    height = image.shape[0]
    width = image.shape[1]

    # output image with reduced dimensions
    im_c = np.zeros((height - len(im_filter) + 1,
                     width - len(im_filter) + 1))

    # iterate over all rows and columns
    for row in range(len(im_c)):
        for col in range(len(im_c[0])):
            # apply the filter
            for i in range(len(im_filter)):
                for j in range(len(im_filter[0])):
                    im_c[row, col] += image[row + i, col + j] * im_filter[i][j]

    # fix out-of-bounds values
    im_c[im_c > 255] = 255
    im_c[im_c < 0] = 0

    # plot images for comparison
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    plt.figure()
    plt.imshow(image, cmap=cm.Greys_r)
    plt.show()

    plt.imshow(im_c, cmap=cm.Greys_r)
    plt.show() 
Example 15
Project: pyCustusX   Author: Danielhiversen   File: CxDataHandler.py    MIT License 5 votes vote down vote up
def show_data(self,frame_no):
        data=self.load_frame(frame_no)
        plt.imshow(data.transpose(), cmap = cm.Greys_r)
        plt.show() 
Example 16
Project: pyCustusX   Author: Danielhiversen   File: CxDataHandler.py    MIT License 5 votes vote down vote up
def show_datas(self):
        def updatefig(frame_no):
            # set the data in the axesimage object
            im.set_array(self.load_frame(frame_no).transpose())
            # return the artists set
            return im,

        fig = plt.figure() # make figure

        im = plt.imshow(self.load_frame(0).transpose(), cmap= cm.Greys_r)

        ani = animation.FuncAnimation(fig, updatefig, frames=range(self.get_no_of_frames()),
                              interval=1, blit=True)
        plt.show() 
Example 17
Project: Image-Captioning-v2   Author: foamliu   File: demo.py    Apache License 2.0 5 votes vote down vote up
def visualize_att(image_path, seq, alphas, rev_word_map, i, smooth=True):
    """
    Visualizes caption with weights at every word.
    Adapted from paper authors' repo: https://github.com/kelvinxu/arctic-captions/blob/master/alpha_visualization.ipynb
    :param image_path: path to image that has been captioned
    :param seq: caption
    :param alphas: weights
    :param rev_word_map: reverse word mapping, i.e. ix2word
    :param smooth: smooth weights?
    """
    image = Image.open(image_path)
    image = image.resize([14 * 24, 14 * 24], Image.LANCZOS)

    words = [rev_word_map[ind] for ind in seq]
    print(words)

    for t in range(len(words)):
        if t > 50:
            break
        plt.subplot(np.ceil(len(words) / 5.), 5, t + 1)

        plt.text(0, 1, '%s' % (words[t]), color='black', backgroundcolor='white', fontsize=12)
        plt.imshow(image)
        current_alpha = alphas[t, :]
        if smooth:
            alpha = skimage.transform.pyramid_expand(current_alpha.numpy(), upscale=24, sigma=8)
        else:
            alpha = skimage.transform.resize(current_alpha.numpy(), [14 * 24, 14 * 24])
        if t == 0:
            plt.imshow(alpha, alpha=0)
        else:
            plt.imshow(alpha, alpha=0.8)
        plt.set_cmap(cm.Greys_r)
        plt.axis('off')

    plt.savefig('images/out_{}.jpg'.format(i))
    plt.close() 
Example 18
Project: Bigdata_proj_yanif   Author: tianyic   File: pca.py    MIT License 5 votes vote down vote up
def plot(data):	
	plt.imshow(data, cmap = cm.Greys_r)
	plt.show() 
Example 19
Project: Bigdata_proj_yanif   Author: tianyic   File: pca_unpar.py    MIT License 5 votes vote down vote up
def plot(data):
    plt.imshow(data, cmap = cm.Greys_r)
    plt.show() 
Example 20
Project: Bigdata_proj_yanif   Author: tianyic   File: views.py    MIT License 5 votes vote down vote up
def plot(data): 
    plt.imshow(data, cmap = cm.Greys_r)
    plt.show() 
Example 21
Project: Bigdata_proj_yanif   Author: tianyic   File: pca.py    MIT License 5 votes vote down vote up
def plot(data):	
	plt.imshow(data, cmap = cm.Greys_r)
	plt.show() 
Example 22
Project: Diffusion-Probabilistic-Models   Author: Sohl-Dickstein   File: viz.py    MIT License 5 votes vote down vote up
def plot_parameter(theta_in, base_fname_part1, base_fname_part2="", title = '', n_colors=None):
    """
    Save both a raw and receptive field style plot of the contents of theta_in.
    base_fname_part1 provides the mandatory root of the filename.
    """

    theta = np.array(theta_in.copy()) # in case it was a scalar
    print "%s min %g median %g mean %g max %g shape"%(
        title, np.min(theta), np.median(theta), np.mean(theta), np.max(theta)), theta.shape
    theta = np.squeeze(theta)
    if len(theta.shape) == 0:
        # it's a scalar -- make it a 1d array
        theta = np.array([theta])
    shp = theta.shape
    if len(shp) > 2:
        theta = theta.reshape((theta.shape[0], -1))
        shp = theta.shape

    ## display basic figure
    plt.figure(figsize=[8,8])
    if len(shp) == 1:
        plt.plot(theta, '.', alpha=0.5)
    elif len(shp) == 2:
        plt.imshow(theta, interpolation='nearest', aspect='auto', cmap=cm.Greys_r)
        plt.colorbar()

    plt.title(title)
    plt.savefig(base_fname_part1 + '_raw_' + base_fname_part2 + '.pdf')
    plt.close()

    ## also display it in basis function view if it's a matrix, or
    ## if it's a bias with a square number of entries
    if len(shp) >= 2 or is_square(shp[0]):
        if len(shp) == 1:
            theta = theta.reshape((-1,1))
        plt.figure(figsize=[8,8])
        if show_receptive_fields(theta, n_colors=n_colors):
            plt.suptitle(title + "receptive fields")
            plt.savefig(base_fname_part1 + '_rf_' + base_fname_part2 + '.pdf')
        plt.close() 
Example 23
Project: DeepBayes   Author: deepgenerativeclassifier   File: visualisation.py    MIT License 5 votes vote down vote up
def plot_images(images, shape, path, filename, n_rows = 10, margin=0, fill_val=None, color = True):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    images = reshape_and_tile_images(images, shape, n_rows, margin, fill_val)
    if color:
        from matplotlib import cm
        plt.imsave(fname=path+filename+".png", arr=images, cmap=cm.Greys_r)
    else:
        plt.imsave(fname=path+filename+".png", arr=images, cmap='Greys')
    print("saving image to " + path + filename + ".png")
    plt.close() 
Example 24
Project: FFNet   Author: shuyueL   File: nn.py    GNU General Public License v3.0 5 votes vote down vote up
def visual_input(self, images, dim_row, dim_col):
	    plt.figure()
	    row = -1;
	    num_col = 10 # number of filters in a row
	    for ni in range(min(len(images),100)):
	        img = images[ni].reshape(dim_row,dim_col)
	        col = ni%num_col
	        if col == 0:
	            row += 1
	        plt.imshow(img, cmap=cm.Greys_r, extent=np.array([col*dim_col,(col+1)*dim_col,row*dim_row,(row+1)*dim_row]))
	    plt.xlim(-5,dim_col * num_col + 5)
	    plt.ylim(-5,dim_row * (row+1) + 5)
	    plt.show()

	# visualize filter 
Example 25
Project: structured-output-ae   Author: sbelharbi   File: Routines.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def show_landmarks_unit_test(self, im, phis_pred, phis_mean_train, bbox, save=False, path="../im.png"):
        """ Display a shape over the face image. (python)
        
                
        phis_pred: predicted phis [xxxyyy]
        phis_mean_train: mean phis of ground of truth
        bbox=[x y w h]
        im = np.ndarray
        """
        plt.close('all')
        if save:
            plt.ioff()
             
        nfids = int(len(phis_pred)/2)
        plt.imshow(im, cmap = cm.Greys_r)
        gt = plt.scatter(x=phis_mean_train[0:nfids], y=phis_mean_train[nfids:], c='g', s=40)
        pr = plt.scatter(x=phis_pred[0:nfids], y=phis_pred[nfids:], c='r', s=20)
        
        mse = np.mean(np.power((phis_pred - phis_mean_train), 2))
        plt.legend((gt, pr), ("mean shape train", "prediction, MSE="+str(mse)), scatterpoints=1,loc='lower left', fontsize=8, fancybox=True, shadow=True)
        """
        plt.plot([bbox[0], bbox[0]],[bbox[1],bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0], bbox[0]+bbox[2]],[bbox[1], bbox[1]],'-b', linewidth=1)
        plt.plot([bbox[0]+bbox[2], bbox[0]+bbox[2]],[bbox[1], bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0] ,bbox[0]+bbox[2]],[bbox[1]+bbox[3] ,bbox[1]+bbox[3]],'-b', linewidth=1)
        """
        plt.axis('off')
        
        if save:
            plt.savefig(path,bbox_inches='tight', dpi=1000)
            plt.ion()
        else:
            plt.show()
            raw_input("... Press ENTER to continue,")
            
        plt.close('all') 
Example 26
Project: structured-output-ae   Author: sbelharbi   File: Routines.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def show_only_landmarks_unit_test(self, im, phis_pred, bbox, save=False, path="../im.png"):
        """ Display a shape over the face image. (python)
        
                
        phis_pred: predicted phis [xxxyyy]
        phis_mean_train: mean phis of ground of truth
        bbox=[x y w h]
        im = np.ndarray
        """
        plt.close('all')
        if save:
            plt.ioff()
             
        nfids = int(len(phis_pred)/2)
        plt.imshow(im, cmap = cm.Greys_r)
        pr = plt.scatter(x=phis_pred[0:nfids], y=phis_pred[nfids:], c='w', s=20)
        
        plt.legend([pr], ["prediction"], scatterpoints=1,loc='lower left', fontsize=8, fancybox=True, shadow=True)
        """
        plt.plot([bbox[0], bbox[0]],[bbox[1],bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0], bbox[0]+bbox[2]],[bbox[1], bbox[1]],'-b', linewidth=1)
        plt.plot([bbox[0]+bbox[2], bbox[0]+bbox[2]],[bbox[1], bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0] ,bbox[0]+bbox[2]],[bbox[1]+bbox[3] ,bbox[1]+bbox[3]],'-b', linewidth=1)
        """
        plt.axis('off')
        
        if save:
            plt.savefig(path,bbox_inches='tight', dpi=100)
            plt.ion()
        else:
            plt.show()
            raw_input("... Press ENTER to continue,")
            
        plt.close('all') 
Example 27
Project: structured-output-ae   Author: sbelharbi   File: Routines.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_code_recont_for_one_set(self, data, in_aes_path):
        """Plot x-code-x_hat for one set.
        """
        x = data['x']
        code = data['code']
        reconst = data['reconstruction']
        nbr = 10 # plot only 100 samples ... just to see.
        for i in xrange(nbr):
            # x
            xx = x[i]
            sz_x = xx.shape[0]
            sqrt_sz_x = int (np.sqrt(sz_x))
            xx = np.resize(xx, sqrt_sz_x ** 2).reshape(sqrt_sz_x, sqrt_sz_x)
            # code
            c = code[i]
            sz_c = c.shape[0]
            sqrt_sz_c = int (np.sqrt(sz_c))
            c = np.resize(c, sqrt_sz_c ** 2).reshape(sqrt_sz_c, sqrt_sz_c)
            
            # reconstruction
            recon = reconst[i]
            sz_recon= recon.shape[0]
            sqrt_sz_recon = int (np.sqrt(sz_recon))
            recon = np.resize(recon, sqrt_sz_recon ** 2).reshape(sqrt_sz_recon, sqrt_sz_recon)
            # plotting ..
            fig, axs = plt.subplots(3)  
            fig.tight_layout()
            xx_ax = axs[0].imshow(xx, cmap = cm.Greys_r)
            axs[0].set_title('x')
            fig.colorbar(xx_ax, ax=axs[0])
            c_ax = axs[1].imshow(c)
            axs[1].set_title('code')
            c_ax.set_cmap('spectral')
            fig.colorbar(c_ax, ax=axs[1])
            recon_ax = axs[2].imshow(recon, cmap = cm.Greys_r)
            axs[2].set_title('x_hat')
            fig.colorbar(recon_ax, ax=axs[2])
            fig.savefig(in_aes_path+str(i)+".png",bbox_inches='tight')
            plt.close("all") 
Example 28
Project: pixelqueer   Author: sdorminey   File: pixelqueer.py    MIT License 5 votes vote down vote up
def plot_image(original_image, altered_image):
    f = plt.figure()
    f.add_subplot(2, 1, 1)
    plt.imshow(original_image, cmap = cm.Greys_r)
    f.add_subplot(2, 1, 2)
    plt.imshow(altered_image, cmap = cm.Greys_r)
    plt.show() 
Example 29
Project: aitom   Author: xulabs   File: io.py    GNU General Public License v3.0 5 votes vote down vote up
def save_image_matplotlib(m, out_file, vmin=None, vmax=None):
    import matplotlib.pyplot as PLT
    import matplotlib.cm as CM

    if vmin is None:        vmin = m.min()
    if vmax is None:        vmax = m.max()

    ax_u = PLT.imshow(  m, cmap = CM.Greys_r, vmin=vmin, vmax=vmax)
    PLT.axis('off')
    PLT.draw()

    PLT.savefig(out_file, bbox_inches='tight')
    PLT.close("all") 
Example 30
Project: Python-Deep-Learning-Second-Edition   Author: PacktPublishing   File: chapter_04_001.py    MIT License 5 votes vote down vote up
def conv(image, im_filter):
    """
    :param image: grayscale image as a 2-dimensional numpy array
    :param im_filter: 2-dimensional numpy array
    """

    # input dimensions
    height = image.shape[0]
    width = image.shape[1]

    # output image with reduced dimensions
    im_c = np.zeros((height - len(im_filter) + 1,
                     width - len(im_filter) + 1))

    # iterate over all rows and columns
    for row in range(len(im_c)):
        for col in range(len(im_c[0])):
            # apply the filter
            for i in range(len(im_filter)):
                for j in range(len(im_filter[0])):
                    im_c[row, col] += image[row + i, col + j] * im_filter[i][j]

    # fix out-of-bounds values
    im_c[im_c > 255] = 255
    im_c[im_c < 0] = 0

    # plot images for comparison
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    plt.figure()
    plt.imshow(image, cmap=cm.Greys_r)
    plt.show()

    plt.imshow(im_c, cmap=cm.Greys_r)
    plt.show() 
Example 31
Project: Jackal_Velodyne_Duke   Author: MengGuo   File: rx_plot_pose_with_map.py    GNU General Public License v2.0 5 votes vote down vote up
def visualize_jackal(figure, pose, img):
    pyplot.cla()
    fig = figure
    ax = fig.add_subplot(111)
    ax.imshow(img, cmap=cm.Greys_r)
    ax.axis('image')
    if pose:
        meter_to_pixel = 10.6
        xl = pose[0]*meter_to_pixel
        yl = pose[1]*meter_to_pixel
        dl = pose[2]
        ax.plot(xl, yl, 'ro', markersize=10)
        L1 = 0.8*meter_to_pixel
        L2 = 1.6*meter_to_pixel
        car=[(xl-L1,yl-L1), (xl-L1,yl+ L1), (xl, yl+L2), (xl+L1, yl+L1), (xl+L1,yl-L1)]
        polygon2 = Polygon(transform(car, [xl,yl],dl+3.14), fill = True, facecolor='blue', edgecolor='blue', lw=4, zorder=2)
        ax.add_patch(polygon2)    
    ax.grid()
    #fig.subplots_adjust(0.003,0.062,0.97,0.94)
    #pyplot.show()
    pyplot.pause(0.01)
    return fig


#==============================
#============================== 
Example 32
Project: grammar-activity-prediction   Author: SiyuanQi   File: rrt.py    MIT License 5 votes vote down vote up
def plan_trajectory_with_ui(img):
    fig = ppl.gcf()
    fig.clf()
    ax = fig.add_subplot(1, 1, 1)
    ax.imshow(img, cmap=cm.Greys_r)
    ax.axis('image')
    ppl.draw()
    print 'Map is', len(img[0]), 'x', len(img)
    start, goal = select_start_goal_points(ax, img)
    path = rrt(img, start, goal, ax)
    return path 
Example 33
Project: ActiveBoundary   Author: MiriamHu   File: query_strategy.py    MIT License 5 votes vote down vote up
def generate_images_line_save(self, line_segment, query_id, image_original_space=None):
        """
        ID of query point from which query line was generated is
        added to the filename of the saved line query.
        :param line_segment:
        :param query_id:
        :return:
        """
        try:
            if image_original_space is not None:
                x = self.generative_model.decode(image_original_space.T)
            else:
                x = self.generative_model.decode(to_vector(self.dataset.data["features"][
                                                               query_id]).T)  # comes from dataset.data["features"], so is already in original space in which ALI operates.
            save_path = os.path.join(self.save_path_queries, "pointquery_%d_%d.png" % (self.n_queries + 1, query_id))
            if x.shape[1] == 1:
                plt.imsave(save_path, x[0, 0, :, :], cmap=cm.Greys)
            else:
                plt.imsave(save_path, x[0, :, :, :].transpose(1, 2, 0), cmap=cm.Greys_r)

            decoded_images = self.generative_model.decode(self.dataset.scaling_transformation.inverse_transform(
                line_segment))  # Transform to original space, in which ALI operates.
            figure = plt.figure()
            grid = ImageGrid(figure, 111, (1, decoded_images.shape[0]), axes_pad=0.1)
            for image, axis in zip(decoded_images, grid):
                if image.shape[0] == 1:
                    axis.imshow(image[0, :, :].squeeze(),
                                cmap=cm.Greys, interpolation='nearest')
                else:
                    axis.imshow(image.transpose(1, 2, 0).squeeze(),
                                cmap=cm.Greys_r, interpolation='nearest')
                axis.set_yticklabels(['' for _ in range(image.shape[1])])
                axis.set_xticklabels(['' for _ in range(image.shape[2])])
                axis.axis('off')
            save_path = os.path.join(self.save_path_queries, "linequery_%d_%d.pdf" % (self.n_queries + 1, query_id))
            plt.savefig(save_path, transparent=True, bbox_inches='tight')
        except Exception as e:
            print "EXCEPTION:", traceback.format_exc()
            raise e 
Example 34
Project: planespotter   Author: ericleib   File: Theano_aircraft.py    GNU General Public License v2.0 5 votes vote down vote up
def load_image(self):
        img = Image.open(os.path.join(self.dataset.directory, self.path)).convert('L').resize(
            self.dataset.image_size, Image.ANTIALIAS)
        array = np.asarray(img, dtype=theano.config.floatX) / 256.
        #pylab.imshow(array, cmap = cm.Greys_r, vmin = 0., vmax = 1.); pylab.show()
        return array.flatten() 
Example 35
Project: DeepVis-PredDiff   Author: lmzintgraf   File: utils_visualise.py    MIT License 4 votes vote down vote up
def plot_results(x_test, x_test_im, sensMap, predDiff, tarFunc, classnames, testIdx, save_path):
    '''
    Plot the results of the relevance estimation
    '''
    imsize = x_test.shape  
    
    tarIdx = np.argmax(tarFunc(x_test)[-1])
    tarClass = classnames[tarIdx]
    #tarIdx = 287
    
    plt.figure()
    plt.subplot(2,2,1)
    plt.imshow(x_test_im, interpolation='nearest')
    plt.title('original')
    frame = pylab.gca()
    frame.axes.get_xaxis().set_ticks([])
    frame.axes.get_yaxis().set_ticks([]) 
    plt.subplot(2,2,2)
    plt.imshow(sensMap, cmap=cm.Greys_r, interpolation='nearest')
    plt.title('sensitivity map')
    frame = pylab.gca()
    frame.axes.get_xaxis().set_ticks([])
    frame.axes.get_yaxis().set_ticks([]) 
    plt.subplot(2,2,3)
    p = predDiff.reshape((imsize[1],imsize[2],-1))[:,:,tarIdx]
    plt.imshow(p, cmap=cm.seismic, vmin=-np.max(np.abs(p)), vmax=np.max(np.abs(p)), interpolation='nearest')
    plt.colorbar()
    #plt.imshow(np.abs(p), cmap=cm.Greys_r)
    plt.title('weight of evidence')
    frame = pylab.gca()
    frame.axes.get_xaxis().set_ticks([])
    frame.axes.get_yaxis().set_ticks([]) 
    plt.subplot(2,2,4)
    plt.title('class: {}'.format(tarClass))
    p = get_overlayed_image(x_test_im, p)
    #p = predDiff[0,:,:,np.argmax(netPred(net, x_test)[0]),1].reshape((224,224))
    plt.imshow(p, cmap=cm.seismic, vmin=-np.max(np.abs(p)), vmax=np.max(np.abs(p)), interpolation='nearest')
    #plt.title('class entropy')
    frame = pylab.gca()
    frame.axes.get_xaxis().set_ticks([])
    frame.axes.get_yaxis().set_ticks([]) 
    
    fig = plt.gcf()
    fig.set_size_inches(np.array([12,12]), forward=True)
    plt.tight_layout()
    plt.tight_layout()
    plt.tight_layout()
    plt.savefig(save_path)
    plt.close() 
Example 36
Project: structured-output-ae   Author: sbelharbi   File: Routines.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def show_landmarks_points(self, im, phis_pred, phis_gt, bbox, nrmse=-1 ,save=False, path="../im.png"):
        """ Display a shape over the face image. (python)
        
                
        phis_pred: predicted phis [xxxyyy]
        phis_gt: phis of ground of truth
        bbox=[x y w h]
        im = np.ndarray
        nrmse: float (nrmse between gt and pred)
        """
        plt.close('all')
        if save:
            plt.ioff()
             
        nfids = int(len(phis_pred)/2)
        plt.imshow(im, cmap = cm.Greys_r)
        
        
        if nrmse > 0:
            gt = plt.scatter(x=phis_gt[0:nfids], y=phis_gt[nfids:], c='g', s=40)
            pr = plt.scatter(x=phis_pred[0:nfids], y=phis_pred[nfids:], c='r', s=20)
            plt.legend((gt, pr), ("grund truth", "prediction, nrmse="+str(nrmse)), scatterpoints=1, fontsize=8, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                       ncol=2, mode="expand", borderaxespad=0., fancybox=True, shadow=True)
        else:       # just display the landmarks of an image.   gt=pred
            
            gt = plt.scatter(x=phis_gt[0:nfids], y=phis_gt[nfids:], c='g', s=20)
            plt.legend([gt], ["landmarks"], scatterpoints=1, fontsize=8, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                       ncol=1, mode="expand", borderaxespad=0., fancybox=True, shadow=True)
        """
        plt.plot([bbox[0], bbox[0]],[bbox[1],bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0], bbox[0]+bbox[2]],[bbox[1], bbox[1]],'-b', linewidth=1)
        plt.plot([bbox[0]+bbox[2], bbox[0]+bbox[2]],[bbox[1], bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0] ,bbox[0]+bbox[2]],[bbox[1]+bbox[3] ,bbox[1]+bbox[3]],'-b', linewidth=1)
        """
        plt.axis('off')
        
        if save:
            plt.savefig(path,bbox_inches='tight', dpi=100)
            plt.ion()
        else:
            plt.show()
            raw_input("... Press ENTER to continue,")
            
        plt.close('all')