学术
模块更新于 2026-11-20· 浏览 0· 下载 0

WMB 小波 Mamba 块

小波低频管亮度:Haar 小波无损分解特征,交换实验中换 LL 分量比换傅里叶幅度分量 SSIM 高 0.08(0.9273 vs 0.8435),WMB 专注在小波域做实全局亮度

计算机视觉图像增强低照度图像增强WMBMambaACCV2024

结构图

WMB 小波 Mamba 块结构图
WMB 小波 Mamba 块结构图

小波低频管亮度:Haar 小波无损分解特征,交换实验中换 LL 分量比换傅里叶幅度分量 SSIM 高 0.08(0.9273 vs 0.8435),WMB 专注在小波域做实全局亮度

论文信息

  • 论文:Wavelet-based Mamba with Fourier Adjustment for Low-light Image Enhancement
  • 出处:ACCV 2024

核心痛点

低照度增强模型大多只在空间域处理:CNN 缺长程依赖,Transformer 又吃算力、推理慢;已有频域方法只用小波或只用傅里叶,而小波低频 LL 分量对全局亮度更敏感、傅里叶相位分量对局部细节更敏感,单一频域增强浪费了这些先验。

模块亮点

  • 小波低频管亮度:Haar 小波无损分解特征,交换实验中换 LL 分量比换傅里叶幅度分量 SSIM 高 0.08(0.9273 vs 0.8435),WMB 专注在小波域做实全局亮度
  • 通道维 Mamba 补长程:低频分支把 H×W 展平、以通道为维度跑 Channel-wise Mamba,线性复杂度补足长程依赖,开销比 Transformer 低
  • 整体又快又好:WMB 配 FFAB 组成 WalMaFa 在 LOL-v1、LOL-v2-real/syn 上达 SOTA,资源更少速度更快,15 人用户研究感知质量领先

适用场景

领域为低照度图像增强(LLIE),原文在 LOL-v1、LOL-v2-real、LOL-v2-synthetic 验证;可迁移到去噪、去模糊、超分等任务,及其他频域全局增强的 2D 网络。

插入位置建议

  • 替换 Restormer、Uformer 等复原网络 Transformer 块里的注意力,WMB 本身是完整块
  • 放进编码器 / 解码器各层级做多尺度亮度增强,原文就是三层 WMB 加下采样 / 上采样堆叠
  • 与频域细节模块串联:WMB 管全局亮度,Latent 用傅里叶相位模块(如原文 FFAB)管局部纹理细节

适用任务

  • 低照度图像增强

完整代码

wmb.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numbers

import einops
from einops import rearrange
from mamba_ssm import Mamba


"""《Wavelet-based Mamba with Fourier Adjustment for Low-light Image Enhancement》ACCV 2024
频率信息(例如离散小波变换和快速傅里叶变换)已广泛应用于解决低光图像增强 (LLIE) 问题。然而,现有的基于频率的模型主要在图像的简单小波或傅里叶空间中运行,缺乏对每个空间中有效的全局和局部信息的利用。
我们发现小波频率信息由于其低频分量而对全局亮度更敏感,而傅里叶频率信息由于其相位分量而对局部细节更敏感。
为了通过在小波变换中将空间通道信息与低频成分最佳地整合来实现卓越的初步亮度增强,我们引入了通道级别的 Mamba,它补偿了 CNN 的长距离依赖性,并且与扩散和 Transformer 模型相比具有更低的复杂度。
因此在这项工作中,我们提出了一种新颖的基于小波的具有傅里叶调整的 Mamba 模型 WalMaFa,由基于小波的 Mamba 块 (WMB) 和快速傅里叶调整块 (FFAB) 组成。我们采用 Encoder-Latent-Decoder 结构来实现端到端转换。
具体来说,在 Encoder 和 Decoder 中采用 WMB 来增强全局亮度,而在 Latent 中采用 FFAB 来微调局部纹理细节并缓解模糊性。大量实验表明,我们提出的 WalMaFa 以更少的计算资源和更快的速度实现了最先进的性能。
"""


m = None

def dwt_init(x):

    x01 = x[:, :, 0::2, :] / 2
    x02 = x[:, :, 1::2, :] / 2
    x1 = x01[:, :, :, 0::2]
    x2 = x02[:, :, :, 0::2]
    x3 = x01[:, :, :, 1::2]
    x4 = x02[:, :, :, 1::2]
    x_LL = x1 + x2 + x3 + x4
    x_HL = -x1 - x2 + x3 + x4
    x_LH = -x1 + x2 - x3 + x4
    x_HH = x1 - x2 - x3 + x4

    return torch.cat((x_LL, x_HL, x_LH, x_HH), 0)


