Skip to content
Advertisement

How can I generate and display a grid of images in PyTorch with plt.imshow and torchvision.utils.make_grid?

I am trying to understand how torchvision interacts with mathplotlib to produce a grid of images. It’s easy to generate images and display them iteratively:

JavaScript

However, displaying these images in a grid does not seem to be as straightforward.

JavaScript

Even though PyTorch’s documentation indicates that w is the correct shape, Python says that it isn’t. So I tried to permute the indices of my tensor:

JavaScript

What’s happening here? How can I place a bunch of randomly generated images into a grid and display them?

Advertisement

Answer

There’s a small mistake in your code. torchvision.utils.make_grid() returns a tensor which contains the grid of images. But the channel dimension has to be moved to the end since that’s what matplotlib recognizes. Below is the code that works fine:

JavaScript

which shows the output as:

torchvision_make_grid

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement