U2Net——U-Net套U-Net——套娃式图像分割算法
创始人
2024-02-24 04:08:43

U2Net

    • 1 相关参考
    • 2 U2−NetU^2-NetU2−Net 网络结构
    • 3 网络代码和测试

1 相关参考

论文名称: U2-Net: Goging Deeper with Nested U-Structure for Salient Object Detetion
论文地址: https://arxiv.org/abs/2005.09007
官方源码: https://github.com/xuebinqin/U-2-Net
参考代码: Pytorch UNet
参考博客: https://blog.csdn.net/qq_37541097/article/details/126255483
参考视频: bilibili 我为霹导举大旗

建议大家可以先看霹导的原理讲解视频和代码讲解视频,代码写的真的太优雅了,以下内容作为自己对重点的记录和一些代码中的修改!

2 U2−NetU^2-NetU2−Net 网络结构

整体结构:
在这里插入图片描述

保留了原始的U-Net网络结构,只是将每一个Block的内部结构做了很大的调整,换成了一个U-Net,同时针对整个结构的输出做出调整,在训练时,给六个输出进行loss计算,在测试时只得到一个输出。

Block结构RSU:
在这里插入图片描述

这里Block,除了输入和输出的通道会发生变化,在中间层进行卷积时,使用的通道数都是Mid_channels,同时在最下层的卷积中,使用的是膨胀卷积。 这里的L=7,指的是RSU-7,是En_1和Dn_1的内部结构,在前四层中,都是使用的是RSU结构;

在后面的两层中,使用的是RSU-4F,其中的卷积层使用的是膨胀卷积,避免因为深度太深,导致图像尺寸太小,丢失特征,RSU-4F结构如下:
RSU-4F:
在这里插入图片描述

这里向下使用了两层的膨胀卷积,进行特征恢复,避免因为网络深度太深,导致特征丢失的问题!

损失函数:
网络在训练的时候,是对六个输出分别和GT进行BCE(二值交叉熵)计算,然后对损失求和进行反向传播,公式如下:
L=∑m=1Mwside (m)lside (m)+wfuse lfuse L=\sum_{m=1}^{M} w_{\text {side }}^{(m)} l_{\text {side }}^{(m)}+w_{\text {fuse }} l_{\text {fuse }} L=m=1∑M​wside (m)​lside (m)​+wfuse ​lfuse ​

在本网络中,前面一部分是六个输出和GT的损失,第二部分是最后的融合图像和GT的损失,代码如下:

import torch
import torch.nn as nn
from torch.nn import functional as F
class U2criterion(nn.Module):def __init__(self):super(U2criterion, self).__init__()def forward(self, inputs, target):losses = [F.binary_cross_entropy_with_logits(inputs[i], target) for i in range(len(inputs))]total_loss = sum(losses)return total_loss

3 网络代码和测试

