边缘检测系列3:【HED】 Holistically-Nested 边缘检测

article/2025/10/20 9:25:08

引入

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

  • 这次就介绍一篇比较经典的论文 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,导致复现的时候并不是很顺利。

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


http://chatgpt.dhexx.cn/article/1EiQd4ad.shtml

相关文章

【论文阅读】(边缘检测相关)HED:Holistically-Nested Edge Detection

论文地址:https://arxiv.org/pdf/1504.06375.pdf Holistically:整体 Nested:嵌套的 参考博客:深度学习论文笔记之(一)HED边缘检测_大青上的博客-CSDN博客_深度学习边缘检测 边缘检测之HED_年轻即出发&#…

深度学习hed边缘检测模型之裂缝检测

裂缝检测原本采用分割模型较多,目前我测试了采用hed的裂缝检测;代码采用这个版本的代码是最简洁易懂的,https://github.com/senliuy/Keras_HED_with_model 环境:win10 keras2.2.4 hed.py from keras.layers import Conv2D, …

hed-训练自己的数据集

1、准备自己训练的原图和边缘图,边缘图制作参考https://blog.csdn.net/weixin_38517705/article/details/84670150 2、将制作好的数据集放在.../rcf-master/data下,我是分为两个文件夹,一个存放原图(hed)、一个存放边…

HED边缘检测

主要是“Holistically-Nested Edge Detection ”这一篇文章 code download:https://github.com/s9xie/hed 这篇边缘检测主要是基于caffe框架下的,所以要实现的时候要在自己电脑上编译caffe,caffe安装编译可以看本人的博客:http:…

【边缘检测】HED论文笔记

论文全称:Holistically-Nested Edge Detection 亮点 1、基于整个图像的训练和预测 2、多尺度和多水平的特征学习 3、基于FCN和VGG 改进 4、通过多个side output输出不同scale的边缘,然后通过一个训练的权重融合函数得到最终的边缘输出。可以solve e…

HED测试单张图片示例

论文全名:[2015](HED_FCN)Holistically-Nested Edge Detection.pdf 代码下载地址:https://github.com/s9xie/hed 附上一篇个人认为写的比较好的论文笔记:http://blog.csdn.NET/u012905422/article/details/52782615 关于HED的训练在另一篇博客…

【深度学习HED边缘检测网络】

源码: 这个版本的代码是最简洁易懂的,https://github.com/senliuy/Keras_HED_with_model 数据集: 链接:https://pan.baidu.com/s/13qStI9DP1mbt9JallQFpPg 提取码:wbfi HED(Holistically-Nested Edge Detection) …

深度学习边缘检测 HED 训练自己的数据

深度学习边缘检测 HED 训练自己的数据 数据集制作 使用labelme标注,选择lineStrip(线条束)标注 生成json文件。 之后使用批量处理脚本将json文件转为边缘数据集。具体过程如下: 首先将所有的json文件放入一个文件夹内&#xff0c…

《HED:Holistically-Nested Edge Detection》原文翻译

注:本人水平有限,如有错误,恳请指正,谢谢 源代码和预训练模型获取地址: https://github.com/s9xie/hed 论文地址:https://arxiv.org/abs/1504.06375 Holistically-Nested Edge Detection 摘要 本文研究了…

边缘检测-HED-RCF

(HED)Holistically-Nested Edge Detection 解决问题 ICCV2015的文章。主要解决两个问题: (1)基于整个图像的训练和预测; (2)多尺度和多水平(多层次)的特征学习。该算法通过深度学习模型,完成了…

论文笔记 HED:Holistically-Nested Edge Detection

同组小伙伴推荐的文章,一篇看似做边缘检测,实际做出了语义分割的文章,ICCV2015的文章。主要解决两个问题:(1)基于整个图像的训练和预测;(2)多尺度和多水平的特征学习。该…

HED边缘检测:Holistically-nested Edge Detection 解读

Holistically-nested Edge Detection (以下简称HED) HED通过深度学习网络实现边缘检测,网络主要有以下两个特点 Holistically:指端到端(end-to-end 或者image-to-image)的学习方式,也就是说&a…

HED 和 RCF 图像边缘检测

HED 和 RCF 图像边缘检测 引言 虽然传统边缘检测算法在不断发展的过程中也取得了很大的进步,但仍然无法做到精细的边缘检测处理。随着近年来深度学习的快速发展,计算机视觉领域因此获益颇丰,当下最先进的计算机视觉应用几乎都离不开深度学习…

hed

一、编译caffe cd进入hed-master文件夹目里下 (1) cp Makefile.config.example Makefile.config (2) make all 出现错误a 解决: 打开Makefile.config文件 将 INCLUDE_DIRS : $(PYTHON_INCLUDE) /usr/local/incl…

边缘检测之HED

出自论文,Holistically-Nested Edge Detection ,ICCV2015,Marr奖提名,非常值得看的一篇。 边缘检测的工作分为以下3个研究方向: (1)传统的检测算子:Sobel ,Canny (2)基于信息理论设计的手工特征:Statisti…

HED神经网

本篇论文提出了一种新的网络结构进行边缘检测,论文这种网络结构称为Holistically-nested network。HED能够实现图像到图像的训练,输入一个图像,输出这个图像的边缘检测图。 1.现有的Multi-Scale和Multi-level学习的网络结构 2. (e)图是论文提…

身体证检测与识别(二)——HED边缘检测与矫正

前言 1.关于边缘检测,我这里用了HED这个边缘检测网络,HED创作于2015年,骨干网络是state-of-the-art的VGG-16,并且使用迁移学习初始化了网络权重。关于HED的算法原理与训练模型代码可以转到github。 2.OpenCV也有好几边缘检测算法可用&#x…

mysql otter 数据同步_MySQL数据同步之otter

一、otter介绍 基于日志数据,用于MySQL或者ORACLE之间准实时同步数据。 用途: mysql/oracle互相同步 中间表/行记录同步 二、原理及架构图 otter整体模块 manager (提供web页面进行同步管理) arbitrate (分布式调度,可跨IDC机房) node (同步过…

Otter简介

原文地址:http://m635674608.iteye.com/blog/2314908 Otter它是一个数据同步解决方案,可以解决本地跨网络跨机房跨地域的数据同步问题,并且拥有可观的效率,web管理工具等特点,而且背景也很优秀,据说阿里B2B内部的本地/异地机房的同步需求基本全上了 otte…

Canal和Otter

问题一: 跨公网部署Otter 参考架构图 解析 ​ a. 数据涉及网络传输,S/E/T/L几个阶段会分散在2个或者更多Node节点上,多个Node之间通过zookeeper进行协同工作 (一般是Select和Extract在一个机房的Node,Transform/Load落在另一个机房的Node&a…