Pytorch 实现sobel算子的卷积操作详解

yipeiwu_com6年前Python基础

卷积在pytorch中有两种实现,一种是torch.nn.Conv2d(),一种是torch.nn.functional.conv2d(),这两种方式本质都是执行卷积操作,对输入的要求也是一样的,首先需要输入的是一个torch.autograd.Variable()的类型,大小是(batch,channel, H,W),其中batch表示输入的一批数据的数目,channel表示输入的通道数。

一般一张彩色的图片是3,灰度图片是1,而卷积网络过程中的通道数比较大,会出现几十到几百的通道数。H和W表示输入图片的高度和宽度,比如一个batch是32张图片,每张图片是3通道,高和宽分别是50和100,那么输入的大小就是(32,3,50,100)。

如下代码是卷积执行soble边缘检测算子的实现:

import torch
import numpy as np
from torch import nn
from PIL import Image
from torch.autograd import Variable
import torch.nn.functional as F
 
 
def nn_conv2d(im):
  # 用nn.Conv2d定义卷积操作
  conv_op = nn.Conv2d(1, 1, 3, bias=False)
  # 定义sobel算子参数
  sobel_kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype='float32')
  # 将sobel算子转换为适配卷积操作的卷积核
  sobel_kernel = sobel_kernel.reshape((1, 1, 3, 3))
  # 给卷积操作的卷积核赋值
  conv_op.weight.data = torch.from_numpy(sobel_kernel)
  # 对图像进行卷积操作
  edge_detect = conv_op(Variable(im))
  # 将输出转换为图片格式
  edge_detect = edge_detect.squeeze().detach().numpy()
  return edge_detect
 
def functional_conv2d(im):
  sobel_kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype='float32') #
  sobel_kernel = sobel_kernel.reshape((1, 1, 3, 3))
  weight = Variable(torch.from_numpy(sobel_kernel))
  edge_detect = F.conv2d(Variable(im), weight)
  edge_detect = edge_detect.squeeze().detach().numpy()
  return edge_detect
 
def main():
  # 读入一张图片,并转换为灰度图
  im = Image.open('./cat.jpg').convert('L')
  # 将图片数据转换为矩阵
  im = np.array(im, dtype='float32')
  # 将图片矩阵转换为pytorch tensor,并适配卷积输入的要求
  im = torch.from_numpy(im.reshape((1, 1, im.shape[0], im.shape[1])))
  # 边缘检测操作
  # edge_detect = nn_conv2d(im)
  edge_detect = functional_conv2d(im)
  # 将array数据转换为image
  im = Image.fromarray(edge_detect)
  # image数据转换为灰度模式
  im = im.convert('L')
  # 保存图片
  im.save('edge.jpg', quality=95)
 
if __name__ == "__main__":
  main()

原图片:cat.jpg

结果图片:edge.jpg

以上这篇Pytorch 实现sobel算子的卷积操作详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Windows下搭建python开发环境详细步骤

Windows下搭建python开发环境详细步骤

本文为大家分享了Windows下搭建python开发环境详细步骤,供大家参考,具体内容如下 1.搭建Java环境 (1)直接从官网下载相应版本的JDK或者JRE并点击安装就可以 (2)J...

Python正则表达式匹配日期与时间的方法

下面给大家介绍下Python正则表达式匹配日期与时间 #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Ran...

利用Python-iGraph如何绘制贴吧/微博的好友关系图详解

利用Python-iGraph如何绘制贴吧/微博的好友关系图详解

前言 最近工作中遇到了一些需求,想通过图形化的方式显示社交网络特定用户的好友关系,上网找了一下这方面的图形库有networkx、graphviz等,找了好久我选择了iGraph这个图形库...

Python实现计算最小编辑距离

Python实现计算最小编辑距离

最小编辑距离或莱文斯坦距离(Levenshtein),指由字符串A转化为字符串B的最小编辑次数。允许的编辑操作有:删除,插入,替换。具体内容可参见:维基百科—莱文斯坦距离。一般代码实现的...

对python tkinter窗口弹出置顶的方法详解

如果想要python 的tkinter窗口置顶,加上下面两句即可实现root窗口的置顶显示,可以用于某些程序的消息提示,能够弹出到桌面显示 root = Tk() root.wm_a...