【问题标题】:displaying grid of images in jupyter notebook在 jupyter notebook 中显示图像网格
【发布时间】:2018-05-10 12:41:05
【问题描述】:

我有一个包含 495 行 URL 的列的数据框。我想在 jupyter notebook 中将这些 URL 显示为图像网格。数据框的第一行显示在这里。任何帮助表示赞赏。

id           latitude     longitude     owner             title                          url
23969985288 37.721238   -123.071023 7679729@N07 There she blows!    https://farm5.staticflickr.com/4491/2396998528...

我试过以下方法,

from IPython.core.display import display, HTML
for index, row in data1.iterrows():
  display(HTML("<img src='%s'>"%(i["url"])))

但是,运行上述代码会显示消息

> TypeError                         Traceback (most recent call last)
<ipython-input-117-4c2081563c17> in <module>()
      1 from IPython.core.display import display, HTML
      2 for index, row in data1.iterrows():
----> 3   display(HTML("<img src='%s'>"%(i["url"])))

TypeError: string indices must be integers

【问题讨论】:

  • 请添加一些代码来显示您已经尝试过的内容。
  • 嗨,我已经添加了一些细节

标签: python html matplotlib jupyter-notebook


【解决方案1】:

您将IPython.core.display 与 HTML 结合使用的想法是完成此类任务的最佳方法。 matplotlib 在绘制如此大量的图像时效率极低(尤其是当您将它们作为 URL 时)。
我基于这个概念构建了一个小包——它叫做ipyplot

import ipyplot

images = data1['url'].values
labels = data1['id'].values

ipyplot.plot_images(images, labels, img_width=150)

你会得到一个类似这样的情节:

【讨论】:

【解决方案2】:

我只能通过“蛮力”做到这一点:

但是,我只能手动完成:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

%matplotlib inline

img1=mpimg.imread('Variable_8.png')
img2=mpimg.imread('Variable_17.png')
img3=mpimg.imread('Variable_18.png')
          ...

fig, ((ax1, ax2, ax3), (ax4,ax5,ax6)) = plt.subplots(2, 3, sharex=True, sharey=True) 

ax1.imshow(img1)
ax1.axis('off')
ax2.imshow(img2)
ax2.axis('off')
   ....

不知道有没有帮助

【讨论】:

【解决方案3】:

在 Jupyter 笔记本中显示图像网格的最佳方法可能是使用 matplotlib 创建网格,因为您还可以使用 imshowmatplotlib 轴上绘制图像。

我使用的是 3x165 网格,因为它正好是 495。随意摆弄它来改变网格的尺寸。

import urllib
f, axarr = plt.subplots(3, 165)
curr_row = 0
for index, row in data1.iterrows():
     # fetch the url as a file type object, then read the image
     f = urllib.request.urlopen(row["url"])
     a = plt.imread(f)

     # find the column by taking the current index modulo 3
     col = index % 3
     # plot on relevant subplot
     axarr[col,curr_row].imshow(a)
     if col == 2:
         # we have finished the current row, so increment row counter
         curr_row += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多