Python matplotlib.pyplot.imshow() Examples

The following are code examples for showing how to use matplotlib.pyplot.imshow(). 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: Kaggle-Statoil-Challenge   Author: adodd202   File: capsulenet.py    MIT License 9 votes vote down vote up
def test(model, data):
    x_test, y_test = data
    y_pred, x_recon = model.predict(x_test, batch_size=100)
    print('-'*50)
    print('Test acc:', np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1))/y_test.shape[0])

    import matplotlib.pyplot as plt
    from utils import combine_images
    from PIL import Image

    img = combine_images(np.concatenate([x_test[:50],x_recon[:50]]))
    image = img * 255
    Image.fromarray(image.astype(np.uint8)).save("real_and_recon.png")
    print()
    print('Reconstructed images are saved to ./real_and_recon.png')
    print('-'*50)
    plt.imshow(plt.imread("real_and_recon.png", ))
    plt.show() 
Example 2
Project: spacesense   Author: spacesense-ai   File: training_data.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def display_sample(self, labels='all'):
        if labels == 'all':
            labels = self.label_names
        for label in labels:
            if label not in self.label_names:
                print('unavailable label')
                print('choose only available label names from "self.label_names" ')
                break
            else:
                i = np.random.choice(range(self.info['labels'][label]))
                folder_path = os.path.join(self.data_path_rgb, label)
                images = glob(folder_path + '/*')
                fig = plt.figure(i)
                fig.suptitle(label)
                plt.imshow(mpimg.imread(images[i]))
                plt.show() 
Example 3
Project: good-semi-bad-gan   Author: christiancosgrove   File: good-semi.py    MIT License 6 votes vote down vote up
def plot(samples):
    width = min(12,int(np.sqrt(len(samples))))
    fig = plt.figure(figsize=(width, width))
    gs = gridspec.GridSpec(width, width)
    gs.update(wspace=0.05, hspace=0.05)

    for ind, sample in enumerate(samples):
        if ind >= width*width:
            break
        ax = plt.subplot(gs[ind])
        plt.axis('off')
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_aspect('equal')
        sample = sample * 0.5 + 0.5
        sample = np.transpose(sample, (1, 2, 0))
        plt.imshow(sample)

    return fig 
Example 4
Project: mmdetection   Author: open-mmlab   File: inference.py    Apache License 2.0 6 votes vote down vote up
def show_result_pyplot(img,
                       result,
                       class_names,
                       score_thr=0.3,
                       fig_size=(15, 10)):
    """Visualize the detection results on the image.

    Args:
        img (str or np.ndarray): Image filename or loaded image.
        result (tuple[list] or list): The detection result, can be either
            (bbox, segm) or just bbox.
        class_names (list[str] or tuple[str]): A list of class names.
        score_thr (float): The threshold to visualize the bboxes and masks.
        fig_size (tuple): Figure size of the pyplot figure.
        out_file (str, optional): If specified, the visualization result will
            be written to the out file instead of shown in a window.
    """
    img = show_result(
        img, result, class_names, score_thr=score_thr, show=False)
    plt.figure(figsize=fig_size)
    plt.imshow(mmcv.bgr2rgb(img)) 
Example 5
Project: oslodatascience-rl   Author: Froskekongen   File: space_invaders4.py    MIT License 6 votes vote down vote up
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
    """ convert the 210x160x3 uint8 frame into a 7056 float vector """
    processed_observation = remove_color(preprocess(input_observation))
    processed_observation = processed_observation.astype(np.float).ravel()

    # subtract the previous frame from the current one so we are only processing on changes in the game
    if prev_processed_observation is not None:
        input_observation = processed_observation - prev_processed_observation
        # B = np.reshape(input_observation, (-1, 84))
        # plt.imshow(np.array(np.squeeze(B)))
        # plt.show()
    else:
        input_observation = np.zeros(input_dimensions)
    # store the previous frame so we can subtract from it next time
    prev_processed_observations = processed_observation
    return input_observation, prev_processed_observations 
