使用matplotlib/pytorch从批处理中创建张量的图像网格

发布于 2025-02-12 01:21:01 字数 754 浏览 1 评论 0原文

我正在尝试从一批张量的图像网格(例如3 x 3)创建,这些张量将在下一步中通过数据加载器馈入GAN。使用以下代码,我能够将张量转换为以正确位置的网格显示的图像。问题是,它们全部显示在单独的网格中,如下所示:图1 a href =“ https://i.sstatic.net/tcjww.png” rel =“ nofollow noreferrer”>图2 图5 。如何将它们放在一个网格中,然后将一个数字带有所有9张图像?也许我使它变得太复杂了。 :d最终必须将the the the示例张开并放入网格中。

real_samples = next(iter(train_loader))
for i in range(9):
    plt.figure(figsize=(9, 9))
    plt.subplot(330 + i + 1)
    plt.imshow(np.transpose(vutils.make_grid(real_samples[i].to(device)
                      [:40], padding=1, normalize=True).cpu(),(1,2,0)))
    plt.show()

I am trying to create a grid of images (e.g. 3 by 3) from a batch of tensors that will be fed into a GAN through a data loader in the next step. With the below code I was able to transform the tensors into images that are displayed in a grid in the right position. The problem is, that they are all displayed in a separate grid as shown here: Figure 1 Figure 2 Figure 5. How can put them in one grid and just get one figure returned with all 9 images?? Maybe I am making it too complicated. :D In the end tensors out of the real_samples have to be transformed and put into a grid.

real_samples = next(iter(train_loader))
for i in range(9):
    plt.figure(figsize=(9, 9))
    plt.subplot(330 + i + 1)
    plt.imshow(np.transpose(vutils.make_grid(real_samples[i].to(device)
                      [:40], padding=1, normalize=True).cpu(),(1,2,0)))
    plt.show()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌生 2025-02-19 01:21:01

这是如何使用matplotlib XD显示可变数量的奇妙加密库,

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

row_count = 3
col_count = 3

cryptopunks = [
    mpimg.imread(f"cryptopunks/{i}.png") for i in range(row_count * col_count)
]

fig = plt.figure(figsize=(8., 8.))
grid = ImageGrid(fig, 111, nrows_ncols=(row_count, col_count), axes_pad=0.1)

for ax, im in zip(grid, cryptopunks):
    ax.imshow(im)

plt.show()

/I.SSTATIC.NET/7X7GI.PNG“ ALT =”在此处输入图像描述>

请注意,代码允许您生成所需的所有图像,而不仅仅是3次3。我有一个文件夹cryptopunks带有许多称为#的图像。PNG(例如,1.png,...,34.png 代码>,...)。只需更改row_countcol_count变量值。例如,对于row_count = 6col_count = 8您得到:

如果您的图像文件没有上面的命名模式(即,只是随机名称),只需将第一行替换为以下一行:(

import os
from pathlib import Path

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

for root, _, filenames in os.walk("cryptopunks/"):
    cryptopunks = [
        mpimg.imread(Path(root, filename)) for filename in filenames
    ]

row_count = 3
col_count = 3

# Here same code as above.

我已经从 kaggle

And here is how to display a variable number of wonderful CryptoPunks using matplotlib XD:

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

row_count = 3
col_count = 3

cryptopunks = [
    mpimg.imread(f"cryptopunks/{i}.png") for i in range(row_count * col_count)
]

fig = plt.figure(figsize=(8., 8.))
grid = ImageGrid(fig, 111, nrows_ncols=(row_count, col_count), axes_pad=0.1)

for ax, im in zip(grid, cryptopunks):
    ax.imshow(im)

plt.show()

enter image description here

Please note that the code allows you to generate all the images you want, not only 3 times 3. I have a folder called cryptopunks with a lot of images called #.png (e.g., 1.png, ..., 34.png, ...). Just change the row_count and col_count variable values. For instance, for row_count=6 and col_count=8 you get:
enter image description here

If your image files do not have that naming pattern above (i.e., just random names), just replace the first lines with the following ones:

import os
from pathlib import Path

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

for root, _, filenames in os.walk("cryptopunks/"):
    cryptopunks = [
        mpimg.imread(Path(root, filename)) for filename in filenames
    ]

row_count = 3
col_count = 3

# Here same code as above.

(I have downloaded the CryptoPunks dataset from Kaggle.)

疾风者 2025-02-19 01:21:01

对于9个图像网格,您可能需要三行和三列。最简单的方法可能就是这样:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=3)
axes = axes.flatten() # Flattens the array so you can access individual axes

for ax in axes:
    # Do stuff with your individual axes here
    plt.show() # This call is here just for example, prob. better call outside of the loop

输出以下轴配置

它以plt.tight_layout()

“ rel =“ nofollow noreferrer”> matplotlib mosaic mosaic mosaic 功能功能/stable/_as_gen/matplotlib.gridspec.gridspec.html“ rel =” nofollow noreferrer“> gridspec One 。希望这会有所帮助。

编辑:这是一个解决方案,可以注释每个图的编号,以便您可以看到什么也是如此:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=3)
axes = axes.flatten()

for idx, ax in enumerate(axes):
    ax.annotate(f"{idx+1}", xy=(0.5, 0.5), xytext=(0.5, 0.5))

“带注释”

For a 9 image grid you probably want three rows and three columns. Probably the simplest way to do that is something like so:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=3)
axes = axes.flatten() # Flattens the array so you can access individual axes

for ax in axes:
    # Do stuff with your individual axes here
    plt.show() # This call is here just for example, prob. better call outside of the loop

which outputs the following axes configuration with plt.tight_layout():

3x3 image grid

You might also be interested in the matplotlib mosaic functionality or gridspec one. Hope this helps.

EDIT: Here's a solution which annotates each plot with its number so you can see what goes where as well:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=3)
axes = axes.flatten()

for idx, ax in enumerate(axes):
    ax.annotate(f"{idx+1}", xy=(0.5, 0.5), xytext=(0.5, 0.5))

with annotations

热情消退 2025-02-19 01:21:01

Matplotlib提供了一个称为子图的函数,我认为这就是您要搜索的!

我猜是语法。

然后配置您的图

Matplotlib provides a function called subplot, I think this is what you are searching for!

plt.subplot(9,1) is the syntax I guess.

And then configure your plots

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文