当前位置: 首页 > 后端技术 > Python

语义分割网络U-net介绍

时间:2023-03-26 15:43:27 Python

U-net介绍今天介绍一个经典的语义分割网络U-net,它于2015年提出,最初应用于医学图像分割任务。由于其良好的效果,被广泛应用于各种分割任务中。到目前为止,已经衍生出很多基于U-net的分割模型。U-net是典型的Encoder-Decoder结构,编码器进行特征提取,解码器进行上采样。由于数据的限制,U-net在训练阶段使用了大量的数据增强操作,最终取得了不错的效果。U-net网络结构U-net的网络结构如下。左边部分是encoder部分,对输入进行下采样,下采样通过maxpooling实现;右边是decoder部分,对encoder的输出进行上采样恢复分辨率,上采样是通过Upsample实现的;中间部分是跳跃连接(Skip-connect),用于特征融合。由于整个网络看起来像一个“U”,所以称为U-net。网络中除了最后的输出层外,其他所有的卷积层都是3*3的卷积。U-net代码实现importtorchastimporttorch.nnasnnclassDoubleConv(nn.Module):def__init__(self,in_channels,out_channels):super(DoubleConv,self).__init__()self.dconv=nnnn.Sequential(.Conv2d(in_channels,?out_channels,?3,?1,?1),????????????nn.BatchNorm2d(out_channels),#inplace设为True可以节省显存/内存????????????nn.ReLU(inplace=True),????????????????????????nn.Conv2d(out_channels,?out_channels,?3,1,1),nn.BatchNorm2d(out_channels),nn.ReLU(inplace=True))defforward(self,img):returnself.dconv(img)#下采样类Down(nn.Modulef):Self,in_Channels,out_Channels):super(double,self).__init__()seld.down=nn.sequential(nn.maxpool2d(2,2),doubleconv(in_channels,out_channels)),:self.down(img)#上采样类Up(nn.Module):def__init__(self,in_channels,out_channels,bilinear=True):super(Up,self).__init__()#ConvTranspose2D有可学习的参数,在训练过程中会不断调整会增加模型的复杂度,可能造成过拟合#Upsample没有可学习的参数#Conv2d和MaxPooling2d的区别是一样的ifbilinear:self.up=nn.Upsample(scale_factor=2,mode='bilinear',align_corners=True)else:self.up=nn.ConvTranspose2d(in_channels//2,in_channels//2,kernel_size=2,stride=2)self.conv=DoubleConv(in_channels,out_channels,fx)x1(:x1=self.up(x1)#填充确保x1和x2具有相同的大小dx=x2.shape[3]-x1.shape[3]dy=x2.shape[2]-x1.shape[2]x1=nn.functional.pad(x1,[dx//2,dx-dx//2,dy//2,dy-dy//2])#通道合并x=t.cat([x1,x2],dim=1)returnself.conv(x)#mainnetworkclassCrackUnet(nn.Module):def__init__(self,channels,classes,bilinear=True):super(CrackUnet,self).__init__()self.channels=channelsself.classes=classesself.bilinear=bilinear#self.inconv=DoubleConv(self.channels,64)#4个下采层self.down1=Down(64,128)self.down2=Down(128,256)self.down3=Down(256,512)self.down4=Down(512,512)#4个上采样层,采用双线采样self.up1=Up(1024,256,bilinear)self.up2=Up(512,128,bilinear)self.up3=Up(256,64,双线性)(Up(256,64,双线性)(Up.128,64,双线性)self.outconv=nn.Conv2d(64,channels,1)defforward(self,img):img=self.inconv(img)down1=self.down1(img)down2=self.down2(down1)down3=self.down3(down2)down4=self.down4(down3)x=self.up1(down4,down3)deldown4deldown3x=self.up2(x,down2)del3xdel3self.x,down1)deldown1x=self.up5(x,img)delimgreturnself.outconv(x)总结u-net结构结构简单稳定小的时候,推荐使用。