当前位置: 首页>>代码示例>>Python>>正文


Python pyplot.imshow方法代码示例

本文整理汇总了Python中matplotlib.pyplot.imshow方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.imshow方法的具体用法?Python pyplot.imshow怎么用?Python pyplot.imshow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.pyplot的用法示例。


在下文中一共展示了pyplot.imshow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: save_frames

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def save_frames(images, filename):
    num_sequences, n_steps, w, h = images.shape

    fig = plt.figure()
    im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('Greys'), interpolation='none')
    plt.axis('image')

    def updatefig(*args):
        im.set_array(combine_multiple_img(images[:, args[0]]))
        return im,

    ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)

    # Either avconv or ffmpeg need to be installed in the system to produce the videos!
    try:
        writer = animation.writers['avconv']
    except KeyError:
        writer = animation.writers['ffmpeg']
    writer = writer(fps=3)
    ani.save(filename, writer=writer)
    plt.close(fig) 
开发者ID:simonkamronn,项目名称:kvae,代码行数:23,代码来源:movie.py

示例2: show_result_pyplot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)):
    """Visualize the detection results on the image.

    Args:
        model (nn.Module): The loaded detector.
        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.
        score_thr (float): The threshold to visualize the bboxes and masks.
        fig_size (tuple): Figure size of the pyplot figure.
    """
    if hasattr(model, 'module'):
        model = model.module
    img = model.show_result(img, result, score_thr=score_thr, show=False)
    plt.figure(figsize=fig_size)
    plt.imshow(mmcv.bgr2rgb(img))
    plt.show() 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:19,代码来源:inference.py

示例3: plot_n_image

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
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([])) 
开发者ID:wdxtub,项目名称:deep-learning-note,代码行数:19,代码来源:8_kmeans_pca.py

示例4: visualize_sampling

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def visualize_sampling(self,permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0
        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations
        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show()

    # Heatmap of attention (x=cities; y=steps) 
开发者ID:MichelDeudon,项目名称:neural-combinatorial-optimization-rl-tensorflow,代码行数:23,代码来源:dataset.py

示例5: visualize_sampling

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def visualize_sampling(self, permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0

        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations

        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show() 
开发者ID:MichelDeudon,项目名称:neural-combinatorial-optimization-rl-tensorflow,代码行数:23,代码来源:dataset.py

示例6: plot_some_results

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
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 
开发者ID:Lasagne,项目名称:Recipes,代码行数:22,代码来源:massachusetts_road_segm.py

示例7: classify

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def classify(self, features, show=False):
        recs, _ = features.shape
        result_shape = (features.shape[0], len(self.root))
        scores = np.zeros(result_shape)
        print scores.shape
        R = Record(np.arange(recs, dtype=int), features)

        for i, T in enumerate(self.root):
            for idxs, result in classify(T, R):
                for idx in idxs.indexes():
                    scores[idx, i] = float(result[0]) / sum(result.values())


        if show:
            plt.cla()
            plt.clf()
            plt.close()

            plt.imshow(scores, cmap=plt.cm.gray)
            plt.title('Scores matrix')
            plt.savefig(r"../scratch/tree_scores.png", bbox_inches='tight')
        
        return scores 
开发者ID:gdanezis,项目名称:trees,代码行数:25,代码来源:malware.py

示例8: preprocess_image

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def preprocess_image(img_path):
    img = io.imread(img_path)
    if np.max(img.shape[:2]) != config.img_size:
        print('Resizing so the max image size is %d..' % config.img_size)
        scale = (float(config.img_size) / np.max(img.shape[:2]))
    else:
        scale = 1.0#scaling_factor
    center = np.round(np.array(img.shape[:2]) / 2).astype(int)
    # image center in (x,y)
    center = center[::-1]
    crop, proc_param = img_util.scale_and_crop(img, scale, center,
                                               config.img_size)
    # import ipdb; ipdb.set_trace()
    # Normalize image to [-1, 1]
    # plt.imshow(crop/255.0)
    # plt.show()
    crop = 2 * ((crop / 255.) - 0.5)

    return crop, proc_param, img 
开发者ID:soubhiksanyal,项目名称:RingNet,代码行数:21,代码来源:demo.py

示例9: plot_attention

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def plot_attention(sentences, attentions, labels, **kwargs):
    fig, ax = plt.subplots(**kwargs)
    im = ax.imshow(attentions, interpolation='nearest',
                   vmin=attentions.min(), vmax=attentions.max())
    plt.colorbar(im, shrink=0.5, ticks=[0, 1])
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")
    ax.set_yticks(range(len(labels)))
    ax.set_yticklabels(labels, fontproperties=getChineseFont())
    # Loop over data dimensions and create text annotations.
    for i in range(attentions.shape[0]):
        for j in range(attentions.shape[1]):
            text = ax.text(j, i, sentences[i][j],
                           ha="center", va="center", color="b", size=10,
                           fontproperties=getChineseFont())

    ax.set_title("Attention Visual")
    fig.tight_layout()
    plt.show() 
开发者ID:EvilPsyCHo,项目名称:TaskBot,代码行数:21,代码来源:plot.py

示例10: show_landmarks

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def show_landmarks(image, heatmap, gt_landmarks, gt_heatmap):
    """Show image with pred_landmarks"""
    pred_landmarks = []
    pred_landmarks, _ = get_preds_fromhm(torch.from_numpy(heatmap).unsqueeze(0))
    pred_landmarks = pred_landmarks.squeeze()*4

    # pred_landmarks2 = get_preds_fromhm2(heatmap)
    heatmap = np.max(gt_heatmap, axis=0)
    heatmap = heatmap / np.max(heatmap)
    # image = ski_transform.resize(image, (64, 64))*255
    image = image.astype(np.uint8)
    heatmap = np.max(gt_heatmap, axis=0)
    heatmap = ski_transform.resize(heatmap, (image.shape[0], image.shape[1]))
    heatmap *= 255
    heatmap = heatmap.astype(np.uint8)
    heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
    plt.imshow(image)
    plt.scatter(gt_landmarks[:, 0], gt_landmarks[:, 1], s=0.5, marker='.', c='g')
    plt.scatter(pred_landmarks[:, 0], pred_landmarks[:, 1], s=0.5, marker='.', c='r')
    plt.pause(0.001)  # pause a bit so that plots are updated 
开发者ID:protossw512,项目名称:AdaptiveWingLoss,代码行数:22,代码来源:utils.py

示例11: test

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def test(self):

        list_ = os.listdir("./maps/val/")
        nums_file = list_.__len__()
        saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, "generator"))
        saver.restore(self.sess, "./save_para/model.ckpt")
        rand_select = np.random.randint(0, nums_file)
        INPUTS_CONDITION = np.zeros([1, self.img_h, self.img_w, 3])
        INPUTS = np.zeros([1, self.img_h, self.img_w, 3])
        img = np.array(Image.open(self.path + list_[rand_select]))
        img_h, img_w = img.shape[0], img.shape[1]
        INPUTS_CONDITION[0] = misc.imresize(img[:, img_w//2:], [self.img_h, self.img_w]) / 127.5 - 1.0
        INPUTS[0] = misc.imresize(img[:, :img_w//2], [self.img_h, self.img_w]) / 127.5 - 1.0
        [fake_img] = self.sess.run([self.inputs_fake], feed_dict={self.inputs_condition: INPUTS_CONDITION})
        out_img = np.concatenate((INPUTS_CONDITION[0], fake_img[0], INPUTS[0]), axis=1)
        Image.fromarray(np.uint8((out_img + 1.0)*127.5)).save("./results/1.jpg")
        plt.imshow(np.uint8((out_img + 1.0)*127.5))
        plt.grid("off")
        plt.axis("off")
        plt.show() 
开发者ID:MingtaoGuo,项目名称:Chinese-Character-and-Calligraphic-Image-Processing,代码行数:22,代码来源:test.py

示例12: generate_png_chess_dp_vertex

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def generate_png_chess_dp_vertex(self):
    """Produces pictures of the dominant product vertex a chessboard convention"""
    import matplotlib.pylab as plt
    plt.ioff()
    dab2v = self.get_dp_vertex_doubly_sparse()
    for i, ab in enumerate(dab2v): 
        fname = "chess-v-{:06d}.png".format(i)
        print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname)
        if type(ab) != 'numpy.ndarray': ab = ab.toarray()
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        plt.close(fig) 
开发者ID:pyscf,项目名称:pyscf,代码行数:18,代码来源:prod_basis.py

示例13: save_movie_to_frame

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def save_movie_to_frame(images, filename, idx=0, cmap='Blues'):
    # Collect to single image
    image = movie_to_frame(images[idx])

    # Flip it
    # image = np.fliplr(image)
    # image = np.flipud(image)

    f = plt.figure(figsize=[12, 12])
    plt.imshow(image, cmap=plt.cm.get_cmap(cmap), interpolation='none', vmin=0, vmax=1)

    plt.axis('image')
    plt.xticks([])
    plt.yticks([])
    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close(f) 
开发者ID:simonkamronn,项目名称:kvae,代码行数:18,代码来源:movie.py

示例14: save_movies_to_frame

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def save_movies_to_frame(images, filename, cmap='Blues'):
    # Binarize images
    # images[images > 0] = 1.

    # Grid images
    images = np.swapaxes(images, 1, 0)
    images = np.array([combine_multiple_img(image) for image in images])

    # Collect to single image
    image = movie_to_frame(images)

    f = plt.figure(figsize=[12, 12])
    plt.imshow(image, cmap=plt.cm.get_cmap(cmap), interpolation='none', vmin=0, vmax=1)
    plt.axis('image')
    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close(f) 
开发者ID:simonkamronn,项目名称:kvae,代码行数:18,代码来源:movie.py

示例15: test_interpolate_grid_const_nn

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import imshow [as 别名]
def test_interpolate_grid_const_nn(self, sphere3_msh):
        data = sphere3_msh.elm.tag1
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        n = (200, 10, 1)
        affine = np.array([[1, 0, 0, -100.5],
                           [0, 1, 0, -5],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]], dtype=float)
        interp = f.interpolate_to_grid(n, affine, method='assign')
        '''
        import matplotlib.pyplot as plt
        plt.imshow(np.squeeze(interp))
        plt.colorbar()
        plt.show()
        assert False
        '''
        assert np.isclose(interp[100, 5, 0], 3)
        assert np.isclose(interp[187, 5, 0], 4)
        assert np.isclose(interp[193, 5, 0], 5)
        assert np.isclose(interp[198, 5, 0], 0) 
开发者ID:simnibs,项目名称:simnibs,代码行数:22,代码来源:test_mesh_io.py


注:本文中的matplotlib.pyplot.imshow方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。