引入

  • 除了传统的边缘检测算法,当然也有基于深度学习的边缘检测模型

  • 这次就介绍一篇比较经典的论文 Holistically-Nested Edge Detection

  • 其中的 Holistically-Nested 表示此模型是一个多尺度的端到端边缘检测模型

相关资料

  • 论文:Holistically-Nested Edge Detection

  • 官方代码(Caffe):s9xie/hed

  • 非官方实现(Pytorch): xwjabc/hed

效果演示

  • 论文中的效果对比图:

模型结构

  • HED 模型包含五个层级的特征提取架构,每个层级中:

    • 使用 VGG Block 提取层级特征图

    • 使用层级特征图计算层级输出

    • 层级输出上采样

  • 最后融合五个层级输出作为模型的最终输出:

    • 通道维度拼接五个层级的输出

    • 1x1 卷积对层级输出进行融合

  • 模型总体架构图如下:

代码实现

导入必要的模块

import cv2
import numpy as npfrom PIL import Imageimport paddle
import paddle.nn as nn

构建 HED Block

  • 由一个 VGG Block 和一个 score Conv2D 层组成

  • 使用 VGG Block 提取图像特征信息

  • 使用一个额外的 Conv2D 计算边缘得分

class HEDBlock(nn.Layer):def __init__(self, in_channels, out_channels, paddings, num_convs, with_pool=True):super().__init__()# VGG Blockif with_pool:pool = nn.MaxPool2D(kernel_size=2, stride=2)self.add_sublayer('pool', pool)conv1 = nn.Conv2D(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=paddings[0])relu = nn.ReLU()self.add_sublayer('conv1', conv1)self.add_sublayer('relu1', relu)for _ in range(num_convs-1):conv = nn.Conv2D(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=paddings[_+1])self.add_sublayer(f'conv{_+2}', conv)self.add_sublayer(f'relu{_+2}', relu)self.layer_names = [name for name in self._sub_layers.keys()]# Socre Layerself.score = nn.Conv2D(in_channels=out_channels, out_channels=1, kernel_size=1, stride=1, padding=0)def forward(self, input):for name in self.layer_names:input = self._sub_layers[name](input)return input, self.score(input)

构建 HED Caffe 模型

  • 本模型基于官方开源的 Caffe 预训练模型实现,预测结果非常接近官方实现。

  • 此代码会稍显冗余,主要是为了对齐官方提供的预训练模型,具体的原因请参考如下说明:

    • 由于 Paddle 的 Bilinear Upsampling 与 Caffe 的 Bilinear DeConvolution 并不完全等价,所以这里使用 Transpose Convolution with Bilinear 进行替代以对齐模型输出。

    • 因为官方开源的 Caffe 预训练模型中第一个 Conv 层的 padding 参数为 35,所以需要在前向计算时进行中心裁剪特征图以恢复其原始形状。

    • 裁切所需要的参数参考自 XWJABC 的复现代码,代码链接

class HED_Caffe(nn.Layer):def __init__(self,channels=[3, 64, 128, 256, 512, 512],nums_convs=[2, 2, 3, 3, 3],paddings=[[35, 1], [1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],crops=[34, 35, 36, 38, 42],with_pools=[False, True, True, True, True]):super().__init__()'''Caffe HED model re-implementation in Paddle.This model is based on the official Caffe pre-training model. The inference results of this model are very close to the official implementation in Caffe.Pytorch and Paddle's Bilinear Upsampling are not completely equivalent to Caffe's DeConvolution with Bilinear, so Transpose Convolution with Bilinear is used instead.In the official Caffe pre-training model, the padding parameter value of the first convolution layer is equal to 35, so the feature map needs to be cropped. The crop parameters refer to the code implementation by XWJABC. The code link: https://github.com/xwjabc/hed/blob/master/networks.py#L55.'''assert (len(channels) - 1) == len(nums_convs), '(len(channels) -1) != len(nums_convs).'self.crops = crops# HED Blocksfor index, num_convs in enumerate(nums_convs):block = HEDBlock(in_channels=channels[index], out_channels=channels[index+1], paddings=paddings[index], num_convs=num_convs, with_pool=with_pools[index])self.add_sublayer(f'block{index+1}', block)self.layer_names = [name for name in self._sub_layers.keys()]# Upsamplesfor index in range(2, len(nums_convs)+1):upsample = nn.Conv2DTranspose(in_channels=1, out_channels=1, kernel_size=2**index, stride=2**(index-1), bias_attr=False)upsample.weight.set_value(self.bilinear_kernel(1, 1, 2**index))upsample.weight.stop_gradient = Trueself.add_sublayer(f'upsample{index}', upsample)# Output Layersself.out = nn.Conv2D(in_channels=len(nums_convs), out_channels=1, kernel_size=1, stride=1, padding=0)self.sigmoid = nn.Sigmoid()def forward(self, input):h, w = input.shape[2:]scores = []for index, name in enumerate(self.layer_names):input, score = self._sub_layers[name](input)if index > 0:score = self._sub_layers[f'upsample{index+1}'](score)score = score[:, :, self.crops[index]: self.crops[index] + h, self.crops[index]: self.crops[index] + w]scores.append(score)output = self.out(paddle.concat(scores, 1))return self.sigmoid(output)@staticmethoddef bilinear_kernel(in_channels, out_channels, kernel_size):'''return a bilinear filter tensor'''factor = (kernel_size + 1) // 2if kernel_size % 2 == 1:center = factor - 1else:center = factor - 0.5og = np.ogrid[:kernel_size, :kernel_size]filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size), dtype='float32')weight[range(in_channels), range(out_channels), :, :] = filtreturn paddle.to_tensor(weight, dtype='float32')

构建 HED 模型

  • 下面就是一个比较精简的 HED 模型实现

  • 与此同时也意味着下面这个模型会与官方实现的模型有所差异,具体差异如下:

    • 3 x 3 卷积采用 padding == 1

    • 采用 Bilinear Upsampling 进行上采样

  • 同样可以加载预训练模型,不过精度可能会略有下降

# class HEDBlock(nn.Layer):
#     def __init__(self, in_channels, out_channels, num_convs, with_pool=True):
#         super().__init__()
#         # VGG Block
#         if with_pool:
#             pool = nn.MaxPool2D(kernel_size=2, stride=2)
#             self.add_sublayer('pool', pool)#         conv1 = nn.Conv2D(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)
#         relu = nn.ReLU()#         self.add_sublayer('conv1', conv1)
#         self.add_sublayer('relu1', relu)#         for _ in range(num_convs-1):
#             conv = nn.Conv2D(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)
#             self.add_sublayer(f'conv{_+2}', conv)
#             self.add_sublayer(f'relu{_+2}', relu)#         self.layer_names = [name for name in self._sub_layers.keys()]#         # Socre Layer
#         self.score = nn.Conv2D(
#             in_channels=out_channels, out_channels=1, kernel_size=1, stride=1, padding=0)#     def forward(self, input):
#         for name in self.layer_names:
#             input = self._sub_layers[name](input)
#         return input, self.score(input)# class HED(nn.Layer):
#     def __init__(self,
#                  channels=[3, 64, 128, 256, 512, 512],
#                  nums_convs=[2, 2, 3, 3, 3],
#                  with_pools=[False, True, True, True, True]):
#         super().__init__()
#         '''
#         HED model implementation in Paddle.#         Fix the padding parameter and use simple Bilinear Upsampling.
#         '''
#         assert (len(channels) - 1) == len(nums_convs), '(len(channels) -1) != len(nums_convs).'#         # HED Blocks
#         for index, num_convs in enumerate(nums_convs):
#             block = HEDBlock(in_channels=channels[index], out_channels=channels[index+1], num_convs=num_convs, with_pool=with_pools[index])
#             self.add_sublayer(f'block{index+1}', block)#         self.layer_names = [name for name in self._sub_layers.keys()]#         # Output Layers
#         self.out = nn.Conv2D(in_channels=len(nums_convs), out_channels=1, kernel_size=1, stride=1, padding=0)
#         self.sigmoid = nn.Sigmoid()#     def forward(self, input):
#         h, w = input.shape[2:]
#         scores = []
#         for index, name in enumerate(self.layer_names):
#             input, score = self._sub_layers[name](input)
#             if index > 0:
#                 score = nn.functional.upsample(score, size=[h, w], mode='bilinear')
#             scores.append(score)#         output = self.out(paddle.concat(scores, 1))
#         return self.sigmoid(output)

预训练模型

def hed_caffe(pretrained=True, **kwargs):model = HED_Caffe(**kwargs)if pretrained:pdparams = paddle.load('hed_pretrained_bsds.pdparams')model.set_dict(pdparams)return model

预处理操作

  • 类型转换

  • 归一化

  • 转置

  • 增加维度

  • 转换为 Paddle Tensor

def preprocess(img):img = img.astype('float32')img -= np.asarray([104.00698793, 116.66876762, 122.67891434], dtype='float32')img = img.transpose(2, 0, 1)img = img[None, ...]return paddle.to_tensor(img, dtype='float32')

后处理操作

  • 上下阈值限制

  • 删除通道维度

  • 反归一化

  • 类型转换

  • 转换为 Numpy NdArary

def postprocess(outputs):results = paddle.clip(outputs, 0, 1)results = paddle.squeeze(results, 1)results *= 255.0results = results.cast('uint8')return results.numpy()

模型推理

model = hed_caffe(pretrained=True)
img = cv2.imread('sample.png')
img_tensor = preprocess(img)
outputs = model(img_tensor)
results = postprocess(outputs)show_img = np.concatenate([cv2.cvtColor(img, cv2.COLOR_BGR2RGB), cv2.cvtColor(results[0], cv2.COLOR_GRAY2RGB)], 1)
Image.fromarray(show_img)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ST0UFcaX-1637974547860)(output_20_0.png)]

