picrest / restore.py
concisewebsesign's picture
Upload 12 files
3154e18 verified
Raw History Blame Contribute Delete
5.26 kB
"""PicRest restoration pipeline.
1. prep: find the print in a phone shot, straighten, trim the border, even out lighting
2. scratch detection (Microsoft "Bringing Old Photos Back to Life", full resolution)
3. scratch repair with the same project's restoration network. Its memory use grows fast with
size, so it runs on a copy of at most REPAIR_SIDE px, and only the repaired pixels (the scratch
mask) are blended back into the full-resolution photo. Everything outside the mask, faces
included, keeps its original pixels; the face stage of that project is not used at all.
4. gentle auto-levels so faded prints regain contrast
"""
import os
import shutil
import subprocess
import sys
import tempfile
import cv2
import numpy as np
from glare import fuse
from prep import even_lighting, prepare
BOP_GLOBAL = os.environ.get("BOP_GLOBAL", os.path.join(os.path.dirname(os.path.abspath(__file__)), "bop", "Global"))
REPAIR_SIDE = int(os.environ.get("REPAIR_SIDE", 640)) # ~6 GB RAM at 640
def auto_levels(img, clip=0.5):
"""Stretch the 0.5..99.5 percentile range; one shared stretch keeps the photo's toning."""
lo = min(np.percentile(img[..., c], clip) for c in range(3))
hi = max(np.percentile(img[..., c], 100 - clip) for c in range(3))
out = (img.astype(np.float32) - lo) * 255.0 / max(hi - lo, 1)
return np.clip(out, 0, 255).astype(np.uint8)
def _run(args):
subprocess.run([sys.executable, *args], cwd=BOP_GLOBAL, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def _resize(img, size, interp=cv2.INTER_AREA):
return cv2.resize(img, size, interpolation=interp)
def _match_tone(restored, original, keep):
"""Shift the network output's local brightness/colour to the original's, measured only where
the photo is undamaged (keep=1), so repaired patches don't show seams."""
sigma = max(original.shape[:2]) / 30
k = cv2.GaussianBlur(keep, (0, 0), sigma) + 1e-4
def local_mean(x):
return cv2.GaussianBlur(x * keep[..., None], (0, 0), sigma) / k[..., None]
o, r = original.astype(np.float32), restored.astype(np.float32)
return r + local_mean(o) - local_mean(r)
def restore(img, extras=()):
"""img: BGR uint8 array (a phone shot or a scan). extras: more shots of the same print from
other angles; glare is then taken out by using, everywhere, the shot where it is darkest.
Returns (restored BGR, info dict)."""
fused = 0
if extras:
first, found = prepare(img, light=False)
prepped, fused = fuse(first, list(extras))
prepped = even_lighting(prepped)
before = even_lighting(first) # the 'before' picture still shows the glare that was taken out
else:
prepped, found = prepare(img)
before = prepped
H, W = prepped.shape[:2]
work = tempfile.mkdtemp(prefix="picrest_")
try:
d = lambda *p: os.path.join(work, *p)
os.makedirs(d("full"))
cv2.imwrite(d("full", "photo.png"), prepped)
_run(["detection.py", "--test_path", d("full"), "--output_dir", d("det"),
"--input_size", "full_size", "--GPU", "-1"])
mask = cv2.imread(d("det", "mask", "photo.png"), cv2.IMREAD_GRAYSCALE)
mask = _resize(mask, (W, H), cv2.INTER_NEAREST)
damaged = float((mask > 127).mean())
if damaged < 0.0005:
return auto_levels(prepped), {"print_found": found, "prepped": before, "damaged": damaged, "fused": fused}
# repair on a smaller copy, using the full-res mask scaled down
k = min(1.0, REPAIR_SIDE / max(H, W))
w, h = (int(W * k) // 4 * 4, int(H * k) // 4 * 4)
os.makedirs(d("small", "input")); os.makedirs(d("small", "mask"))
cv2.imwrite(d("small", "input", "photo.png"), _resize(prepped, (w, h)))
cv2.imwrite(d("small", "mask", "photo.png"), (_resize(mask, (w, h)) > 60).astype(np.uint8) * 255)
_run(["test.py", "--Scratch_and_Quality_restore", "--test_input", d("small", "input"),
"--test_mask", d("small", "mask"), "--outputs_dir", d("rep"), "--gpu_ids", "-1"])
rep = cv2.imread(d("rep", "restored_image", "photo.png"))
rep = _resize(rep, (W, H), cv2.INTER_CUBIC)
m = cv2.dilate((mask > 127).astype(np.uint8), np.ones((5, 5), np.uint8)).astype(np.float32)
rep = _match_tone(rep, prepped, 1 - m)
alpha = cv2.GaussianBlur(m, (0, 0), 1.5)[..., None]
out = np.clip(prepped * (1 - alpha) + rep * alpha, 0, 255).astype(np.uint8)
return auto_levels(out), {"print_found": found, "prepped": before, "damaged": damaged, "fused": fused}
finally:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
import time
src, dst = sys.argv[1], sys.argv[2]
os.makedirs(dst, exist_ok=True)
for f in sorted(os.listdir(src)):
t = time.time()
res, info = restore(cv2.imread(os.path.join(src, f)))
name = os.path.splitext(f)[0]
cv2.imwrite(os.path.join(dst, name + "_prepped.png"), info["prepped"])
cv2.imwrite(os.path.join(dst, name + "_restored.png"), res)
print(f, f"{time.time() - t:.1f}s", "print found" if info["print_found"] else "no print found",
f"damage {info['damaged']:.1%}")