def iwt_init(x):
    r = 2
    in_batch, in_channel, in_height, in_width = x.size()
    out_batch, out_channel, out_height, out_width = int(in_batch/(r**2)),in_channel, r * in_height, r * in_width
    x1 = x[0:out_batch, :, :] / 2
    x2 = x[out_batch:out_batch * 2, :, :, :] / 2
    x3 = x[out_batch * 2:out_batch * 3, :, :, :] / 2
    x4 = x[out_batch * 3:out_batch * 4, :, :, :] / 2

    h = torch.zeros([out_batch, out_channel, out_height,
                     out_width]).float().to(x.device)

    h[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4
    h[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4
    h[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4
    h[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4

    return h

class DWT(nn.Module):
    def __init__(self):
        super(DWT, self).__init__()
        self.requires_grad = False  # 信号处理,非卷积运算,不需要进行梯度求导

    def forward(self, x):
        return dwt_init(x)


class IWT(nn.Module):
    def __init__(self):
        super(IWT, self).__init__()
        self.requires_grad = False

    def forward(self, x):
        return iwt_init(x)



def data_transform(X):
    return 2 * X - 1.0


def inverse_data_transform(X):
    return torch.clamp((X + 1.0) / 2.0, 0.0, 1.0)


class Conv2d_BN(torch.nn.Sequential):
    def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1,
                 groups=1, bn_weight_init=1, resolution=-10000):
        super().__init__()
        self.add_module('c', torch.nn.Conv2d(
            a, b, ks, stride, pad, dilation, groups, bias=False))
        self.add_module('bn', torch.nn.BatchNorm2d(b))
        torch.nn.init.constant_(self.bn.weight, bn_weight_init)
        torch.nn.init.constant_(self.bn.bias, 0)

    @torch.no_grad()
    def fuse(self):
        c, bn = self._modules.values()
        w = bn.weight / (bn.running_var + bn.eps) ** 0.5
        w = c.weight * w[:, None, None, None]
        b = bn.bias - bn.running_mean * bn.weight / \
            (bn.running_var + bn.eps) ** 0.5
        m = torch.nn.Conv2d(w.size(1) * self.c.groups, w.size(
            0), w.shape[2:], stride=self.c.stride, padding=self.c.padding, dilation=self.c.dilation,
                            groups=self.c.groups,
                            device=c.weight.device)
        m.weight.data.copy_(w)
        m.bias.data.copy_(b)
        return m


##########################################################################
## Layer Norm

def to_3d(x):
    return rearrange(x, 'b c h w -> b (h w) c')


def to_4d(x, h, w):
    return rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)


class BiasFree_LayerNorm(nn.Module):
    def __init__(self, normalized_shape):
        super(BiasFree_LayerNorm, self).__init__()
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = (normalized_shape,)
        normalized_shape = torch.Size(normalized_shape)

        assert len(normalized_shape) == 1

        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.normalized_shape = normalized_shape

    def forward(self, x):
        sigma = x.var(-1, keepdim=True, unbiased=False)  ##返回所有元素的方差
        return x / torch.sqrt(sigma + 1e-5) * self.weight


class WithBias_LayerNorm(nn.Module):
    def __init__(self, normalized_shape):
        super(WithBias_LayerNorm, self).__init__()
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = (normalized_shape,)
        normalized_shape = torch.Size(normalized_shape)

        assert len(normalized_shape) == 1

        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.bias = nn.Parameter(torch.zeros(normalized_shape))
        self.normalized_shape = normalized_shape

    def forward(self, x):
        mu = x.mean(-1, keepdim=True)
        sigma = x.var(-1, keepdim=True, unbiased=False)
        return (x - mu) / torch.sqrt(sigma + 1e-5) * self.weight + self.bias


class LayerNorm(nn.Module):
    def __init__(self, dim, LayerNorm_type):
        super(LayerNorm, self).__init__()
        if LayerNorm_type == 'BiasFree':
            self.body = BiasFree_LayerNorm(dim)
        else:
            self.body = WithBias_LayerNorm(dim)

    def forward(self, x):
        h, w = x.shape[-2:]
        return to_4d(self.body(to_3d(x)), h, w)




class FeedForward(nn.Module):
    def __init__(self, dim, ffn_expansion_factor, bias):
        super(FeedForward, self).__init__()

        hidden_features = int(dim * ffn_expansion_factor)

        self.rep_conv1 = Conv2d_BN(hidden_features, hidden_features, 3, 1, 1, groups=hidden_features)
        self.rep_conv2 = Conv2d_BN(hidden_features, hidden_features, 1, 1, 0, groups=hidden_features)

        self.project_in = nn.Conv2d(dim, hidden_features, kernel_size=1, bias=bias)

        self.dwconv = nn.Conv2d(hidden_features, hidden_features, kernel_size=3, stride=1, padding=1,
                                groups=hidden_features, bias=bias)

        self.project_out = nn.Conv2d(hidden_features, dim, kernel_size=1, bias=bias)

    def forward(self, x):
        identity = x
        x = self.project_in(x)
        x1 = x + self.rep_conv1(x) + self.rep_conv2(x)
        x2 = self.dwconv(x)
        x = F.gelu(x2) * x1 + F.gelu(x1) * x2
        x = self.project_out(x)
        return x + identity

    @torch.no_grad()
    def fuse(self):
        conv = self.rep_conv1.fuse()  ##Conv_BN
        conv1 = self.rep_conv2.fuse()  ##Conv_BN

        conv_w = conv.weight
        conv_b = conv.bias
        conv1_w = conv1.weight
        conv1_b = conv1.bias

        conv1_w = torch.nn.functional.pad(conv1_w, [1, 1, 1, 1])

        identity = torch.nn.functional.pad(torch.ones(conv1_w.shape[0], conv1_w.shape[1], 1, 1, device=conv1_w.device),
                                           [1, 1, 1, 1])

        final_conv_w = conv_w + conv1_w + identity
        final_conv_b = conv_b + conv1_b

        conv.weight.data.copy_(final_conv_w)
        conv.bias.data.copy_(final_conv_b)
        return conv


class WM(nn.Module):
    def __init__(self, c=3):
        super().__init__()
        self.convb = nn.Sequential(
            nn.Conv2d(in_channels=c, out_channels=c * 2, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=c * 2, out_channels=c, kernel_size=3, stride=1, padding=1)
        )
        self.model1 = Mamba(
            # This module uses roughly 3 * expand * d_model^2 parameters
            d_model=c,  # Model dimension d_model
            d_state=32,  # SSM state expansion factor
            d_conv=4,  # Local convolution width
            expand=2,  # Block expansion factor
        )

        self.model2 = Mamba(
            # This module uses roughly 3 * expand * d_model^2 parameters
            d_model=c,  # Model dimension d_model
            d_state=32,  # SSM state expansion factor
            d_conv=4,  # Local convolution width
            expand=9,  # Block expansion factor
        )
        self.smooth = nn.Conv2d(in_channels=c, out_channels=c, kernel_size=3, stride=1, padding=1)
        self.ln = nn.LayerNorm(normalized_shape=c)
        self.softmax = nn.Softmax()

    def forward(self, x):
        b, c, h, w = x.shape
        x = self.convb(x) + x
        x = self.ln(x.reshape(b, -1, c))

        y = self.model1(x).permute(0, 2, 1)
        output = y.reshape(b, c, h, w)
        return self.smooth(output)

class Illumination_Estimator(nn.Module):
    def __init__(
            self, n_fea_middle, n_fea_in=4, n_fea_out=3):  # __init__部分是内部属性,而forward的输入才是外部输入
        super(Illumination_Estimator, self).__init__()

        self.conv1 = nn.Conv2d(n_fea_in, n_fea_middle, kernel_size=1, bias=True)

        self.depth_conv = nn.Conv2d(
            n_fea_middle, n_fea_middle, kernel_size=5, padding=2, bias=True, groups=n_fea_middle)

        self.conv2 = nn.Conv2d(n_fea_middle, n_fea_out, kernel_size=1, bias=True)

    def forward(self, img):
        # img:        b,c=3,h,w
        # mean_c:     b,c=1,h,w

        # illu_fea:   b,c,h,w
        # illu_map:   b,c=3,h,w

        mean_c = img.mean(dim=1).unsqueeze(1)
        # stx()
        input = torch.cat([img, mean_c], dim=1)

        x_1 = self.conv1(input)
        illu_fea = self.depth_conv(x_1)
        illu_map = self.conv2(illu_fea)
        return illu_fea, illu_map


class WMB(nn.Module):
    def __init__(self, dim, num_heads=1, ffn_expansion_factor=2.66, bias=True, LayerNorm_type='WithBias'):
        super(WMB, self).__init__()
        self.DWT = DWT()
        self.IWT = IWT()
        self.norm1 = LayerNorm(dim, LayerNorm_type)
        self.illu = Illumination_Estimator(dim, n_fea_in=dim + 1, n_fea_out=dim)
        self.norm2 = LayerNorm(dim, LayerNorm_type)
        self.ffn = FeedForward(dim, ffn_expansion_factor, bias)
        self.mb = WM(dim)

    def forward(self, input_):
        global m
        x = input_
        n, c, h, w = x.shape
        x = self.norm1(x)
        x = data_transform(x)
        input_dwt = self.DWT(x)
        # input_LL=A [B,C,H/2,W/2]   input_high0={V,H,D} [3B,C,H/2,W/2]
        input_LL, input_high = input_dwt[:n, ...], input_dwt[n:, ...]
        input_LL, input_image = self.illu(input_LL)
        input_high = self.mb(input_high)

        output = self.IWT(torch.cat((input_LL, input_high), dim=0))
        output = inverse_data_transform(output)

        x = x + output
        x = x + self.ffn(self.norm2(x))
        return x


if __name__ == '__main__':
    block = WMB(dim=32).to('cuda')
    input = torch.rand(2, 32, 64, 64).to('cuda')
    output = block(input)

    print("Input size:", input.size())
    print("Output size:", output.size())

环境与依赖

Python 3.9+

继续浏览

下一篇WMVF 基于小波的多视角特征融合模块先分频再融合:把两个视角特征各自拆成低频(宏观结构)与高频(边缘细节与噪声)分量,分开投影后再融合,把「噪声在高频、峰值在低频」的物理先验写进结构

相关资源