pytorch入门 Convolution & Pooling

知识点
1、读取图像,灰度图像
2、显示图像
3、定义卷积层
4、nn.Conv2d参数
5、定义kernel
6、修改nn.Conv2d的weight
7、输出图像转numpy()
8、定义池化层
9、输出矩阵宽度计算公式

对于Convolution ,一般用torch.nn.Conv2d定义(torch.nn.functional.conv2d()用的比较少)

import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from PIL import Image
import matplotlib.pyplot as plt

知识点1
读取图像,这里PIL.Image.open()可以方便的读取图像 .convert(‘L’)是以灰度图读取
注意
np.array(im.dtype=‘float32’) 'float32’是必须的,因为后面要转化为tensor
知识点2
显示图像,因为要以图像的形式输出所以 im.astype(‘uint8’)

im = Image.open('./cat.png').convert('L')
im = np.array(im, dtype='float32')
plt.imshow(im.astype('uint8'), cmap='gray')
plt.show()

知识点3
nn.Conv2d对输入的要求为(batch.size, channels, height, width) 的Variable 所以要先把图像转化为4个维度的tensor
知识点4
nn.Conv2d(input_channels, output_channels, kernel_size, stride=1, padding=0)这些是主要参数
知识点5
sobel_kernel 用numpy定义,而且dtype=‘float32’ 同样是input_channels, output_channels, kernel_size
知识点6
nn.Conv2d 直接定义了weight 可以直接调用,很方便
知识点7
把输出的图像(tensor) 转化为numpy时 注意要squeeze()一下

im = torch.from_numpy(im.reshape((1, 1, im.shape[0], im.shape[1])))
conv1 = nn.Conv2d(1, 1, 3, bias=False)
sobel_kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype='float32')
sobel_kernel = sobel_kernel.reshape((1, 1, 3, 3))
conv1.weight.data = torch.from_numpy(sobel_kernel)
edge1 = conv1(Variable(im))
edge1 = edge1.data.squeeze().numpy()
plt.imshow(edge1, cmap='gray')
plt.show()

Pooling
知识点8
pool 一般用nn.MaxPool2d(2, 2)定义,直接实例化后,输入一个Variable的图像就可以了
torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

pool1 = nn.MaxPool2d(2, 2)
print('before max pool, image shape:{} x {}'.format(im.shape[2], im.shape[3]))
small_im1 = pool1(Variable(im))
small_im1 = small_im1.data.squeeze().numpy()
print('after max pool, image shape: {} x {}'.format(small_im1.shape[0], small_im1.shape[1]))
plt.imshow(small_im1, cmap='gray')
plt.show()

知识点9
卷积层与池化层 输出矩阵宽度公式 W_out = (W_in - k + 2p) / S + 1
w 为图像宽度 k 为 kernel p 为 padding S 为 stride

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值