模块更新于 2026-11-20· 浏览 2· 下载 0
EGA 边缘引导注意力模块
免参数提边缘:用拉普拉斯算子从原图提取高频边缘特征,零可学习参数、几乎不增计算量,比 Sobel 等一阶算子得到的边缘更有意义
结构图

免参数提边缘:用拉普拉斯算子从原图提取高频边缘特征,零可学习参数、几乎不增计算量,比 Sobel 等一阶算子得到的边缘更有意义
论文信息
- 论文:MEGANet: Multi-Scale Edge-Guided Attention Network for Weak Boundary Polyp Segmentation
- 出处:arXiv 2023
核心痛点
结肠镜息肉分割中,息肉边界模糊、大小形状多变,背景纹理复杂;U-Net 类网络层层下采样,边缘等高频信息不断流失,解码拼不回精细边界,息肉边缘常常不干净。
模块亮点
- 免参数提边缘:用拉普拉斯算子从原图提取高频边缘特征,零可学习参数、几乎不增计算量,比 Sobel 等一阶算子得到的边缘更有意义
- 三路注意力协同精修:把高层预测图拆成反向注意力(1-预测)挖漏检、边界注意力(对预测做拉普拉斯)锁定边界,再配上原图高频边缘图,三路与编码特征逐支相乘后拼接,经注意力掩码与 CBAM 重标定后残差输出,弥合编码与解码特征间的语义鸿沟
- 消融实打实:只用高频特征时 ClinicDB mDice 91.7,补齐反向、边界注意力与 CBAM 后涨到 93.0,ETIS 同步从 71.6 涨到 78.9;高频特征逐级下采样获取比逐层拉普拉斯金字塔在 Kvasir 上高 1.2 mDice
适用场景
领域为医学图像分割 / 结肠镜息肉分割,原文在 Kvasir-SEG、CVC-ClinicDB、CVC-ColonDB、ETIS、EndoScene 五个基准上验证;也适合各类弱边界目标分割,如病灶分割、显著目标检测、遥感与工业检测。
插入位置建议
- 放在 U-Net 类网络每级 skip connection 处,编码特征先过 EGA 再送入解码器,原文五个分辨率层各放一个
- 接进逐级上采样的解码路径,用上一级预测图驱动反向与边界注意力,边解码边精修
- 用于 PraNet 等自带反向注意力的网络,升级为反向+边界+高频三路融合
适用任务
- 医学图像分割
- 结肠镜息肉分割
- 原文在 Kvasir-SEG
完整代码
ega.py
import warnings
warnings.filterwarnings("ignore")
import torch
if torch.cuda.is_available():
torch.cuda.init()
import torch.nn.functional as F
import torch.nn as nn
""" Edge-Guided Attention module (EGA)
这个模块实现的是一个基于边缘引导的注意力模块 (Edge-Guided Attention Module, EGA),主要用于计算机视觉中的图像处理任务,特别是关注于边缘信息的场景。下面是对代码各个部分及其用途的详细解释:
高斯模糊和金字塔
gauss_kernel(channels=3, cuda=True): 创建一个用于高斯模糊的卷积核。
downsample(x): 实现下采样,将图像尺寸减半。
conv_gauss(img, kernel): 对图像进行高斯卷积模糊处理。
upsample(x, channels): 实现上采样,将图像尺寸加倍。
make_laplace(img, channels): 生成拉普拉斯金字塔的一层,捕获高频信息。
make_laplace_pyramid(img, level, channels): 生成整个拉普拉斯金字塔,包含多层高频信息。
这些函数的组合用于提取和处理图像的多尺度特征,特别是高频边缘信息,这对于图像分割和检测等任务非常有用。
CBAM (Convolutional Block Attention Module)
ChannelGate: 用于生成通道注意力权重,基于全局平均池化和最大池化。
SpatialGate: 用于生成空间注意力权重,基于最大池化和平均池化的特征融合。
CBAM: 组合ChannelGate和SpatialGate,提供通道和空间的联合注意力机制。
CBAM模块用于增强重要特征,抑制不重要特征,从而提升模型的性能。
EGA (Edge-Guided Attention Module)
EGA类: 主要模块,整合边缘特征、输入特征和预测特征,通过注意力机制融合这些特征,从而增强重要特征的表达。
EGA模块的处理流程如下:
Reverse Attention: 基于预测结果计算背景注意力,并得到背景特征。
Boundary Attention: 通过拉普拉斯金字塔提取预测边缘特征,并生成预测特征。
High-Frequency Feature: 利用高频边缘特征,生成输入特征。
Feature Fusion: 将以上三种特征融合,经过卷积和注意力机制生成融合特征。
Output: 融合特征加上残差,经过CBAM模块,得到最终输出。
主要用途
这个模块主要用于增强图像处理任务中的边缘和高频特征,适用于以下场景:
图像分割: 提高边界精度。
目标检测: 强化边缘特征,提升检测效果。
图像超分辨率: 更好地恢复高频细节。
通过EGA模块,可以更好地捕捉和利用图像中的边缘和细节信息,提升模型在各种图像处理任务中的表现。
"""
def gauss_kernel(channels=3, cuda=True):
kernel = torch.tensor([[1., 4., 6., 4., 1],
[4., 16., 24., 16., 4.],
[6., 24., 36., 24., 6.],
[4., 16., 24., 16., 4.],
[1., 4., 6., 4., 1.]])
kernel /= 256.
kernel = kernel.repeat(channels, 1, 1, 1)
if cuda:
kernel = kernel.cuda()
return kernel
def downsample(x):
return x[:, :, ::2, ::2]
def conv_gauss(img, kernel):
img = F.pad(img, (2, 2, 2, 2), mode='reflect')
out = F.conv2d(img, kernel, groups=img.shape[1])
return out
def upsample(x, channels):
cc = torch.cat([x, torch.zeros(x.shape[0], x.shape[1], x.shape[2], x.shape[3], device=x.device)], dim=3)
cc = cc.view(x.shape[0], x.shape[1], x.shape[2] * 2, x.shape[3])
cc = cc.permute(0, 1, 3, 2)
cc = torch.cat([cc, torch.zeros(x.shape[0], x.shape[1], x.shape[3], x.shape[2] * 2, device=x.device)], dim=3)
cc = cc.view(x.shape[0], x.shape[1], x.shape[3] * 2, x.shape[2] * 2)
x_up = cc.permute(0, 1, 3, 2)
return conv_gauss(x_up, 4 * gauss_kernel(channels))
def make_laplace(img, channels):
filtered = conv_gauss(img, gauss_kernel(channels))
down = downsample(filtered)
up = upsample(down, channels)
if up.shape[2] != img.shape[2] or up.shape[3] != img.shape[3]:
up = nn.functional.interpolate(up, size=(img.shape[2], img.shape[3]))
diff = img - up
return diff
def make_laplace_pyramid(img, level, channels):
current = img
pyr = []
for _ in range(level):
filtered = conv_gauss(current, gauss_kernel(channels))
down = downsample(filtered)
up = upsample(down, channels)
if up.shape[2] != current.shape[2] or up.shape[3] != current.shape[3]:
up = nn.functional.interpolate(up, size=(current.shape[2], current.shape[3]))
diff = current - up
pyr.append(diff)
current = down
pyr.append(current)
return pyr
class ChannelGate(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16):
super(ChannelGate, self).__init__()
self.gate_channels = gate_channels
self.mlp = nn.Sequential(
nn.Flatten(),
nn.Linear(gate_channels, gate_channels // reduction_ratio),
nn.ReLU(),
nn.Linear(gate_channels // reduction_ratio, gate_channels)
)
def forward(self, x):
avg_out = self.mlp(F.avg_pool2d(x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))).unsqueeze(-1).unsqueeze(-1)
max_out = self.mlp(F.max_pool2d(x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))).unsqueeze(-1).unsqueeze(-1)
channel_att_sum = avg_out + max_out
scale = torch.sigmoid(channel_att_sum).expand_as(x)
return x * scale
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
kernel_size = 7
self.spatial = nn.Conv2d(2, 1, kernel_size, stride=1, padding=(kernel_size - 1) // 2)
def forward(self, x):
x_compress = torch.cat((torch.max(x, 1)[0].unsqueeze(1), torch.mean(x, 1).unsqueeze(1)), dim=1)
x_out = self.spatial(x_compress)
scale = torch.sigmoid(x_out) # broadcasting
return x * scale
class CBAM(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16):
super(CBAM, self).__init__()
self.ChannelGate = ChannelGate(gate_channels, reduction_ratio)
self.SpatialGate = SpatialGate()
def forward(self, x):
x_out = self.ChannelGate(x)
x_out = self.SpatialGate(x_out)
return x_out
# Edge-Guided Attention Module
class EGA(nn.Module):
def __init__(self, in_channels):
super(EGA, self).__init__()
self.fusion_conv = nn.Sequential(
nn.Conv2d(in_channels * 3, in_channels, 3, 1, 1),
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True))
self.attention = nn.Sequential(
nn.Conv2d(in_channels, 1, 3, 1, 1),
nn.BatchNorm2d(1),
nn.Sigmoid())
self.cbam = CBAM(in_channels)
def forward(self, edge_feature, x, pred):
residual = x
xsize = x.size()[2:]
pred = torch.sigmoid(pred)
# reverse attention
background_att = 1 - pred
background_x = x * background_att
# boudary attention
edge_pred = make_laplace(pred, 1)
pred_feature = x * edge_pred
# high-frequency feature
edge_input = F.interpolate(edge_feature, size=xsize, mode='bilinear', align_corners=True)
input_feature = x * edge_input
fusion_feature = torch.cat([background_x, pred_feature, input_feature], dim=1)
fusion_feature = self.fusion_conv(fusion_feature)
attention_map = self.attention(fusion_feature)
fusion_feature = fusion_feature * attention_map
out = fusion_feature + residual
out = self.cbam(out)
return out
if __name__ == '__main__':
in_channels = 3
height, width = 224, 224
edge_feature = torch.rand(1, in_channels, height, width).cuda()
x = torch.rand(1, in_channels, height, width).cuda()
pred = torch.rand(1, 1, height, width).cuda()
block = EGA(in_channels).cuda()
output = block(edge_feature, x, pred)
print("Edge feature size:", edge_feature.size()) # torch.Size([1, 3, 224, 224])
print("Input feature size:", x.size()) # torch.Size([1, 3, 224, 224])
print("Prediction size:", pred.size()) # torch.Size([1, 1, 224, 224])
print("Output size:", output.size()) # torch.Size([1, 3, 224, 224])
环境与依赖
Python 3.9+
继续浏览
下一篇EMA 指数移动平均分解免填充零参数:只需平滑因子 α(如 0.3),无可学习参数;指数衰减给近期数据更大权重,天然对齐序列长度,不需要 padding,避开 SMA 首尾失真相关资源
模块2026-11-20
CDFA 对比驱动特征聚合模块
对比引导窗口注意力:把 SID 解耦出的前景、背景特征各经一个线性层,在 K×K 局部窗口内生成注意力权重,两步加权后密集聚合,显式引导多级特征融合
医学图像分割CDFAConDSeg
医学影像MIT
模块2026-11-20
ConvSSM 卷积状态空间模块
卷积SSM双分支:输入按通道一分为二,一半卷积分支抠局部细节,另一半经深度卷积送入 SS2D 四方向选择性扫描建模长程依赖,拼接后 1×1 卷积融合、残差输出
医学图像图像分类ConvSSM
医学影像MIT
模块2026-11-20
EPA 高效配对注意力
复杂度二次变线性:空间分支把 K、V 先投影到固定低维空间(p 维,p 远小于 n)再算注意力,复杂度从 O(n²) 降到 O(np),3D 体数据也能轻量做全局建模
医学图像分割EPA注意力机制
医学影像MIT