Skip to content

Diffusion-based image restoration & inverse problems; implementations of DiffPIR, DPS, RePaint, DDRM for inpainting, CT, and deblurring.

License

Notifications You must be signed in to change notification settings

MohammadSadeghSalehi/diffusion-inverse-problems

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Diffusion for Inverse Problems

This repository provides implementations of state-of-the-art diffusion-based methods for solving inverse problems in imaging, including DiffPIR, DPS, DDRM, and RePaint.

Ground Truth DiffPIR DPS

Ground Truth DiffPIR-DDRM


✨ Highlights

  • 🧩 Modular algorithms: easily swap between DDPM/DDIM pipelines
  • πŸ–ΌοΈ Plug-and-play operators for inpainting, tomography (CT), and deblurring
  • πŸ““ Prebuilt Jupyter notebooks for fast experimentation
  • πŸ”¬ Real-world applications: object removal (like Apple Retouch/Google Magic Eraser), CT reconstruction, and image deblurring

πŸš€ Quick Start

# Clone the repository
git clone https://github.com/MohammadSadeghSalehi/diffusion-inverse-problems.git
cd diffusion-inverse-problems

# Install dependencies
pip install -r requirements.txt

# (Optional) Install in editable mode for development
pip install -e .

# Run demo notebook
jupyter notebook notebooks/demo_inpainting.ipynb

πŸ“š Implemented Algorithms

Algorithm Description Paper
DiffPIR Proximal gradient with diffusion priors Zhu et al., 2023
DPS Diffusion posterior sampling for noisy inverse problems Chung et al., 2023
DDRM DDPM/DDIM schedulers for image restoration Kawar et al., 2022
RePaint Iterative inpainting with resampling Lugmayr et al., 2022

πŸ“¦ Repository Structure

diffusion-inverse-problems/
β”‚
β”œβ”€β”€ algorithms/              # Core algorithm implementations
β”‚   β”œβ”€β”€ diffpir.py          # DiffPIR implementation
β”‚   β”œβ”€β”€ dps.py              # DPS implementation
β”‚   β”œβ”€β”€ repaint.py          # RePaint implementation
β”‚   β”œβ”€β”€ ddrm.py             # DDRM implementation
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ physics/                # Forward model operators
β”‚   β”œβ”€β”€ inpainting.py       # Inpainting masks and operators
β”‚   β”œβ”€β”€ tomography.py       # CT reconstruction operators
β”‚   β”œβ”€β”€ blur.py             # Blur kernels and deblurring
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ utils/                  # Utility functions
β”‚   β”œβ”€β”€ dataset.py          # Dataset loaders (MRI, CelebA-HQ, etc.)
β”‚   β”œβ”€β”€ degrade.py          # Image corruption operators
β”‚   β”œβ”€β”€ visualization.py    # Plotting and visualization tools
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ notebooks/              # Example notebooks and demos
β”‚   β”œβ”€β”€ demo_inpainting.ipynb
β”‚   └── demo_tomography.ipynb
β”‚
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ README.md
└── LICENSE

πŸ“Š Example Usage

Basic Inpainting Example

import torch
import numpy as np
from diffusers import DDPMPipeline
import sys, os

# Adding project root (parent of notebooks/) to Python path
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "..")))

# === Imports from Repo ===
from algorithms.repaint import repaint
from utils.dataset import get_pipeline_and_dataset
from utils.degrade import degrade_dataloader
from utils.visualization import show_images
import deepinv as dinv
from physics.inpainting import InpaintingProblem

torch.manual_seed(0)

# === Device Selection ===
device = torch.device(
    "cuda" if torch.cuda.is_available()
    else "mps" if torch.backends.mps.is_available()
    else "cpu"
)

# === Load Pipeline and Dataset ===
pipeline, dataloader = get_pipeline_and_dataset(
    model_name="google/ddpm-celebahq-256",
    dataset_name="BSDS500",   # options: "CT", "CelebA-HQ", ...
    batch_size=1,
    img_size=256,
    subset_ratio=0.01,
    device=device
)

# === Problem Selection ===
problem = "inpainting"
img_size = (3, 256, 256)
noise_level = 0.0

if problem == "inpainting":
    mask = torch.ones(1, img_size[1], img_size[2])
    mask[:, 32:64, 32:64] = 0  # Example: square mask
    physics = InpaintingProblem(img_size=img_size, mask=mask, device=device)
else:
    raise ValueError(f"Unknown problem type: {problem}")

# === Define Forward and Pseudo-inverse Operators ===
A, A_pinv = physics.A, physics.A_dagger

# === Corrupt Dataset ===
noisy_dataloader = degrade_dataloader(dataloader, A, noise_std=noise_level, device=device)

# === Load One Sample (clean + corrupted) ===
sample_clean = next(iter(dataloader))
clean_img = sample_clean["image"].to(device) if isinstance(sample_clean, dict) else sample_clean[0].to(device)

sample_noisy = next(iter(noisy_dataloader))
y = sample_noisy[0].to(device)

# Save GT vs Corrupted for comparison
show_images(
    [(clean_img + 1) / 2, (y + 1) / 2],
    titles=["Ground Truth", "Corrupted"],
    save_path=os.path.join("results", f"{problem}_gt_corrupted.png")
)

# === Run RePaint ===
print(f"Running reconstruction for {problem} with RePaint...")
reconstructed_repaint = repaint(
    pipeline=pipeline,
    y=y,
    A=A,
    A_pinv=A_pinv,
    sigma_n=noise_level,
    num_inference_steps=250,
    jump_length=10,
    jump_n_sample=10,
)

# Save Result
show_images(
    [(clean_img + 1) / 2, (y + 1) / 2, (reconstructed_repaint + 1) / 2],
    titles=["Ground Truth", "Corrupted", "RePaint Reconstruction"],
    save_path=os.path.join("results", f"{problem}_reconstructed_repaint.png")
)

For complete examples, see the notebooks in /notebooks/.


πŸ› οΈ Supported Operations

  • Inpainting: Remove unwanted objects, fill missing regions
  • CT Reconstruction: Reconstruct medical images from sparse projections
  • Deblurring: Remove motion blur and camera shake
  • Super-resolution: Enhance image resolution (coming soon)
  • MRI Reconstruction: Reconstruct medical images from undersampled measurements (coming soon)

πŸ“‹ Requirements

  • Python 3.9+
  • PyTorch 2.0+
  • CUDA 11.0+ (for GPU acceleration), MPS support for non-CT problems
  • Additional dependencies in requirements.txt

🀝 Contributing

We welcome contributions and:

  • Report bugs and request features
  • Submit pull requests
  • Add new algorithms or operators
  • Improve documentation

πŸ“š References

Algorithm Papers

RePaint: Inpainting using Denoising Diffusion Probabilistic Models

@inproceedings{lugmayr2022repaint,
  title={RePaint: Inpainting using Denoising Diffusion Probabilistic Models},
  author={Lugmayr, Andreas and Danelljan, Martin and Romero, Andres and Yu, Fisher and Timofte, Radu and Van Gool, Luc},
  booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
  pages={11461--11471},
  year={2022}
}

Diffusion Posterior Sampling for General Noisy Inverse Problems

@inproceedings{chung2023diffusion,
  title={Diffusion Posterior Sampling for General Noisy Inverse Problems},
  author={Chung, Hyungjin and Kim, Jeongsol and Mccann, Michael Thompson and Klasky, Marc Louis and Ye, Jong Chul},
  booktitle={The Eleventh International Conference on Learning Representations},
  year={2023},
  url={https://openreview.net/forum?id=OnD9zGAGT0k}
}

Denoising Diffusion Models for Plug-and-Play Image Restoration

@article{zhu2023denoising,
  title={Denoising Diffusion Models for Plug-and-Play Image Restoration},
  author={Zhu, Yuanzhi and Zhang, Kai and Liang, Jingyun and Cao, Jiezhang and Wen, Bihan and Timofte, Radu and Van Gool, Luc},
  journal={arXiv preprint arXiv:2305.08995},
  year={2023}
}

Denoising Diffusion Restoration Models

@article{kawar2022denoising,
  title={Denoising Diffusion Restoration Models},
  author={Kawar, Bahjat and Elad, Michael and Ermon, Stefano and Song, Jiaming},
  journal={arXiv preprint arXiv:2201.11793},
  year={2022}
}

πŸ“„ License

This project is licensed under the BSD 3-Clause License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Thanks to the authors of the original papers for their groundbreaking work
  • Special thanks to the open-source community for various code contributions
  • Built with ❀️ for the computer vision, inverse problems, and machine learning community

About

Diffusion-based image restoration & inverse problems; implementations of DiffPIR, DPS, RePaint, DDRM for inpainting, CT, and deblurring.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published