全卷积网络(FCN)

一、定义

1、语义分割是对图像中的每个像素分类。 全卷积网络(fully convolutional network,FCN)采用卷积神经网络实现了从图像像素到像素类别的变换 

2、全卷积网络将中间层特征图的高和宽变换回输入图像的尺寸:通过转置卷积(transposed convolution)实现的

3、输出的类别预测与输入图像在像素级别上具有一一对应关系:通道维的输出即该位置对应像素的类别预测

4、使用在ImageNet数据集上预训练的ResNet-18模型来提取图像特征,并将该网络记为pretrained_net,但将全局平均汇聚层和全连接层替换为转置卷积层

5、使用Xavier初始化1×1卷积层

二、代码

1、构造模型

pretrained_net = torchvision.models.resnet18(pretrained=True)
#只要除最后两层之外的层
net = nn.Sequential(*list(pretrained_net.children())[:-2])
X = torch.rand(size=(1, 3, 320, 480))
num_classes = 21
#使用1×1卷积层将输出通道数转换为Pascal VOC2012数据集的类数(21类)
net.add_module('final_conv', nn.Conv2d(512, num_classes, kernel_size=1))
#将特征图的高度和宽度增加32倍,从而将其变回输入图像的高和宽;步幅为𝑠,填充为𝑠/2(假设𝑠/2是整数)且卷积核的高和宽为2𝑠,转置卷积核会将输入的高和宽分别放大𝑠倍
net.add_module('transpose_conv', nn.ConvTranspose2d(num_classes, num_classes,
                                    kernel_size=64, padding=16, stride=32))

2、初始化转置卷积层

        使用双线性插值生成权重的主要原因是为了在上采样(upsampling)操作中保持图像的平滑过渡,避免像素块效应,并且能够更好地保留图像的细节。

        比如会是这种样子

       

#双线性插值,函数返回生成的双线性插值卷积核权重 weight,可以用于上采样操作
def bilinear_kernel(in_channels, out_channels, kernel_size):
    # 计算插值中心的位置因子
    factor = (kernel_size + 1) // 2
    # 判断 kernel_size 是奇数还是偶数,确定中心位置
    if kernel_size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    # og 包含两个部分,一个是列向量,一个是行向量,用于生成 2D 网格的坐标
    og = (torch.arange(kernel_size).reshape(-1, 1),
          torch.arange(kernel_size).reshape(1, -1))
    # 计算双线性插值卷积核
    filt = (1 - torch.abs(og[0] - center) / factor) * \
           (1 - torch.abs(og[1] - center) / factor)
    # 初始化权重张量为全零,形状为 (in_channels, out_channels, kernel_size, kernel_size)
    weight = torch.zeros((in_channels, out_channels,
                          kernel_size, kernel_size))
    #初始化权重张量 weight
    weight[range(in_channels), range(out_channels), :, :] = filt
    return weight

#构造一个将输入的高和宽放大2倍的转置卷积层,并将其卷积核用bilinear_kernel函数初始化
conv_trans = nn.ConvTranspose2d(3, 3, kernel_size=4, padding=1, stride=2,
                                bias=False)
conv_trans.weight.data.copy_(bilinear_kernel(3, 3, 4));

#读取图像X,将上采样的结果记作Y
img = torchvision.transforms.ToTensor()(d2l.Image.open('../img/catdog.jpg'))
X = img.unsqueeze(0)
Y = conv_trans(X)
#调整通道维的位置(因为将预测标号存在通道维了)
out_img = Y[0].permute(1, 2, 0).detach()

3、读取数据集

batch_size, crop_size = 32, (320, 480)
train_iter, test_iter = d2l.load_data_voc(batch_size, crop_size)

4、训练

def loss(inputs, targets):
    return F.cross_entropy(inputs, targets, reduction='none').mean(1).mean(1)

num_epochs, lr, wd, devices = 5, 0.001, 1e-3, d2l.try_all_gpus()
trainer = torch.optim.SGD(net.parameters(), lr=lr, weight_decay=wd)
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)

5、预测

def predict(img):
    X = test_iter.dataset.normalize_image(img).unsqueeze(0)
    pred = net(X.to(devices[0])).argmax(dim=1)
    return pred.reshape(pred.shape[1], pred.shape[2])

#将预测类别映射回它们在数据集中的标注颜色
def label2image(pred):
    colormap = torch.tensor(d2l.VOC_COLORMAP, device=devices[0])
    X = pred.long()
    return colormap[X, :]

voc_dir = d2l.download_extract('voc2012', 'VOCdevkit/VOC2012')
test_images, test_labels = d2l.read_voc_images(voc_dir, False)
n, imgs = 4, []
for i in range(n):
    crop_rect = (0, 0, 320, 480)
    X = torchvision.transforms.functional.crop(test_images[i], *crop_rect)
    pred = label2image(predict(X))
    imgs += [X.permute(1,2,0), pred.cpu(),
             torchvision.transforms.functional.crop(
                 test_labels[i], *crop_rect).permute(1,2,0)]
d2l.show_images(imgs[::3] + imgs[1::3] + imgs[2::3], 3, n, scale=2);

三、总结

1、全卷积网络先使用卷积神经网络抽取图像特征,然后通过1×1卷积层将通道数变换为类别个数,最后通过转置卷积层将特征图的高和宽变换为输入图像的尺寸。

2、在全卷积网络中,我们可以将转置卷积层初始化为双线性插值的上采样。

  • 16
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值