Skip to main content
 首页 » 编程设计

python之如何加载图像并将其转换为适合 PyTorch 的张量

2024年12月31日11qq78292959

我正在尝试使用一些标签自定义加载一些图像文件(JPG 文件),并按照示例 here 将它们送入 PyTorch 中的卷积神经网络 (CNN)。 .但是,似乎仍然存在 no decent end-to-end tutorials .我看到的问题如下。

RuntimeError: thnn_conv2d_forward is not implemented for type 
torch.ByteTensor 

我的数据集如下所示。

class ImageData(Dataset): 
    def __init__(self, width=256, height=256, transform=None): 
        self.width = width 
        self.height = height 
        self.transform = transform 
        y, x = get_images() #y is a list of labels, x is a list of file paths 
        self.y = y 
        self.x = x 
 
    def __getitem__(self, index): 
        img = Image.open(self.x[index]) # use pillow to open a file 
        img = img.resize((self.width, self.height)) # resize the file to 256x256 
        img = img.convert('RGB') #convert image to RGB channel 
        if self.transform is not None: 
            img = self.transform(img) 
 
        img = np.asarray(img).transpose(-1, 0, 1) # we have to change the dimensions from width x height x channel (WHC) to channel x width x height (CWH) 
        img = torch.from_numpy(np.asarray(img)) # create the image tensor 
        label = torch.from_numpy(np.asarray(self.y[index]).reshape([1, 1])) # create the label tensor 
        return img, label 
 
    def __len__(self): 
        return len(self.x) 

CNN 摘自here并修改为处理 NCWH(批处理 x channel x 宽度 x 高度),如下所示。

class Net(nn.Module): 
    def __init__(self): 
        super(Net, self).__init__() 
        self.conv1 = nn.Conv2d(3, 256, 256) 
        self.pool = nn.MaxPool2d(2, 2) 
        self.conv2 = nn.Conv2d(6, 16, 5) 
        self.fc1 = nn.Linear(16 * 5 * 5, 120) 
        self.fc2 = nn.Linear(120, 84) 
        self.fc3 = nn.Linear(84, 10) 
 
    def forward(self, x): 
        x = self.pool(F.relu(self.conv1(x))) 
        x = self.pool(F.relu(self.conv2(x))) 
        x = x.view(-1, 16 * 5 * 5) 
        x = F.relu(self.fc1(x)) 
        x = F.relu(self.fc2(x)) 
        x = self.fc3(x) 
        return x 

学习循环也取自 same tutorial看起来像下面这样。

for epoch in range(2):  # loop over the dataset multiple times 
 
    running_loss = 0.0 
    for i, data in enumerate(dataloader, 0): 
        # get the inputs 
        inputs, labels = data 
 
        # zero the parameter gradients 
        optimizer.zero_grad() 
 
        # forward + backward + optimize 
        outputs = net(inputs) 
        loss = criterion(outputs, labels) 
        loss.backward() 
        optimizer.step() 
 
        # print statistics 
        running_loss += loss.item() 
        if i % 2000 == 1999:    # print every 2000 mini-batches 
            print('[%d, %5d] loss: %.3f' % 
                  (epoch + 1, i + 1, running_loss / 2000)) 
            running_loss = 0.0 
 
print('Finished Training') 

但是会抛出上面提到的RuntimeError。关于我做错了什么的任何想法?

另外,我知道在不转置图像数据的情况下,它是WHC的形状,但是NN模型要求它是CWH。问题是,如果我们从 WHC 更改为 CWH,那么如果我们遍历 DataLoader,就不能再简单地绘制图像。

data = ImageData() 
dataloader = DataLoader(data, batch_size=10, shuffle=True, num_workers=1) 
imgs, labels = next(iter(dataloader)) 
plt.imshow(imgs.numpy()[0,:,:,:]) 
plt.show() 

尝试这样做会抛出以下错误。

TypeError: Invalid dimensions for image data 

对我来说,那个 Pillow 给你 WHC,你可以用它来绘图,但是 PyTorch CNN 想要 CWH 来处理,这很麻烦。关于如何始终如一或轻松地不进行如此多的转换但能够绘制数据并将其馈送到 CNN 的任何想法?或者,这种 WHC 与 CWH 的不匹配是我们不得不忍受的吗?

在不转置图像的情况下,将其提供给 CNN 时,会抛出以下错误。

RuntimeError: Given groups=1, weight[256, 3, 256, 256], so expected 
input[10, 256, 256, 3] to have 3 channels, but got 256 channels 

相反。

请您参考如下方法:

conv2d 对浮点张量进行操作。在将输入图像传递到神经网络之前对其进行归一化是一种常见的良好做法。

我会在 __getitem__ 中将其转换为 Torch 张量之前立即添加 img = img/255 行,然后它将转换为 float 张量而不是 byte 张量,因此将与 conv2d 方法兼容。