Example 6
Project: oslodatascience-rl   Author: Froskekongen   File: space_invaders3.py    MIT License 6 votes vote down vote up
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
    """ convert the 210x160x3 uint8 frame into a 6400 float vector """
    # processed_observation = input_observation
    # processed_observation = remove_color(processed_observation)
    # processed_observation = remove_background(processed_observation)
    # processed_observation[processed_observation != 0] = 1 # everything else (paddles, ball) just set to 1
    # # Convert from 80 x 80 matrix to 6400 x 1 matrix
    #
    # processed_observation = processed_observation[25:195,]

    processed_observation = remove_color(preprocess(input_observation))
    processed_observation = processed_observation.astype(np.float).ravel()

    # subtract the previous frame from the current one so we are only processing on changes in the game
    if prev_processed_observation is not None:
        input_observation = processed_observation - prev_processed_observation
        # B = np.reshape(input_observation, (-1, 84))
        # plt.imshow(np.array(np.squeeze(B)))
        # plt.show()
    else:
        input_observation = np.zeros(input_dimensions)
    # store the previous frame so we can subtract from it next time
    prev_processed_observations = processed_observation
    return input_observation, prev_processed_observations 
Example 7
Project: deep-learning-note   Author: wdxtub   File: 8_kmeans_pca.py    MIT License 6 votes vote down vote up
def plot_n_image(X, n):
    """ plot first n images
    n has to be a square number
    """
    pic_size = int(np.sqrt(X.shape[1]))
    grid_size = int(np.sqrt(n))

    first_n_images = X[:n, :]

    fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size,
                                    sharey=True, sharex=True, figsize=(8, 8))

    for r in range(grid_size):
        for c in range(grid_size):
            ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((pic_size, pic_size)))
            plt.xticks(np.array([]))
            plt.yticks(np.array([])) 
Example 8
Project: tf-cnn-lstm-ocr-captcha   Author: Luonic   File: ImageAugmenter.py    MIT License 6 votes vote down vote up
def apply_motion_blur(image, kernel_size, strength = 1.0):
    """Applies motion blur on image 
    """
    # generating the kernel
    kernel_motion_blur = np.zeros((kernel_size, kernel_size))
    kernel_motion_blur[int((kernel_size - 1) / 2), :] = np.ones(kernel_size)
    kernel_motion_blur = kernel_motion_blur / kernel_size

    rotation_kernel = np.random.uniform(0, 360)
    kernel_motion_blur = rotate(kernel_motion_blur, rotation_kernel)
    #cv2.imshow("kernel", cv2.resize(kernel_motion_blur, (100, 100)))
    kernel_motion_blur *= strength

    # applying the kernel to the input image
    output = cv2.filter2D(image, -1, kernel_motion_blur)
    return output 
