File size: 13,545 Bytes
21a6f2b
 
 
 
 
 
f021e6e
21a6f2b
 
c7854b5
f3b1617
 
 
 
 
 
 
 
 
 
c7854b5
 
f3b1617
c7854b5
 
 
21a6f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f021e6e
 
 
 
 
 
 
 
 
f8e3f6c
f021e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b5b5a0
 
f021e6e
1b5b5a0
 
 
 
 
 
 
 
 
 
 
 
 
f021e6e
 
 
 
21a6f2b
 
f021e6e
 
 
 
 
21a6f2b
f021e6e
21a6f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7854b5
1b5b5a0
f021e6e
1b5b5a0
f021e6e
 
1b5b5a0
f021e6e
1b5b5a0
21a6f2b
 
 
 
 
f021e6e
 
 
21a6f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7854b5
21a6f2b
 
 
 
 
 
 
 
 
 
 
 
 
c7854b5
21a6f2b
 
 
 
1b5b5a0
 
 
 
 
 
 
 
 
21a6f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b5b5a0
f021e6e
21a6f2b
1b5b5a0
 
21a6f2b
 
 
 
f3b1617
 
21a6f2b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""Denoising playground: compare open-source denoisers side by side.

    python app.py
"""
from __future__ import annotations

import gc
import os
import time



def _gpu_seconds(*args, **kwargs) -> int:
    """GPU time to reserve per run (same arguments as run). ZeroGPU charges the reservation
    against the visitor's daily quota, so keep it close to what the run really needs."""
    n = len(args[2]) if len(args) > 2 and args[2] else 1
    full = len(args) > 3 and args[3] == "Full image"
    return min(300, 60 + 40 * n) if full else 15 + 8 * n


try:  # Hugging Face ZeroGPU: must be imported before torch
    import spaces
    gpu = spaces.GPU(duration=_gpu_seconds)
except ImportError:
    def gpu(fn):
        return fn
from pathlib import Path

import cv2
import gradio as gr
import numpy as np
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
from skimage.restoration import estimate_sigma

import denoisers as D

RAW_EXT = {".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".rw2", ".orf", ".pef", ".srw", ".nrw"}
INPUT, REFERENCE = "Input (noisy)", "Clean reference"
HEADERS = ["Model", "Time (s)", "PSNR (dB)", "SSIM", "Residual noise σ", "Licence", "Commercial use"]
COMMERCIAL = {"yes": "Yes", "copyleft": "Yes, copyleft (GPL)", "no": "NO (research only)"}


# ------------------------------------------------------------------------- helpers
def develop_raw(path: str, ev: float = 0.0, half: bool = False, region=None) -> np.ndarray:
    """Camera RAW -> sRGB float32 in [0, 1], with no noise reduction and no tone curve.

    Developed to *linear* sRGB primaries (camera white balance, no auto-brightness),
    then exposed and encoded with the exact sRGB curve. Because nothing else is applied,
    the baseline's sRGB -> linear Rec.2020 conversion recovers true linear sensor data.
    """
    import rawpy
    def decode():
        with rawpy.imread(str(path)) as raw:  # str(): gradio passes a str subclass, rawpy wants exact str
            return raw.postprocess(use_camera_wb=True, output_bps=16, gamma=(1, 1),
                                   no_auto_bright=True, half_size=half)
    try:
        try:
            rgb = decode()
        except (MemoryError, rawpy.LibRawError):  # often just low RAM: drop cached models, retry
            D.unload()
            gc.collect()
            rgb = decode()
    except Exception as e:
        raise gr.Error(f"Could not decode RAW file {Path(path).name}: {e}")
    # auto exposure from the whole frame: put the 99.5th luminance percentile near the
    # top, then apply the EV offset
    p = float(np.percentile(rgb[::4, ::4].mean(2), 99.5)) / 65535
    gain = float(np.clip(0.85 / max(p, 1e-4), 1, 32)) * 2.0 ** ev
    if region:  # crop while still uint16: a full 24+ MP frame in float32 is ~300 MB per copy
        rgb = crop_region(rgb, *region)
    return D.linear_to_srgb(rgb.astype(np.float32) * (gain / 65535))


def preview(path: str | None, ev: float):
    """Preview + info line for the uploaded file; shows the EV slider only for RAW."""
    if not path:
        return None, "", gr.update(visible=False)
    is_raw = Path(path).suffix.lower() in RAW_EXT
    if is_raw:  # half-size decode: fast, and plenty for a preview
        img = develop_raw(path, ev, half=True)
        h, w = img.shape[0] * 2, img.shape[1] * 2
    else:
        img = load_image(path)
        h, w = img.shape[:2]
    s = 1024 / max(img.shape[:2])
    if s < 1:
        img = cv2.resize(img, None, fx=s, fy=s, interpolation=cv2.INTER_AREA)
    kind = "camera RAW, developed without noise reduction" if is_raw else "image"
    return u8(img), f"**{Path(path).name}**: {w} x {h} px ({kind})", gr.update(visible=is_raw)


def load_image(path: str | None, ev: float = 0.0, region=None) -> np.ndarray | None:
    """Any image or camera RAW -> sRGB float32 HxWx3 in [0, 1], cropped to `region`."""
    if not path:
        return None
    img = _read(path, ev, region)
    return img if Path(path).suffix.lower() in RAW_EXT or not region else crop_region(img, *region)


def _read(path: str, ev: float, region) -> np.ndarray:
    if Path(path).suffix.lower() in RAW_EXT:
        return develop_raw(path, ev, region=region)
    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    if img is None:
        raise gr.Error(f"Could not read {Path(path).name}")
    scale = 65535 if img.dtype == np.uint16 else 255
    if img.ndim == 2:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    return img[..., 2::-1].astype(np.float32) / scale  # drops alpha, BGR -> RGB


def crop_region(img: np.ndarray, mode: str, size: int, cx: float, cy: float) -> np.ndarray:
    h, w = img.shape[:2]
    if mode == "Full image":
        return img
    if mode == "Downscale to max side":
        s = size / max(h, w)
        return img if s >= 1 else cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
    ch, cw = min(size, h), min(size, w)
    y = int(round((h - ch) * cy / 100))
    x = int(round((w - cw) * cx / 100))
    return img[y:y + ch, x:x + cw]


def add_noise(img: np.ndarray, sigma: float, shot: float, seed: int = 0) -> np.ndarray:
    """Gaussian read noise (sigma on the 0-255 scale) + signal-dependent shot noise."""
    if sigma <= 0 and shot <= 0:
        return img
    rng = np.random.default_rng(seed)
    var = (sigma / 255) ** 2 + (shot / 255) ** 2 * img
    return np.clip(img + rng.normal(0, 1, img.shape) * np.sqrt(var), 0, 1).astype(np.float32)


def u8(img: np.ndarray) -> np.ndarray:
    return (np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)


def row(name, img, ref, seconds, licence="", commercial=""):
    psnr = ssim = ""
    if ref is not None:
        psnr = round(float(peak_signal_noise_ratio(ref, img, data_range=1)), 2)
        ssim = round(float(structural_similarity(ref, img, channel_axis=2, data_range=1)), 4)
    sigma = round(float(estimate_sigma(img, channel_axis=2, average_sigmas=True)) * 255, 2)
    return [name, "" if seconds is None else round(seconds, 1), psnr, ssim, sigma, licence, commercial]


def model_table():
    return [[s.name, s.licence, COMMERCIAL[s.commercial], s.notes] for s in D.MODELS.values()]


# ----------------------------------------------------------------------------- run
@gpu
def run(src_path, ref_path, models, mode, size, cx, cy,
        noise_sigma, noise_shot, sigma, strength, tile, raw_ev=0.0, progress=gr.Progress()):
    if src_path and Path(src_path).suffix.lower() in RAW_EXT:
        progress(0, desc="Developing RAW…")
    region = (mode, size, cx, cy)
    noisy = load_image(src_path, raw_ev, region)
    if noisy is None:
        raise gr.Error("Upload an image or a camera RAW file first.")
    if not models:
        raise gr.Error("Pick at least one model.")

    ref = None
    if ref_path:
        ref = load_image(ref_path, region=region)
        if ref.shape != noisy.shape:
            raise gr.Error("The clean reference must have the same pixel dimensions as the input.")
    if noise_sigma > 0 or noise_shot > 0:  # synthetic test: the upload is the ground truth
        ref = noisy if ref is None else ref
        noisy = add_noise(noisy, noise_sigma, noise_shot)

    images = {INPUT: u8(noisy)}
    if ref is not None:
        images[REFERENCE] = u8(ref)
    rows = [row(INPUT, noisy, ref, None)]
    opts = {"sigma": sigma, "tile": int(tile)}

    def emit(status):
        names = list(images)
        right = names[-1]
        return (
            [(images[n], n) for n in names], rows, images,
            gr.update(choices=names, value=INPUT), gr.update(choices=names, value=right),
            (images[INPUT], images[right]), status,
        )

    yield emit("Starting…")
    for i, name in enumerate(models):
        spec = D.MODELS[name]

        def cb(frac, msg, i=i):
            progress((i + frac) / len(models), desc=msg)

        cb(0, f"{name}…")
        t0 = time.perf_counter()
        try:
            out, info = D.denoise(name, noisy, opts, cb)
        except Exception as e:  # keep going: one model failing (e.g. OOM) shouldn't kill the run
            rows.append([name, "", "", "", "", spec.licence, f"FAILED: {type(e).__name__}: {e}"[:120]])
            yield emit(f"{name} failed: {e}")
            continue
        dt = time.perf_counter() - t0
        if strength < 100:
            out = noisy + (out - noisy) * (strength / 100)
        images[name] = u8(out)
        rows.append(row(name, out, ref, dt, spec.licence, COMMERCIAL[spec.commercial]))
        yield emit(f"Done {i + 1}/{len(models)}: {name} in {dt:.1f}s")
    h, w = noisy.shape[:2]
    yield emit(f"Finished {len(models)} model(s) on a {w}x{h} region, device: {D.device()}.")


def compare(images, left, right):
    if not images or left not in images or right not in images:
        return None
    return images[left], images[right]


# ------------------------------------------------------------------------------ UI
with gr.Blocks(title="Denoising Playground") as demo:
    gr.Markdown(
        "# Denoising Playground\n"
        "Compare open-source denoisers against the **LightCraft baseline** on your own photos. "
        "Weights download on first use into `weights/`."
    )
    state = gr.State({})
    with gr.Row():
        with gr.Column(scale=1, min_width=340):
            src = gr.File(
                label="Noisy photo: JPEG / PNG / TIFF or camera RAW (DNG, CR2, CR3, NEF, ARW, RAF, …)",
                type="filepath", height=140,
                file_types=["image"] + sorted(RAW_EXT | {e.upper() for e in RAW_EXT}))
            src_info = gr.Markdown()
            src_view = gr.Image(label="Preview", interactive=False, height=240)
            raw_ev = gr.Slider(-3, 3, 0, step=0.25, label="RAW exposure compensation (EV)",
                               info="Applied on top of auto exposure.", visible=False)
            with gr.Accordion("Clean reference (optional)", open=False):
                ref = gr.Image(label="Clean reference, same size (enables PSNR / SSIM)",
                               type="filepath", sources=["upload"], height=180)
            models = gr.CheckboxGroup(list(D.MODELS), value=list(D.MODELS)[:4], label="Models")
            with gr.Accordion("Region to process", open=True):
                mode = gr.Radio(["Crop", "Downscale to max side", "Full image"], value="Crop",
                                label="Mode", info="Crop keeps true pixel-level noise. "
                                "Full image on CPU can take minutes per model.")
                size = gr.Slider(256, 2048, 768, step=64, label="Crop size / max side (px)")
                with gr.Row():
                    cx = gr.Slider(0, 100, 50, step=1, label="Crop X position (%)")
                    cy = gr.Slider(0, 100, 50, step=1, label="Crop Y position (%)")
            with gr.Accordion("Synthetic noise (treats the upload as ground truth)", open=False):
                noise_sigma = gr.Slider(0, 75, 0, step=1, label="Gaussian σ (0-255 scale)")
                noise_shot = gr.Slider(0, 75, 0, step=1, label="Shot noise (signal-dependent)")
            with gr.Accordion("Model settings", open=False):
                sigma = gr.Slider(1, 75, 15, step=1, label="Noise level σ",
                                  info="Only used by non-blind models: DRUNet and Non-Local Means.")
                strength = gr.Slider(0, 100, 100, step=5, label="Strength (%)",
                                     info="Blend of denoised result with the input, all models.")
                tile = gr.Slider(256, 1024, 512, step=64, label="Tile size (px)",
                                 info="Lower if you run out of memory. The baseline always uses 512.")
            go = gr.Button("Denoise", variant="primary")
            status = gr.Markdown()
        with gr.Column(scale=2):
            with gr.Row():
                left = gr.Dropdown([INPUT], value=INPUT, label="Left")
                right = gr.Dropdown([INPUT], value=INPUT, label="Right")
            slider = gr.ImageSlider(label="A / B comparison (drag the divider)", type="numpy",
                                    height=560, interactive=False)
            table = gr.Dataframe(headers=HEADERS, label="Results", interactive=False, wrap=True)
            gallery = gr.Gallery(label="All outputs", columns=3, height=420, object_fit="contain")
    with gr.Accordion("Models and licences", open=False):
        gr.Dataframe(value=model_table(), headers=["Model", "Licence", "Commercial use", "Notes"],
                     interactive=False, wrap=True)
        gr.Markdown(
            "PSNR / SSIM need a clean reference or synthetic noise. *Residual noise σ* is a "
            "wavelet estimate (0-255 scale) of what noise is left: lower is cleaner, but it "
            "cannot tell lost detail from removed noise, so judge with the A / B slider too."
        )

    go.click(run, [src, ref, models, mode, size, cx, cy,
                   noise_sigma, noise_shot, sigma, strength, tile, raw_ev],
             [gallery, table, state, left, right, slider, status])
    src.change(preview, [src, raw_ev], [src_view, src_info, raw_ev])
    raw_ev.release(preview, [src, raw_ev], [src_view, src_info, raw_ev])
    left.input(compare, [state, left, right], slider)
    right.input(compare, [state, left, right], slider)

if __name__ == "__main__":
    if "SPACE_ID" in os.environ:  # fetch weights at boot so downloads don't eat GPU quota
        D.prefetch()
    demo.queue(default_concurrency_limit=1).launch(inbrowser="SPACE_ID" not in os.environ)