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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于PyTorch框架实现的UNet图像分割代码示例: ```python import torch import torch.nn as nn import torch.nn.functional as F class DoubleConv(nn.Module): """Double convolution layer with batch normalization and ReLU activation""" def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True) ) def forward(self, x): return self.conv(x) class UNet(nn.Module): """UNet architecture for image segmentation""" def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]): super(UNet, self).__init__() self.downs = nn.ModuleList() self.ups = nn.ModuleList() self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # Encoder for feature in features: self.downs.append(DoubleConv(in_channels, feature)) in_channels = feature # Decoder for feature in reversed(features): self.ups.append(nn.ConvTranspose2d(feature*2, feature, kernel_size=2, stride=2)) self.ups.append(DoubleConv(feature*2, feature)) self.bottleneck = DoubleConv(features[-1], features[-1]*2) self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1) def forward(self, x): skip_connections = [] # Encoder for down in self.downs: x = down(x) skip_connections.append(x) x = self.pool(x) # Bottleneck x = self.bottleneck(x) # Decoder skip_connections = skip_connections[::-1] for idx in range(0, len(self.ups), 2): x = self.ups[idx](x) skip_connection = skip_connections[idx//2] if x.shape != skip_connection.shape: x = F.interpolate(x, size=skip_connection.shape[2:], mode='bilinear', align_corners=True) x = torch.cat((skip_connection, x), dim=1) x = self.ups[idx+1](x) # Final convolution x = self.final_conv(x) return x ``` 这个代码实现了一个UNet模型,包括Encoder和Decoder部分,以及一个bottleneck层和一个最终的卷积层。UNet模型的核心思想是在Encoder部分通过不断下采样(使用MaxPooling)来提取图像的低级特征,然后在Decoder部分通过上采样(使用ConvTranspose2d)和跳过连接(skip connections)来逐渐恢复图像的分辨率并提取高级特征,最终输出图像的分割结果。在这个实现中,我们使用了双卷积层(DoubleConv)作为UNet的基本构建块,每个双卷积层都包含两个卷积层、批量归一化和ReLU激活函数。UNet的输入是一个3通道的图像,输出是一个1通道的分割结果。可以根据具体的应用场景,调整输入和输出的通道数,以及Encoder和Decoder的层数和特征数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值