gpt4 book ai didi

python - 将卷积操作应用于图像 - PyTorch

转载 作者:行者123 更新时间:2023-12-04 01:55:07 25 4
gpt4 key购买 nike

如果形状为 27x35,我使用以下方法渲染图像:

random_image = []
for x in range(1 , 946):
random_image.append(random.randint(0 , 255))

random_image_arr = np.array(random_image)
matplotlib.pyplot.imshow(random_image_arr.reshape(27 , 35))

这会产生:

enter image description here

然后我尝试使用 torch.nn.Conv2d 对图像应用卷积。 :
conv2 = torch.nn.Conv2d(3, 18, kernel_size=3, stride=1, padding=1)

image_d = np.asarray(random_image_arr.reshape(27 , 35))

conv2(torch.from_numpy(image_d))

但这显示错误:
~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input)
299 def forward(self, input):
300 return F.conv2d(input, self.weight, self.bias, self.stride,
--> 301 self.padding, self.dilation, self.groups)
302
303

RuntimeError: input has less dimensions than expected

输入的形状 image_d(27, 35)
我应该更改 Conv2d的参数吗?为了将卷积应用于图像?

更新。从@McLawrence 回答我有:
random_image = []
for x in range(1 , 946):
random_image.append(random.randint(0 , 255))

random_image_arr = np.array(random_image)
matplotlib.pyplot.imshow(random_image_arr.reshape(27 , 35))

这呈现图像:

enter image description here

应用卷积操作:
conv2 = torch.nn.Conv2d(1, 18, kernel_size=3, stride=1, padding=1)

image_d = torch.FloatTensor(np.asarray(random_image_arr.reshape(1, 1, 27 , 35))).numpy()

fc = conv2(torch.from_numpy(image_d))

matplotlib.pyplot.imshow(fc[0][0].data.numpy())

渲染图像:

enter image description here

最佳答案

您的代码有两个问题:

首先,pytorch中的2d卷积是 defined仅适用于 4d 张量。
这在神经网络中使用起来很方便。第一个维度是批量大小,而第二个维度是 channel (例如,RGB 图像具有三个 channel )。所以你必须像这样 reshape 你的张量

image_d = torch.FloatTensor(np.asarray(random_image_arr.reshape(1, 1, 27 , 35)))
FloatTensor在这里很重要,因为卷积没有在 LongTensor 上定义如果您的 numpy 将自动创建数组仅包含 int s。

其次,您创建了一个具有三个输入 channel 的卷积,而您的图像只有一个 channel (它是灰度)。所以你必须将卷积调整为:
conv2 = torch.nn.Conv2d(1, 18, kernel_size=3, stride=1, padding=1)

关于python - 将卷积操作应用于图像 - PyTorch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com