如何将 ByteTensor 转换为图像张量?

How to convert a ByteTensor into an image tensor?

我正在通过 matlab 将图像转换为二进制文件,并尝试将二进制 matlab 向量 (1d) 加载到 python 并将它们转换为 ByteTensors:

img = np.fromfile(dir_train + image_name)
img = torch.ByteTensor(img) 

这很好用。 ByteTensors 是 2 维的。之后我想将它们转换回图像,就像重塑它们一样,因为神经网络 (resnet18) 需要 4 维张量。最好的方法是什么?

目前我的网络需要维度 [64, 3, 7, 7] 的张量,但字节张量是 [8, 1914]。

我是这样解决的:

img = np.fromfile(dir_train + image_name, 'bool')    # read in the binary file
img = img.reshape(1, 350, 350)    # reshape binary file
img = torch.ByteTensor(img)    # convert to ByteTensor
img = img.type(torch.FloatTensor)    # convert to FloatTensor

我认为没有比对 ByteTensor 进行类型转换更好的方法了。最重要的是,我更改了网络架构 (resnet18) 的第一个卷积层,以确保输入预期输入与 convertet 二进制输入相匹配。

resnet18.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)