模型训练

  • 模型的训练代码仍在打磨,后续会继续更新的

总结

  • 这是一篇发表于 CVPR 2015 上的论文,距离现在也又很多年时间了,所以模型结构看起来算是比较简单的。

  • 不过由于当时官方实现采用的是 Caffe 框架,加上那个 35 的谜之 padding,导致复现的时候并不是很顺利。

  • 有关于边缘检测模型的训练,之后会有一个单独的项目来详细展开的,敬请期待(低情商:还没搞完)。

边缘检测系列3:【HED】 Holistically-Nested 边缘检测相关推荐

  1. 边缘检测系列5:【CED】添加了反向细化路径的 HED 模型

    引入 边缘检测系列第 5 弹,本次继续介绍经典的边缘检测模型 Crisp Edge Detection(CED)模型是前面介绍过的 HED 模型的另一种改进模型 CED 模型利用自上而下的反向细化路径 ...

  2. 边缘检测系列4:【RCF】基于更丰富的卷积特征的边缘检测

    引入 上一篇介绍了经典的 HED 边缘检测模型 这一次继续介绍另一篇边缘检测方向的经典论文:Richer Convolutional Features for Edge Detection 其中提出了 ...

  3. 图像处理——基于深度学习HED实现目标边缘检测

    前言 使用传统的图像来检测目标边缘,受到干扰的因素太多了,而已鲁棒性不高,同样的参数,在这个环境下可以,换个环境就根本检测不到物体的边缘,或者把不是边缘的也检测进去了.ICCV2015有人提出了整体嵌 ...

  4. Matlab与FPGA图像处理系列——基于FPGA的实时边缘检测系统设计,sobel边缘检测流水线实现

    注:下载链接的资源是图片存 ROM 后读取进行 Sobel 检测显示在 VGA上,可供参考. 摘要:本文设计了一种基于 FPGA 的实时边缘检测系统,使用OV5640 摄像头模块获取实时的视频图像数据 ...

  5. 自动驾驶感知-车道线系列(二)——Canny边缘检测

    Canny边缘检测 前言 一.Canny是什么? 二.算法详细步骤 1. 平滑处理 2. 梯度检测 3. 非极大值抑制 4. 滞后阈值处理 三.函数原型 四.应用实例 五.总结 前言 边缘检测是图像处 ...

  6. canny边缘检测算法_什么是Canny边缘检测算法

    canny边缘检测算法 Canny edge detector is a multi-step algorithm to detect the edges for any input image. I ...

  7. 用matlab进行边缘检测,利用MATLAB进行数字图像的边缘检测

    第 卷第 期的 年 月 辽 阳石 油化工 高等专科学校学报父 而 吐 伽 罗 浏阮 利用 进行数字 图像的边缘检测 岳海萍 沈 阳 市机械工业 学校 电专业教研室 , 辽宁 沈阳 以犯 摘 要 介绍 ...

  8. 基于matlab的数字图像边缘检测算法研究,基于MATLAB数字图像边缘检测算法的研究与对比分析...

    ·161· 居 舍 研究探讨 2017年10月(中) 1 绪论 图像边缘中通常包含着重要的边界信息,这些边界信息便于分析和研究图像.另外,边缘检测可以大大降低图像处 理的工作量,将提高图像分析的效率. ...

  9. matlab实现sobel边缘检测图像,基于Sobel算子图像边缘检测的MATLAB实现

    <基于Sobel算子图像边缘检测的MATLAB实现>由会员分享,可在线阅读,更多相关<基于Sobel算子图像边缘检测的MATLAB实现(3页珍藏版)>请在人人文库网上搜索. 1 ...