from typing import Union, List
import torch
import torch.nn as nn
import torch.nn.functional as Fclass ConvBNReLU(nn.Module):def __init__(self, in_ch, out_ch, kernel_size=3, dilation=1):super().__init__()padding = kernel_size // 2 if dilation == 1 else dilation  # 保持图像大小不变self.conv = nn.Sequential(nn.Conv2d(in_ch, out_ch, kernel_size=kernel_size, padding=padding, dilation=dilation, bias=False),  # 因为后面有BN,bias不起作用nn.BatchNorm2d(out_ch),nn.ReLU(inplace=True) )def forward(self, x):return self.conv(x)class DownConvBNReLu(ConvBNReLU):def __init__(self, in_ch, out_ch, kernel_size=3, dilation=1, flag=True):super().__init__(in_ch, out_ch, kernel_size, dilation)self.down_flag = flagdef forward(self, x):if self.down_flag:x = F.max_pool2d(x, kernel_size=2, stride=2, ceil_mode=True)return self.conv(x)class UpConvBNReLU(ConvBNReLU):def __init__(self, in_ch, out_ch, kernel_size=3, dilation=1, flag=True):super().__init__(in_ch, out_ch, kernel_size, dilation)self.up_flag = flagdef forward(self, x1, x2): # x1为下面传入的, x2为左边传入的if self.up_flag:x1 = F.interpolate(x1, size=x2.shape[2:], mode="bilinear", align_corners=False)x = torch.cat([x1, x2], dim=1)return self.conv(x)class RSU(nn.Module):def __init__(self, height, in_ch, mid_ch, out_ch):super().__init__()assert height >= 2self.conv_in = ConvBNReLU(in_ch, out_ch)  # 这个是不算在height上的encode_list = [DownConvBNReLu(out_ch, mid_ch, flag=False)]decode_list = [UpConvBNReLU(mid_ch*2, mid_ch, flag=False)]for i in range(height-2): # 含有上下采样的模块encode_list.append(DownConvBNReLu(mid_ch, mid_ch))decode_list.append(UpConvBNReLU(mid_ch*2, mid_ch if i < height-3 else out_ch)) # 这里最后的decode的输出是out_chencode_list.append(ConvBNReLU(mid_ch, mid_ch, dilation=2))self.encode_modules = nn.ModuleList(encode_list)self.decode_modules = nn.ModuleList(decode_list)def forward(self, x):x_in = self.conv_in(x)x = x_inencode_outputs = []for m in self.encode_modules:x = m(x)encode_outputs.append(x)x = encode_outputs.pop() # 这是移除list最后的一个数据,并且将该数据赋值给x,这里的x是含有空洞卷积的输出for m  in self.decode_modules:x2 = encode_outputs.pop() # 这里是倒数第二深的输出,x表示下面的,x2表示左边的x = m(x, x2)  # 将下面的,和左边的一起传入到上卷积中return x + x_in  # 这里是最上面一层进行相加class RSU4F(nn.Module):def __init__(self, in_ch, mid_ch, out_ch):super().__init__()self.conv_in = ConvBNReLU(in_ch, out_ch)self.encode_modules = nn.ModuleList([ConvBNReLU(out_ch, mid_ch),ConvBNReLU(mid_ch, mid_ch, dilation=2),ConvBNReLU(mid_ch, mid_ch, dilation=4),ConvBNReLU(mid_ch, mid_ch, dilation=8)])self.decode_modules = nn.ModuleList([ConvBNReLU(mid_ch*2, mid_ch, dilation=4),ConvBNReLU(mid_ch*2, mid_ch, dilation=2),ConvBNReLU(mid_ch*2, out_ch)])def forward(self, x):x_in = self.conv_in(x)x = x_inencode_outputs = []for m in self.encode_modules:x = m(x)encode_outputs.append(x)x = encode_outputs.pop()for m in self.decode_modules:x2 = encode_outputs.pop()x = m(torch.cat([x, x2], dim=1))return x+x_inclass U2Net(nn.Module):def __init__(self, cfg, out_ch=1):super().__init__()assert "encode" in cfgassert "decode" in cfgself.encode_num = len(cfg["encode"])encode_list = []side_list = []for c in cfg["encode"]:# [height, in_ch, mid_ch, out_ch, RSU4F, side]assert len(c) == 6encode_list.append(RSU(*c[:4]) if c[4] is False else RSU4F(*c[1:4]))  # 这里的*是将列表解开为单独的数值,这样才能传入到函数中if c[5] is True:side_list.append(nn.Conv2d(c[3], out_ch, kernel_size=3, padding=1))self.encode_modules = nn.ModuleList(encode_list)decode_list = []for c in cfg["decode"]:assert len(c) == 6decode_list.append(RSU(*c[:4]) if  c[4] is False else RSU4F(*c[1:4]))if c[5] is True:side_list.append(nn.Conv2d(c[3], out_ch, kernel_size=3, padding=1))self.decode_modules = nn.ModuleList(decode_list)self.side_modules = nn.ModuleList(side_list)self.out_conv = nn.Conv2d(self.encode_num*out_ch, out_ch, kernel_size=1)  # 这里是针对cat后的结果进行卷积,得到最后的out_ch=1def forward(self, x):_, _, h, w = x.shapeencode_outputs = []for i, m in enumerate(self.encode_modules):x = m(x)encode_outputs.append(x)if i != self.encode_num - 1:  # 除了最后一个encode_block不用下采样,其余每一个block都需要下采样x = F.max_pool2d(x, kernel_size=2, stride=2, ceil_mode=True)x = encode_outputs.pop()decode_outputs = [x]for m in self.decode_modules:x2 = encode_outputs.pop()x = F.interpolate(x, size=x2.shape[2:], mode="bilinear", align_corners=False)x = m(torch.cat([x, x2], dim=1))decode_outputs.insert(0, x) #这里是保证了从上到下的decode层的输出,在列表中的遍历是从0到5side_outputs = []for m in self.side_modules:x = decode_outputs.pop()x = F.interpolate(m(x), size=[h,w], mode="bilinear", align_corners=False)side_outputs.insert(0, x)x = self.out_conv(torch.cat(side_outputs, dim=1))if self.training:   # 在训练的时候,需要将6个输出都拿出来进行loss计算,return [x] + side_outputselse:  # 非训练时,直接sigmoid后的数据return torch.sigmoid(x)# return torch.sigmoid(x)def u2net_full(in_ch=3, out_ch=1):cfg = {# height, in_ch, mid_ch, out_ch, RSU4F, side"encode": [[7, in_ch, 32, 64, False, False],      # En1[6, 64, 32, 128, False, False],    # En2[5, 128, 64, 256, False, False],   # En3[4, 256, 128, 512, False, False],  # En4[4, 512, 256, 512, True, False],   # En5[4, 512, 256, 512, True, True]],   # En6# height, in_ch, mid_ch, out_ch, RSU4F, side"decode": [[4, 1024, 256, 512, True, True],   # De5[4, 1024, 128, 256, False, True],  # De4[5, 512, 64, 128, False, True],    # De3[6, 256, 32, 64, False, True],     # De2[7, 128, 16, 64, False, True]]     # De1}return U2Net(cfg, out_ch)def u2net_lite(in_ch=3, out_ch=1):cfg = {# height, in_ch, mid_ch, out_ch, RSU4F, side"encode": [[7, in_ch, 16, 64, False, False],  # En1[6, 64, 16, 64, False, False],  # En2[5, 64, 16, 64, False, False],  # En3[4, 64, 16, 64, False, False],  # En4[4, 64, 16, 64, True, False],  # En5[4, 64, 16, 64, True, True]],  # En6# height, in_ch, mid_ch, out_ch, RSU4F, side"decode": [[4, 128, 16, 64, True, True],  # De5[4, 128, 16, 64, False, True],  # De4[5, 128, 16, 64, False, True],  # De3[6, 128, 16, 64, False, True],  # De2[7, 128, 16, 64, False, True]]  # De1}return U2Net(cfg, out_ch)# net = u2net_full(1,1)
# x = torch.randn(16,1,256,256)
# net.eval()
# print(net(x))
  1. 这里u2net_full指的是完整的U2Net,u2net_lite,指的是轻量级的U2Net,这两个的唯一区别是,模块中的通道数不同;
  2. 指定网络的时候,需要指定网络输入通道和输出通道,这里的修改是为了自己使用网络的便利,原始网络中,默认输入通道是3
  3. 轻量级模型的参数是完整性模型参数的1/40

贴一个网络参数计算代码:

def count_parameters(model):  # 传入的是模型实例对象params = [p.numel() for p in model.parameters() if p.requires_grad]
#     for item in params:
#         print(f'{item:>16}')   # 参数大于16的展示print(f'________\n{sum(params):>16}')  # 大于16的进行统计,可以自行修改

网络测试:
在这里插入图片描述
在这里插入图片描述
再说一下,霹导写的代码真的很优雅,可以去看霹导的代码讲解和网络结构讲解!!

相关内容

热门资讯

埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...