代码之家  ›  专栏  ›  技术社区  ›  blue-sky

卷积运算在图像处理中的应用

  •  0
  • blue-sky  · 技术社区  · 7 年前

    要在形状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的回答中我得到了:

    随机图像=[]
    对于范围(1946)内的x:
    random_image.append(random.randint(0,255))
    
    随机图像arr=np.数组(随机图像)
    matplotlib.pyplot.imshow(随机图像重组(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

    1 回复  |  直到 7 年前
        1
  •  2
  •   McLawrence    7 年前

    代码有两个问题:

    首先,二维卷积 pytorch defined 仅适用于4D张量。 这在神经网络中使用很方便。第一个维度是批处理大小,而第二个维度是通道(例如,rgb图像有三个通道)。所以你必须重塑你的张量

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

    这个 FloatTensor 在这里很重要,因为卷积在 LongTensor 如果您的 numpy 数组仅包括 int S.

    其次,您创建了一个包含三个输入通道的卷积,而您的图像只有一个通道(灰度)。所以你必须调整卷积为:

    conv2 = torch.nn.Conv2d(1, 18, kernel_size=3, stride=1, padding=1)