最新文章

  1. BZOJ4754 JSOI2016独特的树叶(哈希)
  2. java 连续运算_JS连续运算
  3. LibreOJ 6279 数列分块入门 3(分块+排序)
  4. IAR FOR ARM 各版本号,须要的大家能够收藏了
  5. boost::static_min_max_signed_type用法的测试程序
  6. .net core 一个避免跨站请求的中间件
  7. ES6减少魔法操作之Reflect
  8. mysql 组复制 不一致_使用MySQL组复制的限制和局限性
  9. SQL 语句还原SQL Server数据库
  10. Python 一键转 Java?“Google 翻译”你别闹
  11. 《海量数据库解决方案》之位图索引的结构和特征
  12. 手机远程服务器总说磁盘空间不足,查询远程服务器上磁盘空间的最佳方式
  13. c++ - 虚函数表
  14. My97DateTimePicker使用说明
  15. 【071】张大妈计算器-工资计算器及各地薪资报告
  16. excel转vcf 易语言免费版
  17. 网易云那些触动人心的经典热评
  18. 拜师——python基础入门—第3大节课—列表,排序,revered逆序,max,min,sum——day15
  19. Chrome插件安装的3种方法,解决拖放不能安装的情况,并提供插件下载
  20. 什么是纵向加密与横向隔离

热门文章

  1. 只有程序员才会玩的游戏
  2. 计算机高级系统设置无法设置,进入高级系统设置启动和故障恢复设置
  3. 瑞星预警:Vista出现首个重大安全漏洞
  4. 中国热固性粉末涂料行业现状调研及趋势分析报告
  5. 【唐山装修公司】了解这几点,不怕房屋漏水
  6. 创新杯计算机教学设计大赛,2015年全国中等职业学校数学课程“创新杯”教师信息化教学设计及说课大赛成功举办...
  7. 2022和23届港澳台联考学生注意啦!通过港澳台联考申请香港知名大学!
  8. 查看GPU显存 使用率
  9. 理论+实验:ELK日志分析系统
  10. Ubuntu更换apt源之arm版