LoginSignup
7
1

More than 3 years have passed since last update.

[エラー] The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0

Posted at

The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0

[忙しい人のための解決策]

#後ろにconvert('RGB)をつけてchannels数を3に変更する
input_image = Image.open(filename).convert('RGB')

[原因] 入力された画像のchannel数が4であるために3に戻してあげる必要がある。

<該当コード>

from torchvision import transforms

input_image = Image.open('test.png')  #ここが問題

preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
input_tensor = preprocess(input_image)

<エラー画像>

<訂正後のコード>

from torchvision import transforms

input_image = Image.open('test.png')  #ここを訂正した

preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
input_tensor = preprocess(input_image)

参考

7
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1