【问题标题】:Visualize list of images with matplotlib使用 matplotlib 可视化图像列表
【发布时间】:2021-02-27 04:24:57
【问题描述】:

我的数据集由 50 个大小为 8 x 8 的图像组成,这些图像被展平为大小为 64 的数组。使用 matplotlib.pyplot (plt) 的函数 imshow 可视化前 16 个图像(在 4x4 网格中)数据集。

我尝试了以下代码:

import matplotlib.pyplot as plt

import numpy as np
data = np.random.rand(50,64) #this will simulate my data

fig=plt.figure(figsize=(8, 8)) 
    
for i in range(16):
        
   img = np.reshape(data[i:(i+1)],(8,8))
   fig.add_subplot(4, 4, i)
   plt.imshow(img)
        
plt.show()

这是回溯:

<ipython-input-207-7af8d2013358> in plot_first_digits()
     13 
     14         img = np.reshape(X[i:(i+1)],(8,8))
---> 15         fig.add_subplot(4, 4, i)
     16         plt.imshow(img)
     17 

~/anaconda3/lib/python3.8/site-packages/matplotlib/figure.py in add_subplot(self, *args, **kwargs)
   1417                     self._axstack.remove(ax)
   1418 
-> 1419             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
   1420 
   1421         return self._add_axes_internal(key, a)

~/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs)
     63             else:
     64                 if num < 1 or num > rows*cols:
---> 65                     raise ValueError(
     66                         f"num must be 1 <= num <= {rows*cols}, not {num}")
     67                 self._subplotspec = GridSpec(

ValueError: num must be 1 <= num <= 16, not 0

<Figure size 576x576 with 0 Axes>

【问题讨论】:

  • 你能分享回溯吗?
  • 什么是回溯?
  • 运行此脚本时 Python 返回的错误

标签: python image numpy matplotlib image-processing


【解决方案1】:

从您的脚本中,我们可以看到错误是由于在第一次迭代时使用i = 0 调用plt.add_subplot() 造成的(此函数只接受正整数参数)。

fig.add_subplots 的解决方案 1

import matplotlib.pyplot as plt
import numpy as np

# simulate data
data = np.random.rand(50, 64)

# create figure
fig = plt.figure(figsize=(8, 8))

# loop over images
for i in range(16):
    print(i)
    img = np.reshape(data[i : (i + 1)], (8, 8))
    fig.add_subplot(4, 4, i + 1)
    plt.imshow(img)

# save image
plt.savefig("subplot_image")

输出图像如下:

plt.subplots 的解决方案 2(更多 Pythonic)

以下解决方案通过直接迭代生成plt.subplots() 的子图和data 矩阵的元素来生成相同的图像。

# create figure
fig, axes = plt.subplots(4, 4, figsize=(8, 8))

# loop over images
for ax, img in zip(axes.ravel(), data):
    ax.imshow(img.reshape(8, 8))

# save image
plt.savefig("subplot_image")

【讨论】:

    【解决方案2】:

    尝试使用Image Grid,如下所示:

    from mpl_toolkits.axes_grid1 import ImageGrid
    
    def show_images(images):
      fig = plt.figure(figsize=(12., 12.))
      grid = ImageGrid(fig, 111, nrows_ncols=(1, len(images)),axes_pad=0.1)
    
      for ax, im in zip(grid, images):
        ax.axis('off')
        ax.imshow(im, cmap="gray")
    
    sample_negative = ~sample1
    show_images([sample1, sample_negative])
    

    密切关注构造函数。您正在传递您希望如何对齐图像的图形、行数和列数。在上面的示例中,我将所有图像对齐在一行中。下面是输出的样子:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2017-09-14
      • 2021-11-04
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多