Skip to main content

Denoising with Linearized Bregman

This notebook mirrors SlimOptim’s denoising example using a wavelet sparsifying transform and the linearized Bregman iterations implemented in devitohorizon.optim.bregman. It demonstrates:

Requirements

  • PyWavelets: pip install -e .[optim-extra] or pip install PyWavelets
  • Optionally, scikit-image for a standard test image (falls back to synthetic if missing)
import numpy as np
import matplotlib.pyplot as plt
from devitohorizon.optim import bregman
try:
    from skimage import data, img_as_float
    img = img_as_float(data.moon())
except Exception:
    # Fallback synthetic image
    x = np.linspace(0, 1, 256)
    img = np.outer(np.sin(4*np.pi*x), np.cos(3*np.pi*x))

Load and Corrupt Image

# Use a smaller field-of-view for speed
img = img[128:-128, 128:-128].astype(float)
fig, ax = plt.subplots(1, 1, figsize=(4, 4), tight_layout=True)
ax.imshow(img, cmap='magma')
ax.set_title('Clean')
ax.axis('off')
plt.show()

Measurement Operator A (Romberg-like integration)

Following the tutorial, we build a tall measurement operator A as a vertical stack of k identical 2D Romberg-like integration operators acting on k blocks of size n×n in the image (stacked vertically). This yields b = A x + noise.

# Measurement operator: vcat of k identical
# random-convolution Romberg operators
# (JOLI joRomberg analog)
k = 4
n = img.shape[0]
assert img.shape[1] == n
n1, n2 = k*n, n

# Build random phases and random sign mask (per JOLI joRomberg)
rng = np.random.default_rng(0)
theta = rng.random((n, n))
p1 = np.exp(2j*np.pi*theta)
p2 = np.fft.fftn(np.real(np.fft.ifftn(p1)))
phs = p2 / np.maximum(1e-12, np.abs(p2))
sgn = np.sign(rng.standard_normal((n, n)))


def A_block_fwd(X):
    return np.real(sgn * np.fft.ifftn(phs * np.fft.fftn(X)))


def A_block_adj(Y):
    return np.real(np.fft.ifftn(np.conj(phs) * np.fft.fftn(sgn * Y)))


def A_fwd(x):
    X = np.asarray(x).reshape(n, n)
    Y = A_block_fwd(X)
    return np.tile(Y, (k, 1)).reshape(-1)


def A_adj(y):
    Ystack = np.asarray(y).reshape(k*n, n)
    accum = np.zeros((n, n), dtype=np.float64)
    for i in range(k):
        accum += A_block_adj(Ystack[i*n:(i+1)*n, :])
    return accum.reshape(-1)


# Measurements b = A vec(img) + noise
b = A_fwd(img.astype(np.float64).reshape(-1))
# no noise in this tutorial
B = b.reshape(n1, n2)
plt.figure(figsize=(6, 4))
plt.imshow(B, cmap='magma', aspect=.5)
plt.title('b')
plt.axis('off')
plt.show()

Sparsifying Transform (Identity)

For this tutorial, we follow the original setup using the identity transform (TD = I).

# Identity transform TD and adjoint
def TD(x):
    return np.asarray(x).reshape(-1)


def TD_adj(y):
    return np.asarray(y).reshape(-1)


# Sanity check
v = np.random.default_rng(0).standard_normal(img.size)
assert np.linalg.norm(TD_adj(TD(v)) - v) < 1e-12

Objective Function

We solve a data-fitting problem 0.5||A x − b||² with b = A x_true. bregman applies an L1 penalty in the transform domain via soft-thresholding of the dual variable.

b = b  # already a vector from measurement cell


def fg(x):
    r = A_fwd(x) - b
    return 0.5*float(r @ r), A_adj(r)


x0 = np.zeros(n*n)
f0, _ = fg(x0)
f0

Run Linearized Bregman

We use a fixed step tau and let the threshold be estimated automatically from the initial dual variable (95% quantile). The callback records the objective and L1(TD(x)) for plots.

hist_f, hist_l1, hist_err = [], [], []

x_true = img.reshape(-1)


def callback(xk):
    f, _ = fg(xk)
    hist_f.append(f)
    hist_l1.append(np.linalg.norm(TD(xk), 1))
    hist_err.append(np.linalg.norm(xk - x_true)/max(1e-12, np.linalg.norm(x_true)))


def lambda_func(z):
    return np.quantile(np.abs(z), 0.5)


x_opt, f_opt, info = bregman(
    fg, x0, bounds=None, maxiter=200,
    tau=None, alpha=0.5, l1_lambda=None,
    progTol=1e-8, lambda_func=lambda_func,
    verbose=True, TD=TD, TD_adj=TD_adj, use_spg_step=True, callback=callback
)
f_opt, info

Visualize Results

denoised = x_opt.reshape(img.shape)
fig, axs = plt.subplots(1, 3, figsize=(12, 6), tight_layout=True)
axs[0].imshow(img, cmap='magma')
axs[0].set_title('Original')
axs[0].axis('off')
diff = denoised - img
cl = np.max(np.abs(diff)) or 1.0
axs[1].imshow(denoised, cmap='magma')
axs[1].set_title('Reconstruction')
axs[1].axis('off')
axs[2].imshow(diff, cmap='seismic', vmin=-cl, vmax=cl)
axs[2].set_title('Difference')
axs[2].axis('off')
plt.show()

# Data-consistency on observed pixels
Ax = A_fwd(x_opt)
cons_err = np.linalg.norm(Ax - b) / max(1e-12, np.linalg.norm(b))
print({'relative_data_error': cons_err})
{'relative_data_error': np.float64(2.1958177347137895e-16)}

Convergence Plots

fig, ax = plt.subplots(1, 2, figsize=(10, 3.5), tight_layout=True)
ax[0].semilogy(hist_f)
ax[0].set_title('Objective 0.5||x-b||^2')
ax[0].set_xlabel('iter')
ax[0].grid(True, alpha=.3)
ax[1].plot(hist_l1)
ax[1].set_title('L1 norm of TD(x)')
ax[1].set_xlabel('iter')
ax[1].grid(True, alpha=.3)
plt.show()

Reconstruction Error

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3))
plt.semilogy(hist_err)
plt.title('Relative reconstruction error')
plt.xlabel('iter')
plt.grid(True, which='both', alpha=.3)
plt.show()
Back to top