Example 9
Project: procgen   Author: juancroldan   File: simplex.py    Apache License 2.0 6 votes vote down vote up
def simplex2D_subjective():
	print("Displaying 2D simplex output")
	N = 100
	pmap = [[combined(simplex2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(simplex2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(simplex2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(simplex2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 10
Project: procgen   Author: juancroldan   File: white.py    Apache License 2.0 6 votes vote down vote up
def white2D_subjective():
	print("Displaying 2D white output")
	N = 100
	pmap = [[combined(white, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(white, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(white, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(white, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 11
Project: procgen   Author: juancroldan   File: perlin.py    Apache License 2.0 6 votes vote down vote up
def perlin2D_subjective():
	print("Displaying 2D perlin output")
	N = 100
	pmap = [[combined(perlin2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(perlin2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(perlin2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(perlin2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 12
Project: procgen   Author: juancroldan   File: opensimplex.py    Apache License 2.0 6 votes vote down vote up
def opensimplex2D_subjective():
	print("Displaying 2D opensimplex output")
	N = 100
	pmap = [[combined(opensimplex2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(opensimplex2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(opensimplex2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(opensimplex2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 13
Project: MLP-Numpy-Implementation-Gradient-Descent-Backpropagation   Author: EsterHlav   File: support.py    MIT License 6 votes vote down vote up
def showImages(imgarray, indexes):
    # takes as input a (N*784) set of data and integers (indexes of image to show)
    # and print the corresponding image
    # figure out the size of figure
    n = len(indexes)
    w,l = shapeGrid(n)

    imgarrayX, imgarrayY = imgarray

    import matplotlib.pyplot as plt
    plt.figure(figsize=(8, 6))
    plt.subplots_adjust(hspace=1, wspace=0.3)
    for i in range(n):
        plt.subplot(w, l, i+1)
        pixels = np.array(imgarrayX[indexes[i]]*255).reshape((28, 28))
        s = "Label: {}".format(imgarrayY[indexes[i]])
        plt.title(s)
        plt.axis('off')
        plt.imshow(pixels, cmap='gray')
    plt.show() 
Example 14
Project: MLP-Numpy-Implementation-Gradient-Descent-Backpropagation   Author: EsterHlav   File: support.py    MIT License 6 votes vote down vote up
def showPredictedLabels(imgarray, indexes, labels):
    # takes as input a (N*784) set of data, integers (index of images to show) and labels predicted
    # and print the corresponding images as well as the real label and predicted labels

    # figure out the size of figure
    n = len(indexes)
    w,l = shapeGrid(n)

    imgarrayX, imgarrayY = imgarray
    import matplotlib.pyplot as plt
    plt.figure(figsize=(10, 8))
    plt.subplots_adjust(hspace=0.4, wspace=0.3)
    for i in range(n):
        plt.subplot(w, l, i+1)
        pixels = np.array(imgarrayX[indexes[i]]*255).reshape((28, 28))
        s = "True: {}, Pred: {}".format(imgarrayY[indexes[i]], labels[i])
        plt.title(s)
        plt.axis('off')
        plt.imshow(pixels, cmap='gray')
    plt.show()

# example to try
# idx = [2,9,10,387, 2839, 8473, 10, 89, 87, 1, 12, 26, 28]
# pred = [8, 2, 2, 0, 5, 7, 1, 3, 2, 0, 2, 6, 8]
# showPredictedLabels(valid, idx, pred) 
Example 15
Project: Recipes   Author: Lasagne   File: massachusetts_road_segm.py    MIT License 6 votes vote down vote up
def plot_some_results(pred_fn, test_generator, n_images=10):
    fig_ctr = 0
    for data, seg in test_generator:
        res = pred_fn(data)
        for d, s, r in zip(data, seg, res):
            plt.figure(figsize=(12, 6))
            plt.subplot(1, 3, 1)
            plt.imshow(d.transpose(1,2,0))
            plt.title("input patch")
            plt.subplot(1, 3, 2)
            plt.imshow(s[0])
            plt.title("ground truth")
            plt.subplot(1, 3, 3)
            plt.imshow(r)
            plt.title("segmentation")
            plt.savefig("road_segmentation_result_%03.0f.png"%fig_ctr)
            plt.close()
            fig_ctr += 1
            if fig_ctr > n_images:
                break 
Example 16
Project: StyleGAN   Author: mgmk2   File: image_utils.py    Apache License 2.0 6 votes vote down vote up
def show_images(images, epoch=None, mode='show'):
    if mode not in ['show', 'pause']:
        raise ValueError('Unknown mode to show images: ' + mode)

    if images.shape[-1] == 1:
        x = images[:, :, :, 0]
        cmap = 'gray'
    else:
        x = images
        cmap = None
    fig = plt.figure(figsize=(4, 4))
    for i in range(16):
        plt.subplot(4, 4, i + 1)
        plt.imshow(x[i].clip(0, 1), cmap=cmap)
        plt.axis('off')
    if epoch is not None:
        fig.suptitle('epoch: {:}'.format(epoch))

    if mode == 'pause':
        plt.pause(.05)
    else:
        plt.show() 
Example 17
Project: Deformable-ConvNets   Author: guanfuchen   File: show_boxes.py    MIT License 6 votes vote down vote up
def show_boxes(im, dets, classes, scale = 1.0):
    plt.cla()
    plt.axis("off")
    plt.imshow(im)
    for cls_idx, cls_name in enumerate(classes):
        cls_dets = dets[cls_idx]
        for det in cls_dets:
            bbox = det[:4] * scale
            color = (rand(), rand(), rand())
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                  bbox[2] - bbox[0],
                                  bbox[3] - bbox[1], fill=False,
                                  edgecolor=color, linewidth=2.5)
            plt.gca().add_patch(rect)

            if cls_dets.shape[1] == 5:
                score = det[-1]
                plt.gca().text(bbox[0], bbox[1],
                               '{:s} {:.3f}'.format(cls_name, score),
                               bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white')
    plt.show()
    return im 
Example 18
Project: SyNEThesia   Author: RunOrVeith   File: live_viewer.py    MIT License 5 votes vote down vote up
def display(self, image_generator):
        im = plt.imshow(np.zeros((1, 1, 3)), animated=True)
        def update(frame, *_):
            im.set_array(frame)
            return im,

        ani = FuncAnimation(self.fig, func=update, frames=image_generator, interval=self.pause_time, blit=True)
        plt.show() 
Example 19
Project: curriculum-dropout   Author: pmorerio   File: load.py    GNU General Public License v3.0 5 votes vote down vote up
def main():

	data_ = open('../data_dir.txt','r')
	datasets_dir = data_.readline().split()[0]
	double_mnist, labels, _, _= doubleMnist(datasets_dir)	
	print 'label', labels[110,:]
	plt.imshow(double_mnist[110,:,:])
	plt.show() 
Example 20
Project: Tacotron   Author: ElwynWang   File: signal_process.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_alignment(alignment, gs, mode, path = None):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    mode: "save_fig" or "with_return". "save_fig":save fig locally, "with_return":return plot for tensorboard
    """

    plt.imshow(alignment, cmap='hot', interpolation='nearest')
    plt.xlabel('Decoder Steps')
    plt.ylabel('Encoder Steps')
    plt.title('{} Steps'.format(gs))

    if mode == "save_fig":
        if path is not None:
            plt.savefig('{}/alignment_{}k.png'.format(path, gs//Hp.save_model_step), format='jpg')
        else:
            print ("Warning! You need specify the saved path! The temporal path is {}".format(Hp.logdir))
            plt.savefig('{}/alignment_{}k.png'.format(Hp.logdir, gs//Hp.save_model_step), format='jpg')

    elif mode == "with_return":
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plot = tf.image.decode_png(buf.getvalue(), channels=4)
        plot = tf.expand_dims(plot,0)
        return plot

    else:
        print ("Error Mode! Exit!")
        sys.exit(0) 
Example 21
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 22
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 23
Project: Random-Erasing   Author: zhunzhong07   File: visualize.py    Apache License 2.0 5 votes vote down vote up
def show_batch(images, Mean=(2, 2, 2), Std=(0.5,0.5,0.5)):
    images = make_image(torchvision.utils.make_grid(images), Mean, Std)
    plt.imshow(images)
    plt.show() 
Example 24
Project: Random-Erasing   Author: zhunzhong07   File: visualize.py    Apache License 2.0 5 votes vote down vote up
def show_mask_single(images, mask, Mean=(2, 2, 2), Std=(0.5,0.5,0.5)):
    im_size = images.size(2)

    # save for adding mask
    im_data = images.clone()
    for i in range(0, 3):
        im_data[:,i,:,:] = im_data[:,i,:,:] * Std[i] + Mean[i]    # unnormalize

    images = make_image(torchvision.utils.make_grid(images), Mean, Std)
    plt.subplot(2, 1, 1)
    plt.imshow(images)
    plt.axis('off')

    # for b in range(mask.size(0)):
    #     mask[b] = (mask[b] - mask[b].min())/(mask[b].max() - mask[b].min())
    mask_size = mask.size(2)
    # print('Max %f Min %f' % (mask.max(), mask.min()))
    mask = (upsampling(mask, scale_factor=im_size/mask_size))
    # mask = colorize(upsampling(mask, scale_factor=im_size/mask_size))
    # for c in range(3):
    #     mask[:,c,:,:] = (mask[:,c,:,:] - Mean[c])/Std[c]

    # print(mask.size())
    mask = make_image(torchvision.utils.make_grid(0.3*im_data+0.7*mask.expand_as(im_data)))
    # mask = make_image(torchvision.utils.make_grid(0.3*im_data+0.7*mask), Mean, Std)
    plt.subplot(2, 1, 2)
    plt.imshow(mask)
    plt.axis('off') 
Example 25
Project: Random-Erasing   Author: zhunzhong07   File: visualize.py    Apache License 2.0 5 votes vote down vote up
def show_mask(images, masklist, Mean=(2, 2, 2), Std=(0.5,0.5,0.5)):
    im_size = images.size(2)

    # save for adding mask
    im_data = images.clone()
    for i in range(0, 3):
        im_data[:,i,:,:] = im_data[:,i,:,:] * Std[i] + Mean[i]    # unnormalize

    images = make_image(torchvision.utils.make_grid(images), Mean, Std)
    plt.subplot(1+len(masklist), 1, 1)
    plt.imshow(images)
    plt.axis('off')

    for i in range(len(masklist)):
        mask = masklist[i].data.cpu()
        # for b in range(mask.size(0)):
        #     mask[b] = (mask[b] - mask[b].min())/(mask[b].max() - mask[b].min())
        mask_size = mask.size(2)
        # print('Max %f Min %f' % (mask.max(), mask.min()))
        mask = (upsampling(mask, scale_factor=im_size/mask_size))
        # mask = colorize(upsampling(mask, scale_factor=im_size/mask_size))
        # for c in range(3):
        #     mask[:,c,:,:] = (mask[:,c,:,:] - Mean[c])/Std[c]

        # print(mask.size())
        mask = make_image(torchvision.utils.make_grid(0.3*im_data+0.7*mask.expand_as(im_data)))
        # mask = make_image(torchvision.utils.make_grid(0.3*im_data+0.7*mask), Mean, Std)
        plt.subplot(1+len(masklist), 1, i+2)
        plt.imshow(mask)
        plt.axis('off')



# x = torch.zeros(1, 3, 3)
# out = colorize(x)
# out_im = make_image(out)
# plt.imshow(out_im)
# plt.show() 
Example 26
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def show(image):
    """
    Render a given numpy.uint8 2D array of pixel data.
    """
    plt.imshow(image, cmap='gray')
    plt.show() 
Example 27
Project: deep-learning-note   Author: wdxtub   File: 18_basic_tfrecord.py    MIT License 5 votes vote down vote up
def read_tfrecord(tfrecod_file):
    label, shape, image = read_from_tfrecord([tfrecod_file])

    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        label, image, shape = sess.run([label, image, shape])
        coord.request_stop()
        coord.join(threads)

    print(label)
    print(shape)
    plt.imshow(image)
    plt.show() 
Example 28
Project: deep-learning-note   Author: wdxtub   File: 16_basic_kernels.py    MIT License 5 votes vote down vote up
def show_images(images, rgb=True):
    gs = gridspec.GridSpec(1, len(images))
    for i, image in enumerate(images):
        plt.subplot(gs[0, i])
        if rgb:
            plt.imshow(image)
        else:
            image = image.reshape(image.shape[0], image.shape[1])
            plt.imshow(image, cmap='gray')
        plt.axis('off')
    plt.show() 
Example 29
Project: deep-learning-note   Author: wdxtub   File: 2_serving_and_predict.py    MIT License 5 votes vote down vote up
def show(idx, title):
  plt.figure()
  plt.imshow(test_images[idx].reshape(28,28))
  plt.axis('off')
  plt.title('\n\n{}'.format(title), fontdict={'size': 16})
  plt.show() 
Example 30
Project: DeepLab_v3_plus   Author: songdejia   File: util.py    MIT License 5 votes vote down vote up
def decode_segmap(label_mask, dataset='pascal', plot=False):
    """
    将 mask 解码成class-wise rgb图
    返回 opencv 格式的 h, w, 3, 记住是np.int32
    Decode segmentation class labels into a color image
    Args:
        label_mask (np.ndarray): an (M,N) array of integer values denoting
          the class label at each spatial location.
        plot (bool, optional): whether to show the resulting color image
          in a figure.
    Returns:
        (np.ndarray, optional): the resulting decoded color image.
    """
    if dataset == 'pascal':
        n_classes = 21
        label_colours = get_pascal_labels()
    elif dataset == 'cityscapes':
        n_classes = 19
        label_colours = get_cityscapes_labels()
    else:
        raise NotImplementedError

    r = label_mask.copy()
    g = label_mask.copy()
    b = label_mask.copy()
    for ll in range(0, n_classes):
        r[label_mask == ll] = label_colours[ll, 0]
        g[label_mask == ll] = label_colours[ll, 1]
        b[label_mask == ll] = label_colours[ll, 2]
    rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3))
    rgb[:, :, 0] = r 
    rgb[:, :, 1] = g 
    rgb[:, :, 2] = b 
    #rgb = rgb.transpose((2,0,1))
    if plot:
        plt.imshow(rgb)
        plt.show()
    else:
        return rgb.astype(np.int32) 
Example 31
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: dcgan.py    Apache License 2.0 5 votes vote down vote up
def visual(title, X, name):
    assert len(X.shape) == 4
    X = X.transpose((0, 2, 3, 1))
    X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    buff = buff[:,:,::-1]
    plt.imshow(buff)
    plt.title(title)
    plt.savefig(name) 
Example 32
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: vis.py    Apache License 2.0 5 votes vote down vote up
def vis_detection(im_orig, detections, class_names, thresh=0.7):
    """visualize [cls, conf, x1, y1, x2, y2]"""
    import matplotlib.pyplot as plt
    import random
    plt.imshow(im_orig)
    colors = [(random.random(), random.random(), random.random()) for _ in class_names]
    for [cls, conf, x1, y1, x2, y2] in detections:
        cls = int(cls)
        if cls > 0 and conf > thresh:
            rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
                                 fill=False, edgecolor=colors[cls], linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(class_names[cls], conf),
                           bbox=dict(facecolor=colors[cls], alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 33
Project: black-widow   Author: BLQ-Software   File: run_interactive.py    MIT License 5 votes vote down vote up
def do_show(self, line):
        """Shows the network.

        Parameters
        ----------
        line : string
            A string containing command line arguments. Ignored.
        """
        try:
            # Get the pydot object for the network
            d = self.network.dump(self.output)

            # Set the dpi
            d.set_dpi(self.dpi)

            # Get a PNG string with the specified projection
            png_str = d.create_png(prog=self.proj)

            # Write the string to a StringIO object
            sio = StringIO()
            sio.write(png_str)
            sio.seek(0)

            # Show the image
            image = mpimg.imread(sio)
            plt.axis('off')
            plt.imshow(image)
            plt.show()
        except Exception as e:
            print e 
Example 34
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 35
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def plot_priors():
  g0s_prior_mean_bxn = train_modelvals['prior_g0_mean']
  g0s_prior_var_bxn = train_modelvals['prior_g0_var']
  g0s_post_mean_bxn = train_modelvals['posterior_g0_mean']
  g0s_post_var_bxn = train_modelvals['posterior_g0_var']

  plt.figure(figsize=(10,4), tight_layout=True);
  plt.subplot(1,2,1)
  plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b');
  plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g');

  plt.title('Histogram of Prior/Posterior Mean Values')
  plt.subplot(1,2,2)
  plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b');
  plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g');
  plt.title('Histogram of Prior/Posterior Log Variance Values')

  plt.figure(figsize=(10,10), tight_layout=True)
  plt.subplot(2,2,1)
  plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 means')

  plt.subplot(2,2,2)
  plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 means');

  plt.subplot(2,2,3)
  plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 variance Values')

  plt.subplot(2,2,4)
  plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 variance Values')

  plt.figure(figsize=(10,5))
  plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0))));
  plt.title('Log standard deviation of h0 means'); 
Example 36
Project: smach_based_introspection_framework   Author: birlrobotics   File: collect_classification_statistics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    try:
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')
    except FloatingPointError:
        print ('Error occurred: invalid value encountered in divide')
        sys.exit()
    
    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
Example 37
Project: Stegall   Author: mrT4ntr4   File: soxy.py    MIT License 5 votes vote down vote up
def show_image(width=None, height=None):
	import matplotlib.pyplot as plt
	import matplotlib.image as mpimg
	import matplotlib as mpl
	mpl.rcParams['savefig.pad_inches'] = 0
	figsize = None if width is None else (width, height)
	fig = plt.figure(figsize=figsize)
	ax = plt.axes([0,0,1,1], frameon=False)
	ax.get_xaxis().set_visible(False)
	ax.get_yaxis().set_visible(False)
	plt.autoscale(tight=True)
	img = mpimg.imread('spectrogram.png')
	plt.imshow(img)
	plt.show() 
Example 38
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 39
Project: ANN   Author: waynezv   File: ANN_large_v23.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 40
Project: ANN   Author: waynezv   File: ANN_large_v23.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 41
Project: ANN   Author: waynezv   File: ANN_large_v22.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 42
Project: ANN   Author: waynezv   File: ANN_large_v22.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 43
Project: ANN   Author: waynezv   File: ANN_large_v3.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 44
Project: ANN   Author: waynezv   File: ANN_large_v24.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 45
Project: ANN   Author: waynezv   File: ANN_large_v24.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 46
Project: ANN   Author: waynezv   File: ANN_v0.1.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 47
Project: ANN   Author: waynezv   File: ANN_large_v2.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 48
Project: ANN   Author: waynezv   File: ANN_large_v2.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 49
Project: ANN   Author: waynezv   File: ANN_large_v2.py    MIT License 5 votes vote down vote up
def test_net():
    num_samples = 86
    num_channels = 1
    num_rows = 66
    num_cols = 66
    label_size = 32
    dct_size = 25

    input_data = np.zeros((num_samples, num_channels, num_rows, num_cols))
    with h5.File('input_h5', 'r') as hf:
        input_data = np.array(hf['input_data'])

    with h5.File('output_h5', 'r') as hf:
        output_data = np.array(hf['output_data'])

    # Train
    ann = ANN()
    pred = ann.train_cnn(input_data, output_data)
    pred = pred.reshape(num_samples, dct_size, dct_size)

    images_pred = []
    for i in range(num_samples):
        dct_pr = pred[i,:]
        dct_pr_cp = np.zeros((label_size,label_size))
        dct_pr_cp[:dct_size,:dct_size] = dct_pr.copy()
        img_pr = get_2D_idct(dct_pr_cp)
        images_pred.append(img_pr)
    with h5.File('images_pred.h5', 'w') as hf:
        hf['images_pred'] = images_pred

    #  print('amp_pr is ')
    #  print(amp_pr)

    #  plt.figure()
    #  plt.imshow(amp_pr[0,:,:], extent=(0,0.1,0,0.1))
    #  plt.show() 
Example 50
Project: ANN   Author: waynezv   File: ANN_large.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show()