簡體   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