首页 > 解决方案 > 将另一个函数生成的图像放入子图中

问题描述

所以我得到了一个函数 show_image ,它接受一个数组,基本上调用

plt.imshow(img, cmap='gray')
plt.axis('off')

在它的身体里。它正确显示图像,没问题。

我被要求用这个函数创建四个图像,并将它们显示在一个图中,每个都作为一个子图。我认为我必须使用该函数并且不应该更改该函数内部的内容(所以我不能添加新的返回或任何东西)

我不确定如何让图像显示/排列为更大图像的子图。我试过了

fig, ([ax1, ax2], [ax3, ax4]) = plt.subplots(2, 2,figsize=(12,16))
ax1 = show_image(image)
ax2 = show_image(log)
...

但这没有用。具体来说,似乎只创建了最后一张图像,并且该图像始终显示在右下角的子图中。我还能做什么?

标签: pythonmatplotlibsubplot

解决方案


您可以在函数中使用绘图show_image功能

import matplotlib.pyplot as plt
import numpy as np

def show_image(*images):
    # get the 4 subplots
    fig, ax = plt.subplots(2, 2,figsize=(12,16))
    # now assign each images to each subplot
    ax[0][0].imshow(images[0], cmap='gray')
    ax[0][1].imshow(images[1], cmap='gray')
    ax[1][0].imshow(images[2], cmap='gray')
    ax[1][1].imshow(images[3], cmap='gray')
    plt.axis('off')
    
arr1 = np.random.randint(255, size=(28,28))
arr2 = np.random.randint(255, size=(28,28))
arr3 = np.random.randint(255, size=(28,28))
arr4 = np.random.randint(255, size=(28,28))

show_image(arr1, arr2, arr3, arr4)

推荐阅读