0

0

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

P粉084495128

P粉084495128

发布时间:2025-07-18 10:09:50

|

603人浏览过

|

来源于php中文网

原创

本文介绍经典论文《Holistically-Nested Edge Detection》中的HED模型,这是多尺度端到端边缘检测模型。给出其Paddle实现,包括HEDBlock构建、HED_Caffe模型(对齐Caffe预训练模型)及精简HED模型,还涉及预训练模型加载、预处理、后处理操作及推理过程。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

边缘检测系列3:【hed】 holistically-nested 边缘检测 - php中文网

引入

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

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

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

相关资料

  • 论文:Holistically-Nested Edge Detection

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

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

效果演示

  • 论文中的效果对比图:

    边缘检测系列3:【HED】 Holistically-Nested 边缘检测 - php中文网

模型结构

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

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

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

    • 层级输出上采样

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

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

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

  • 模型总体架构图如下:

    边缘检测系列3:【HED】 Holistically-Nested 边缘检测 - php中文网

代码实现

导入必要的模块

In [1]
import cv2import numpy as npfrom PIL import Imageimport paddleimport paddle.nn as nn

构建 HED Block

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

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

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

In [2]
class HEDBlock(nn.Layer):
    def __init__(self, in_channels, out_channels, paddings, 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=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 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)

构建 HED Caffe 模型

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

    AI工具箱
    AI工具箱

    AI工具箱是一个全方位AI资源聚合平台

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

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

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

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

In [3]
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 Blocks
        for 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()]        # Upsamples
        for 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 = True
            self.add_sublayer(f'upsample{index}', upsample)        # 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 = 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)    @staticmethod
    def bilinear_kernel(in_channels, out_channels, kernel_size):
        '''
        return a bilinear filter tensor
        '''
        factor = (kernel_size + 1) // 2
        if kernel_size % 2 == 1:
            center = factor - 1
        else:
            center = factor - 0.5
        og = 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), :, :] = filt        return paddle.to_tensor(weight, dtype='float32')

构建 HED 模型

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

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

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

    • 采用 Bilinear Upsampling 进行上采样

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

In [4]
# 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)

预训练模型

In [5]
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

In [6]
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

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

模型推理

In [8]
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)
<PIL.Image.Image image mode=RGB size=960x320 at 0x7F3390C85090>
代码解释

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Nginx跨平台安装实操指南:Windows、macOS与Linux环境快速搭建
Nginx跨平台安装实操指南:Windows、macOS与Linux环境快速搭建

本指南详解Nginx在Windows、macOS及Linux系统的安装全流程。涵盖官方包解压、Homebrew一键部署、APT/YUM源配置及Docker容器化方案。无论新手或开发者,均可快速搭建运行环境,掌握跨平台核心指令,为后续配置与调优奠定坚实基础。

9

2026.03.16

chatgpt使用指南
chatgpt使用指南

本专题整合了chatgpt使用教程、新手使用说明等等相关内容,阅读专题下面的文章了解更多详细内容。

22

2026.03.16

chatgpt官网入口地址合集
chatgpt官网入口地址合集

本专题整合了chatgpt官网入口地址、使用教程等内容,阅读专题下面的文章了解更多详细内容。

52

2026.03.16

minimax入口地址汇总
minimax入口地址汇总

本专题整合了minimax相关入口合集,阅读专题下面的文章了解更多详细地址。

21

2026.03.16

C++多线程并发控制与线程安全设计实践
C++多线程并发控制与线程安全设计实践

本专题围绕 C++ 在高性能系统开发中的并发控制技术展开,系统讲解多线程编程模型与线程安全设计方法。内容包括互斥锁、读写锁、条件变量、原子操作以及线程池实现机制,同时结合实际案例分析并发竞争、死锁避免与性能优化策略。通过实践讲解,帮助开发者掌握构建稳定高效并发系统的关键技术。

10

2026.03.16

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

116

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

142

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

412

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

65

2026.03.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 4.3万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.6万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 94人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号