Tv.utils.make_grid(images) RuntimeError: The size of tensor a (480) must match the size of tensor b (640) at non-singleton dimension 3

I am using Torchvision to print off a grid of photos, and I get the following error message.

@staticmethod
def imshow(images):
    for image in images:
        print(f"image shape = {image.shape}")
    img = tv.utils.make_grid(images)

Details of run and error message (See that all the tensors are the same shape);


image shape = torch.Size([1, 1, 480, 640])
image shape = torch.Size([1, 1, 480, 640])
image shape = torch.Size([1, 1, 480, 640])
image shape = torch.Size([1, 1, 480, 640])
image shape = torch.Size([1, 1, 480, 640])
image shape = torch.Size([1, 1, 480, 640])
Traceback (most recent call last):
  File "c:\Users\hijik\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\hijik\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 
432, in main
    run()
  File "c:\Users\hijik\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 
316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\hijik\AppData\Local\Continuum\anaconda3\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\hijik\AppData\Local\Continuum\anaconda3\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\hijik\AppData\Local\Continuum\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\702\702-Coursework-Task-5\src\Main.py", line 91, in <module>
    Imagez.imshow(images)
  File "d:\702\702-Coursework-Task-5\src\imagez.py", line 27, in imshow
    img = torchvision.utils.make_grid(images)
  File "C:\Users\hijik\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\utils.py", line 85, in make_grid
    .copy_(tensor[k])
RuntimeError: The size of tensor a (480) must match the size of tensor b (640) at non-singleton 3

It seems you have an additional unnecessary dimension in images.
Could you remove dim1 or dim2 in images (both have the size 1) and it should work.

# Your error
images = torch.randn(6, 1, 1, 480, 640)
for img in images:
    print(img.shape)
img = make_grid(images)

# works
images = torch.randn(6, 1, 480, 640)
for img in images:
    print(img.shape)
img = make_grid(images)

I got rid of the single dimensions using;
img = torch.squeeze(img)

This gives image shape = torch.Size([480, 640])
I get an error message:

TypeError: Invalid shape (6, 480, 640) for image data

EDIT - I now realise that the maximum number of images that can be shown is 4, so by sending 4 images I get a shape of (480, 640, 4) and now I have a new problem; it only shows 1 image.

torch.squeeze will remove both single size dimension, so you should call images = images.squeeze(1) in my example.