繁体   English   中英

使用 matplotlib 并排绘制图像

[英]Plotting images side by side using matplotlib

我想知道如何使用matplotlib并排显示 plot 个图像,例如:

在此处输入图像描述

我得到的最接近的是:

在此处输入图像描述

这是使用以下代码生成的:

f, axarr = plt.subplots(2,2)
axarr[0,0] = plt.imshow(image_datas[0])
axarr[0,1] = plt.imshow(image_datas[1])
axarr[1,0] = plt.imshow(image_datas[2])
axarr[1,1] = plt.imshow(image_datas[3])

但我似乎无法显示其他图像。 我认为必须有更好的方法来执行此操作,因为我认为尝试管理索引会很痛苦。 我已经查看了文档,尽管我觉得我可能看错了文档。 谁能给我举个例子或给我指明正确的方向?

编辑:

如果您希望 function 自动确定网格大小,请参阅@duhaime答案

您面临的问题是您尝试imshow的返回imshow (它是一个matplotlib.image.AxesImage分配给现有的轴对象。

将图像数据绘制到axarr不同轴的正确方法是

f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])

所有子图的概念都是相同的,并且在大多数情况下,轴实例提供与 pyplot (plt) 接口相同的方法。 例如,如果ax是您的子图轴之一,为了绘制法线图,您将使用ax.plot(..)而不是plt.plot() 这实际上可以在您链接到的页面的源中找到。

我发现用于打印所有图像非常有帮助的一件事:

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

您正在一个轴上绘制所有图像。 您想要的是分别获得每个轴的句柄并在那里绘制图像。 像这样:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)

有关更多信息,请查看此处: http : //matplotlib.org/examples/pylab_examples/subplots_demo.html

对于复杂的布局,您应该考虑使用 gridspec: http ://matplotlib.org/users/gridspec.html

如果图像在数组中,并且您想遍历每个元素并打印它,则可以编写如下代码:

plt.figure(figsize=(10,10)) # specifying the overall grid size

for i in range(25):
    plt.subplot(5,5,i+1)    # the number of images in the grid is 5*5 (25)
    plt.imshow(the_array[i])

plt.show()

另请注意,我使用了子图而不是子图。 他们都不同

根据matplotlib 对图像网格的建议

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

下面是一个完整的函数show_image_list() ,它在网格中并排显示图像。 您可以使用不同的参数调用该函数。

  1. 传入图像list ,其中每个图像都是一个 Numpy 数组。 默认情况下,它将创建一个包含 2 列的网格。 它还将推断每个图像是彩色还是灰度。
list_images = [img, gradx, grady, mag_binary, dir_binary]

show_image_list(list_images, figsize=(10, 10))

在此处输入图片说明

  1. 通过在list的图像,一个的list标题为每个图像的,而其他参数。
show_image_list(list_images=[img, gradx, grady, mag_binary, dir_binary], 
                list_titles=['original', 'gradx', 'grady', 'mag_binary', 'dir_binary'],
                num_cols=3,
                figsize=(20, 10),
                grid=False,
                title_fontsize=20)

在此处输入图片说明

这是代码:

import matplotlib.pyplot as plt
import numpy as np

def img_is_color(img):

    if len(img.shape) == 3:
        # Check the color channels to see if they're all the same.
        c1, c2, c3 = img[:, : , 0], img[:, :, 1], img[:, :, 2]
        if (c1 == c2).all() and (c2 == c3).all():
            return True

    return False

def show_image_list(list_images, list_titles=None, list_cmaps=None, grid=True, num_cols=2, figsize=(20, 10), title_fontsize=30):
    '''
    Shows a grid of images, where each image is a Numpy array. The images can be either
    RGB or grayscale.

    Parameters:
    ----------
    images: list
        List of the images to be displayed.
    list_titles: list or None
        Optional list of titles to be shown for each image.
    list_cmaps: list or None
        Optional list of cmap values for each image. If None, then cmap will be
        automatically inferred.
    grid: boolean
        If True, show a grid over each image
    num_cols: int
        Number of columns to show.
    figsize: tuple of width, height
        Value to be passed to pyplot.figure()
    title_fontsize: int
        Value to be passed to set_title().
    '''

    assert isinstance(list_images, list)
    assert len(list_images) > 0
    assert isinstance(list_images[0], np.ndarray)

    if list_titles is not None:
        assert isinstance(list_titles, list)
        assert len(list_images) == len(list_titles), '%d imgs != %d titles' % (len(list_images), len(list_titles))

    if list_cmaps is not None:
        assert isinstance(list_cmaps, list)
        assert len(list_images) == len(list_cmaps), '%d imgs != %d cmaps' % (len(list_images), len(list_cmaps))

    num_images  = len(list_images)
    num_cols    = min(num_images, num_cols)
    num_rows    = int(num_images / num_cols) + (1 if num_images % num_cols != 0 else 0)

    # Create a grid of subplots.
    fig, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
    
    # Create list of axes for easy iteration.
    if isinstance(axes, np.ndarray):
        list_axes = list(axes.flat)
    else:
        list_axes = [axes]

    for i in range(num_images):

        img    = list_images[i]
        title  = list_titles[i] if list_titles is not None else 'Image %d' % (i)
        cmap   = list_cmaps[i] if list_cmaps is not None else (None if img_is_color(img) else 'gray')
        
        list_axes[i].imshow(img, cmap=cmap)
        list_axes[i].set_title(title, fontsize=title_fontsize) 
        list_axes[i].grid(grid)

    for i in range(num_images, len(list_axes)):
        list_axes[i].set_visible(False)

    fig.tight_layout()
    _ = plt.show()

我大约每周访问一次这个网址。 对于那些想要一个可以轻松绘制图像网格的小功能的人来说,我们开始吧:

import matplotlib.pyplot as plt
import numpy as np

def plot_image_grid(images, ncols=None, cmap='gray'):
    '''Plot a grid of images'''
    if not ncols:
        factors = [i for i in range(1, len(images)+1) if len(images) % i == 0]
        ncols = factors[len(factors) // 2] if len(factors) else len(images) // 4 + 1
    nrows = int(len(images) / ncols) + int(len(images) % ncols)
    imgs = [images[i] if len(images) > i else None for i in range(nrows * ncols)]
    f, axes = plt.subplots(nrows, ncols, figsize=(3*ncols, 2*nrows))
    axes = axes.flatten()[:len(imgs)]
    for img, ax in zip(imgs, axes.flatten()): 
        if np.any(img):
            if len(img.shape) > 2 and img.shape[2] == 1:
                img = img.squeeze()
            ax.imshow(img, cmap=cmap)

# make 16 images with 60 height, 80 width, 3 color channels
images = np.random.rand(16, 60, 80, 3)

# plot them
plot_image_grid(images)

可视化数据集中的一张随机图像的示例代码

def get_random_image(num):
    path=os.path.join("/content/gdrive/MyDrive/dataset/",images[num])
    image=cv2.imread(path)
    return image

拨打function

images=os.listdir("/content/gdrive/MyDrive/dataset")
random_num=random.randint(0, len(images))
img=get_random_image(random_num)
plt.figure(figsize=(8,8))
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))

显示给定数据集中的随机图像簇

#Making a figure containing 16 images 
lst=random.sample(range(0,len(images)), 16)
plt.figure(figsize=(12,12))
for index,value in  enumerate(lst):
    img=get_random_image(value)
    img_resized=cv2.resize(img,(400,400))
    #print(path)
    plt.subplot(4,4,index+1)
    plt.imshow(img_resized)
    plt.axis('off')

plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
#plt.savefig(f"Images/{lst[0]}.png")
plt.show() 

绘制数据集中存在的图像 这里 rand 给出了一个随机索引值,用于选择数据集中存在的随机图像,labels 具有每种图像类型的整数表示,labels_dict 是一个包含关键 val 信息的字典

fig,ax = plt.subplots(5,5,figsize = (15,15))
ax = ax.ravel()
for i in range(25):
  rand = np.random.randint(0,len(image_dataset))
  image = image_dataset[rand]
  ax[i].imshow(image,cmap = 'gray')
  ax[i].set_title(labels_dict[labels[rand]])
  
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM