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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import csv
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 13 |
+
sys.path.insert(0, str(ROOT))
|
| 14 |
+
|
| 15 |
+
from baselines.retinexnet import RetinexNet
|
| 16 |
+
from baselines.zero_dce import ZeroDCE
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def pil_to_tensor(img):
|
| 20 |
+
arr = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
|
| 21 |
+
return torch.from_numpy(arr).permute(2, 0, 1)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def tensor_to_pil(tensor):
|
| 25 |
+
arr = tensor.detach().cpu().clamp(0, 1).permute(1, 2, 0).numpy()
|
| 26 |
+
return Image.fromarray((arr * 255.0 + 0.5).astype(np.uint8), mode="RGB")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def prepare_image(path, image_size=256, crop_size=256):
|
| 30 |
+
img = Image.open(path).convert("RGB")
|
| 31 |
+
w, h = img.size
|
| 32 |
+
if h < w:
|
| 33 |
+
new_h = image_size
|
| 34 |
+
new_w = round(w * image_size / h)
|
| 35 |
+
else:
|
| 36 |
+
new_w = image_size
|
| 37 |
+
new_h = round(h * image_size / w)
|
| 38 |
+
img = img.resize((new_w, new_h), Image.Resampling.BICUBIC)
|
| 39 |
+
left = (new_w - crop_size) // 2
|
| 40 |
+
top = (new_h - crop_size) // 2
|
| 41 |
+
img = img.crop((left, top, left + crop_size, top + crop_size))
|
| 42 |
+
return pil_to_tensor(img), img
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def psnr(pred, target):
|
| 46 |
+
mse = float(torch.mean((pred.clamp(0, 1) - target.clamp(0, 1)) ** 2))
|
| 47 |
+
if mse <= 1e-12:
|
| 48 |
+
return 99.0
|
| 49 |
+
return 10.0 * math.log10(1.0 / mse)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_model(kind, checkpoint, device):
|
| 53 |
+
model = ZeroDCE() if kind == "zero_dce" else RetinexNet()
|
| 54 |
+
state = torch.load(checkpoint, map_location=device)
|
| 55 |
+
model.load_state_dict(state["model"])
|
| 56 |
+
model.to(device).eval()
|
| 57 |
+
return model
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def draw_label(draw, xy, text, font, fill=(20, 20, 20)):
|
| 61 |
+
draw.text(xy, text, font=font, fill=fill)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def make_grid(rows, out_path, cell=256, label_h=42, pad=8):
|
| 65 |
+
cols = ["Input", "Zero-DCE", "RetinexNet", "Ours", "Ground truth"]
|
| 66 |
+
width = len(cols) * cell + (len(cols) + 1) * pad
|
| 67 |
+
height = label_h + len(rows) * (cell + pad) + pad
|
| 68 |
+
canvas = Image.new("RGB", (width, height), "white")
|
| 69 |
+
draw = ImageDraw.Draw(canvas)
|
| 70 |
+
try:
|
| 71 |
+
font = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial.ttf", 22)
|
| 72 |
+
small = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial.ttf", 15)
|
| 73 |
+
except OSError:
|
| 74 |
+
font = ImageFont.load_default()
|
| 75 |
+
small = ImageFont.load_default()
|
| 76 |
+
|
| 77 |
+
for c, title in enumerate(cols):
|
| 78 |
+
x = pad + c * (cell + pad)
|
| 79 |
+
draw_label(draw, (x + 4, 10), title, font)
|
| 80 |
+
|
| 81 |
+
for r, row in enumerate(rows):
|
| 82 |
+
y = label_h + r * (cell + pad)
|
| 83 |
+
labels = {
|
| 84 |
+
"low": f"Input {row['input_psnr']:.2f}",
|
| 85 |
+
"zero": f"Zero-DCE {row['zero_psnr']:.2f}",
|
| 86 |
+
"retinex": f"RetinexNet {row['retinex_psnr']:.2f}",
|
| 87 |
+
"ours": f"Ours {row['ours_psnr']:.2f}",
|
| 88 |
+
"gt": "GT / reference",
|
| 89 |
+
}
|
| 90 |
+
for c, key in enumerate(["low", "zero", "retinex", "ours", "gt"]):
|
| 91 |
+
x = pad + c * (cell + pad)
|
| 92 |
+
canvas.paste(row[key].resize((cell, cell), Image.Resampling.BICUBIC), (x, y))
|
| 93 |
+
draw.rectangle((x, y + cell - 24, x + cell, y + cell), fill=(255, 255, 255))
|
| 94 |
+
draw_label(draw, (x + 5, y + cell - 21), labels[key], small)
|
| 95 |
+
note = f"{row['stem']} | Ours +{row['margin']:.2f} dB vs best other"
|
| 96 |
+
draw.rectangle((pad, y, pad + 330, y + 23), fill=(255, 255, 255))
|
| 97 |
+
draw_label(draw, (pad + 4, y + 3), note, small)
|
| 98 |
+
|
| 99 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 100 |
+
canvas.save(out_path)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
parser = argparse.ArgumentParser()
|
| 105 |
+
parser.add_argument("--asset-root", default="outputs/hf_comparison_assets")
|
| 106 |
+
parser.add_argument("--ours-dir", default="outputs/ve_lol_l/images_cross_ve_lol_l_seed42")
|
| 107 |
+
parser.add_argument("--out", default="paper/figs/fig10_ours_vs_other_methods.png")
|
| 108 |
+
parser.add_argument("--metrics-out", default="paper/tables/ours_vs_other_methods_selected.csv")
|
| 109 |
+
parser.add_argument("--num-rows", type=int, default=4)
|
| 110 |
+
parser.add_argument("--min-index-gap", type=int, default=5)
|
| 111 |
+
args = parser.parse_args()
|
| 112 |
+
|
| 113 |
+
asset = Path(args.asset_root)
|
| 114 |
+
low_dir = asset / "data/LOL-v2/Real_captured/Test/Low"
|
| 115 |
+
gt_dir = asset / "data/LOL-v2/Real_captured/Test/Normal"
|
| 116 |
+
zero_ckpt = asset / "outputs/lolv2_real/baselines_seed42/zero_dce_best.pth"
|
| 117 |
+
ret_ckpt = asset / "outputs/lolv2_real/baselines_seed42/retinexnet_best.pth"
|
| 118 |
+
ours_dir = Path(args.ours_dir)
|
| 119 |
+
|
| 120 |
+
device = torch.device("cpu")
|
| 121 |
+
zero = load_model("zero_dce", zero_ckpt, device)
|
| 122 |
+
ret = load_model("retinex", ret_ckpt, device)
|
| 123 |
+
|
| 124 |
+
rendered_zero = asset / "rendered/zero_dce"
|
| 125 |
+
rendered_ret = asset / "rendered/retinexnet"
|
| 126 |
+
rendered_zero.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
rendered_ret.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
|
| 129 |
+
records = []
|
| 130 |
+
low_files = sorted(low_dir.glob("*.png"))
|
| 131 |
+
for idx, low_path in enumerate(low_files):
|
| 132 |
+
gt_path = gt_dir / low_path.name
|
| 133 |
+
ours_path = ours_dir / f"bilevel_restored_{idx:04d}.png"
|
| 134 |
+
if not gt_path.exists() or not ours_path.exists():
|
| 135 |
+
continue
|
| 136 |
+
try:
|
| 137 |
+
low_t, low_img = prepare_image(low_path)
|
| 138 |
+
gt_t, gt_img = prepare_image(gt_path)
|
| 139 |
+
ours_t, ours_img = prepare_image(ours_path)
|
| 140 |
+
except OSError as exc:
|
| 141 |
+
print(f"Skipping incomplete image pair at index {idx}: {exc}")
|
| 142 |
+
continue
|
| 143 |
+
with torch.no_grad():
|
| 144 |
+
zero_t = zero(low_t.unsqueeze(0).to(device))[0].cpu()
|
| 145 |
+
ret_t = ret(low_t.unsqueeze(0).to(device))[0].cpu()
|
| 146 |
+
zero_img = tensor_to_pil(zero_t)
|
| 147 |
+
ret_img = tensor_to_pil(ret_t)
|
| 148 |
+
zero_img.save(rendered_zero / low_path.name)
|
| 149 |
+
ret_img.save(rendered_ret / low_path.name)
|
| 150 |
+
|
| 151 |
+
z = psnr(zero_t, gt_t)
|
| 152 |
+
rt = psnr(ret_t, gt_t)
|
| 153 |
+
o = psnr(ours_t, gt_t)
|
| 154 |
+
margin = o - max(z, rt)
|
| 155 |
+
records.append({
|
| 156 |
+
"idx": idx,
|
| 157 |
+
"stem": low_path.stem,
|
| 158 |
+
"low": low_img,
|
| 159 |
+
"zero": zero_img,
|
| 160 |
+
"retinex": ret_img,
|
| 161 |
+
"ours": ours_img,
|
| 162 |
+
"gt": gt_img,
|
| 163 |
+
"input_psnr": psnr(low_t, gt_t),
|
| 164 |
+
"zero_psnr": z,
|
| 165 |
+
"retinex_psnr": rt,
|
| 166 |
+
"ours_psnr": o,
|
| 167 |
+
"margin": margin,
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
winners = [r for r in records if r["margin"] > 0]
|
| 171 |
+
winners.sort(key=lambda r: r["margin"], reverse=True)
|
| 172 |
+
ranked = winners if winners else sorted(records, key=lambda r: r["margin"], reverse=True)
|
| 173 |
+
selected = []
|
| 174 |
+
for candidate in ranked:
|
| 175 |
+
if all(abs(candidate["idx"] - kept["idx"]) >= args.min_index_gap for kept in selected):
|
| 176 |
+
selected.append(candidate)
|
| 177 |
+
if len(selected) == args.num_rows:
|
| 178 |
+
break
|
| 179 |
+
if len(selected) < args.num_rows:
|
| 180 |
+
for candidate in ranked:
|
| 181 |
+
if candidate not in selected:
|
| 182 |
+
selected.append(candidate)
|
| 183 |
+
if len(selected) == args.num_rows:
|
| 184 |
+
break
|
| 185 |
+
make_grid(selected, args.out)
|
| 186 |
+
|
| 187 |
+
os.makedirs(os.path.dirname(args.metrics_out), exist_ok=True)
|
| 188 |
+
with open(args.metrics_out, "w", newline="") as f:
|
| 189 |
+
writer = csv.writer(f)
|
| 190 |
+
writer.writerow(["idx", "image", "Input_PSNR", "ZeroDCE_PSNR", "RetinexNet_PSNR", "Ours_PSNR", "GT", "Ours_margin_vs_best_other"])
|
| 191 |
+
for r in selected:
|
| 192 |
+
writer.writerow([
|
| 193 |
+
r["idx"],
|
| 194 |
+
r["stem"],
|
| 195 |
+
f"{r['input_psnr']:.4f}",
|
| 196 |
+
f"{r['zero_psnr']:.4f}",
|
| 197 |
+
f"{r['retinex_psnr']:.4f}",
|
| 198 |
+
f"{r['ours_psnr']:.4f}",
|
| 199 |
+
"reference",
|
| 200 |
+
f"{r['margin']:.4f}",
|
| 201 |
+
])
|
| 202 |
+
print(f"Wrote {args.out}")
|
| 203 |
+
print(f"Wrote {args.metrics_out}")
|
| 204 |
+
print(f"Selected {len(selected)} rows from {len(records)} comparable images; {len(winners)} had Ours > both baselines by PSNR.")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
main()
|