concisewebsesign commited on
Commit
affeece
·
verified ·
1 Parent(s): dc3b82c

Upload 7 files

Browse files
Files changed (8) hide show
  1. .gitattributes +1 -0
  2. app.py +42 -0
  3. example_couple.jpg +0 -0
  4. example_portrait.jpg +3 -0
  5. prep.py +99 -0
  6. requirements.txt +12 -0
  7. restore.py +102 -0
  8. setup_models.py +33 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ example_portrait.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import gradio as gr
3
+ import numpy as np
4
+
5
+ from setup_models import ensure_models
6
+
7
+ try: # ZeroGPU Spaces refuse to start unless at least one function asks for the GPU
8
+ import spaces
9
+
10
+ @spaces.GPU
11
+ def _gpu_placeholder():
12
+ pass
13
+ except ImportError:
14
+ pass
15
+
16
+ ensure_models()
17
+ from restore import restore # noqa: E402
18
+
19
+
20
+ def run(image):
21
+ if image is None:
22
+ raise gr.Error("Upload a photo first.")
23
+ bgr = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
24
+ out, info = restore(bgr)
25
+ note = ("Found the print edges and straightened it." if info["print_found"]
26
+ else "Couldn't find the print's edges, so the whole picture was used. "
27
+ "Try a shot with a little background visible around the photo.")
28
+ note += f" Repaired damage covering {info['damaged']:.1%} of the photo."
29
+ return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), note
30
+
31
+
32
+ with gr.Blocks(title="PicRest") as demo:
33
+ gr.Markdown("# PicRest\nTake a photo of an old print and upload it. PicRest straightens it, "
34
+ "repairs scratches and cracks, and restores faded contrast. Faces are not redrawn.")
35
+ with gr.Row():
36
+ inp = gr.Image(type="pil", label="Your photo of the photo")
37
+ out = gr.Image(type="numpy", label="Restored", format="png")
38
+ note = gr.Markdown()
39
+ gr.Button("Restore", variant="primary").click(run, inp, [out, note], api_name="restore")
40
+ gr.Examples(["example_couple.jpg", "example_portrait.jpg"], inp)
41
+
42
+ demo.queue(max_size=8).launch()
example_couple.jpg ADDED
example_portrait.jpg ADDED

Git LFS Details

  • SHA256: e204096c2a2374f04197aa555759341388d829e6c16769a402a83e0e90408bf0
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
prep.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 1 of PicRest: turn a phone shot of a print into a flat, cropped scan.
2
+
3
+ Non-generative: only geometry (crop/straighten) and gentle global tone fixes.
4
+ """
5
+ import cv2
6
+ import numpy as np
7
+
8
+
9
+ def _order(pts):
10
+ s, d = pts.sum(1), np.diff(pts, axis=1).ravel()
11
+ return np.float32([pts[s.argmin()], pts[d.argmin()], pts[s.argmax()], pts[d.argmax()]])
12
+
13
+
14
+ def find_print(img):
15
+ """Return the 4 corners of the photo print, or None if not confidently found."""
16
+ h, w = img.shape[:2]
17
+ k = 800 / max(h, w)
18
+ small = cv2.resize(img, None, fx=k, fy=k, interpolation=cv2.INTER_AREA)
19
+ gray = cv2.GaussianBlur(cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), (5, 5), 0)
20
+ best = None
21
+ for lo, hi in ((30, 90), (50, 150), (75, 200)):
22
+ edges = cv2.dilate(cv2.Canny(gray, lo, hi), np.ones((3, 3), np.uint8))
23
+ cnts, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
24
+ for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
25
+ area = cv2.contourArea(c)
26
+ if area < 0.2 * small.shape[0] * small.shape[1] or area > 0.98 * small.shape[0] * small.shape[1]:
27
+ continue
28
+ approx = cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), True)
29
+ if len(approx) == 4 and cv2.isContourConvex(approx):
30
+ if best is None or area > best[0]:
31
+ best = (area, approx.reshape(4, 2) / k)
32
+ break
33
+ return None if best is None else _order(best[1].astype(np.float32))
34
+
35
+
36
+ def flatten(img, quad):
37
+ tl, tr, br, bl = quad
38
+ W = int(max(np.linalg.norm(tr - tl), np.linalg.norm(br - bl)))
39
+ H = int(max(np.linalg.norm(bl - tl), np.linalg.norm(br - tr)))
40
+ M = cv2.getPerspectiveTransform(quad, np.float32([[0, 0], [W, 0], [W, H], [0, H]]))
41
+ return cv2.warpPerspective(img, M, (W, H), flags=cv2.INTER_CUBIC)
42
+
43
+
44
+ def trim_border(img):
45
+ """Drop a plain light border (white print margin) around the picture."""
46
+ gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 5).astype(np.float32)
47
+ h, w = gray.shape
48
+ m = int(0.15 * min(h, w))
49
+ def edge(lines):
50
+ # a border line is bright and smooth (lighting may still vary slowly along it).
51
+ # The outermost few lines can still hold table pixels, so the border may start a bit in.
52
+ seen = False
53
+ for i, line in enumerate(lines[:m]):
54
+ core = line[int(.1 * len(line)):int(.9 * len(line))]
55
+ is_border = core.mean() > 120 and np.abs(np.diff(core)).mean() < 2.5
56
+ if is_border:
57
+ seen = True
58
+ elif seen or i >= 10:
59
+ return i if seen else 0
60
+ return 0
61
+ t, b = edge(gray), edge(gray[::-1])
62
+ l, r = edge(gray.T), edge(gray.T[::-1])
63
+ if not (t + b + l + r):
64
+ return img
65
+ pad = 3
66
+ return img[t + pad:h - b - pad, l + pad:w - r - pad]
67
+
68
+
69
+ def even_lighting(img, strength=0.7):
70
+ """Remove soft glare / uneven light by flattening very low-frequency brightness."""
71
+ lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB).astype(np.float32)
72
+ L = lab[..., 0]
73
+ sigma = max(img.shape[:2]) / 6
74
+ illum = cv2.GaussianBlur(L, (0, 0), sigma)
75
+ corrected = L / np.maximum(illum, 1) * illum.mean()
76
+ lab[..., 0] = np.clip((1 - strength) * L + strength * corrected, 0, 255)
77
+ return cv2.cvtColor(lab.astype(np.uint8), cv2.COLOR_LAB2BGR)
78
+
79
+
80
+ def prepare(img, max_side=1600):
81
+ quad = find_print(img)
82
+ found = quad is not None
83
+ if found:
84
+ img = trim_border(flatten(img, quad))
85
+ img = even_lighting(img)
86
+ k = max_side / max(img.shape[:2])
87
+ if k < 1:
88
+ img = cv2.resize(img, None, fx=k, fy=k, interpolation=cv2.INTER_AREA)
89
+ return img, found
90
+
91
+
92
+ if __name__ == "__main__":
93
+ import sys, os
94
+ src, dst = sys.argv[1], sys.argv[2]
95
+ os.makedirs(dst, exist_ok=True)
96
+ for f in sorted(os.listdir(src)):
97
+ out, found = prepare(cv2.imread(os.path.join(src, f)))
98
+ print(f, "print found" if found else "no print edge found", out.shape)
99
+ cv2.imwrite(os.path.join(dst, os.path.splitext(f)[0] + ".png"), out)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ opencv-python-headless
4
+ scikit-image
5
+ easydict
6
+ pyyaml
7
+ dominate
8
+ dill
9
+ scipy
10
+ einops
11
+ matplotlib
12
+ tensorboardX
restore.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PicRest restoration pipeline.
2
+
3
+ 1. prep: find the print in a phone shot, straighten, trim the border, even out lighting
4
+ 2. scratch detection (Microsoft "Bringing Old Photos Back to Life", full resolution)
5
+ 3. scratch repair with the same project's restoration network. Its memory use grows fast with
6
+ size, so it runs on a copy of at most REPAIR_SIDE px, and only the repaired pixels (the scratch
7
+ mask) are blended back into the full-resolution photo. Everything outside the mask, faces
8
+ included, keeps its original pixels; the face stage of that project is not used at all.
9
+ 4. gentle auto-levels so faded prints regain contrast
10
+ """
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+
17
+ import cv2
18
+ import numpy as np
19
+
20
+ from prep import prepare
21
+
22
+ BOP_GLOBAL = os.environ.get("BOP_GLOBAL", os.path.join(os.path.dirname(os.path.abspath(__file__)), "bop", "Global"))
23
+ REPAIR_SIDE = int(os.environ.get("REPAIR_SIDE", 640)) # ~6 GB RAM at 640
24
+
25
+
26
+ def auto_levels(img, clip=0.5):
27
+ """Stretch the 0.5..99.5 percentile range; one shared stretch keeps the photo's toning."""
28
+ lo = min(np.percentile(img[..., c], clip) for c in range(3))
29
+ hi = max(np.percentile(img[..., c], 100 - clip) for c in range(3))
30
+ out = (img.astype(np.float32) - lo) * 255.0 / max(hi - lo, 1)
31
+ return np.clip(out, 0, 255).astype(np.uint8)
32
+
33
+
34
+ def _run(args):
35
+ subprocess.run([sys.executable, *args], cwd=BOP_GLOBAL, check=True,
36
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
37
+
38
+
39
+ def _resize(img, size, interp=cv2.INTER_AREA):
40
+ return cv2.resize(img, size, interpolation=interp)
41
+
42
+
43
+ def _match_tone(restored, original, keep):
44
+ """Shift the network output's local brightness/colour to the original's, measured only where
45
+ the photo is undamaged (keep=1), so repaired patches don't show seams."""
46
+ sigma = max(original.shape[:2]) / 30
47
+ k = cv2.GaussianBlur(keep, (0, 0), sigma) + 1e-4
48
+ def local_mean(x):
49
+ return cv2.GaussianBlur(x * keep[..., None], (0, 0), sigma) / k[..., None]
50
+ o, r = original.astype(np.float32), restored.astype(np.float32)
51
+ return r + local_mean(o) - local_mean(r)
52
+
53
+
54
+ def restore(img):
55
+ """img: BGR uint8 array (a phone shot or a scan). Returns (restored BGR, info dict)."""
56
+ prepped, found = prepare(img)
57
+ H, W = prepped.shape[:2]
58
+ work = tempfile.mkdtemp(prefix="picrest_")
59
+ try:
60
+ d = lambda *p: os.path.join(work, *p)
61
+ os.makedirs(d("full"))
62
+ cv2.imwrite(d("full", "photo.png"), prepped)
63
+ _run(["detection.py", "--test_path", d("full"), "--output_dir", d("det"),
64
+ "--input_size", "full_size", "--GPU", "-1"])
65
+ mask = cv2.imread(d("det", "mask", "photo.png"), cv2.IMREAD_GRAYSCALE)
66
+ mask = _resize(mask, (W, H), cv2.INTER_NEAREST)
67
+ damaged = float((mask > 127).mean())
68
+ if damaged < 0.0005:
69
+ return auto_levels(prepped), {"print_found": found, "prepped": prepped, "damaged": damaged}
70
+
71
+ # repair on a smaller copy, using the full-res mask scaled down
72
+ k = min(1.0, REPAIR_SIDE / max(H, W))
73
+ w, h = (int(W * k) // 4 * 4, int(H * k) // 4 * 4)
74
+ os.makedirs(d("small", "input")); os.makedirs(d("small", "mask"))
75
+ cv2.imwrite(d("small", "input", "photo.png"), _resize(prepped, (w, h)))
76
+ cv2.imwrite(d("small", "mask", "photo.png"), (_resize(mask, (w, h)) > 60).astype(np.uint8) * 255)
77
+ _run(["test.py", "--Scratch_and_Quality_restore", "--test_input", d("small", "input"),
78
+ "--test_mask", d("small", "mask"), "--outputs_dir", d("rep"), "--gpu_ids", "-1"])
79
+ rep = cv2.imread(d("rep", "restored_image", "photo.png"))
80
+ rep = _resize(rep, (W, H), cv2.INTER_CUBIC)
81
+
82
+ m = cv2.dilate((mask > 127).astype(np.uint8), np.ones((5, 5), np.uint8)).astype(np.float32)
83
+ rep = _match_tone(rep, prepped, 1 - m)
84
+ alpha = cv2.GaussianBlur(m, (0, 0), 1.5)[..., None]
85
+ out = np.clip(prepped * (1 - alpha) + rep * alpha, 0, 255).astype(np.uint8)
86
+ return auto_levels(out), {"print_found": found, "prepped": prepped, "damaged": damaged}
87
+ finally:
88
+ shutil.rmtree(work, ignore_errors=True)
89
+
90
+
91
+ if __name__ == "__main__":
92
+ import time
93
+ src, dst = sys.argv[1], sys.argv[2]
94
+ os.makedirs(dst, exist_ok=True)
95
+ for f in sorted(os.listdir(src)):
96
+ t = time.time()
97
+ res, info = restore(cv2.imread(os.path.join(src, f)))
98
+ name = os.path.splitext(f)[0]
99
+ cv2.imwrite(os.path.join(dst, name + "_prepped.png"), info["prepped"])
100
+ cv2.imwrite(os.path.join(dst, name + "_restored.png"), res)
101
+ print(f, f"{time.time() - t:.1f}s", "print found" if info["print_found"] else "no print found",
102
+ f"damage {info['damaged']:.1%}")
setup_models.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fetch Microsoft's "Bringing Old Photos Back to Life" code and its global-stage checkpoints (~2 GB).
2
+ Runs once when the Space starts; skipped if already present."""
3
+ import os
4
+ import subprocess
5
+ import urllib.request
6
+ import zipfile
7
+
8
+ ROOT = os.path.dirname(os.path.abspath(__file__))
9
+ BOP = os.path.join(ROOT, "bop")
10
+ CKPT_URL = "https://github.com/microsoft/Bringing-Old-Photos-Back-to-Life/releases/download/v1.0/global_checkpoints.zip"
11
+
12
+
13
+ def ensure_models():
14
+ if not os.path.isdir(BOP):
15
+ subprocess.run(["git", "clone", "--depth", "1",
16
+ "https://github.com/microsoft/Bringing-Old-Photos-Back-to-Life.git", BOP], check=True)
17
+ det = os.path.join(BOP, "Global", "detection_models")
18
+ if not os.path.isdir(os.path.join(det, "sync_batchnorm")):
19
+ sb = os.path.join(det, "Synchronized-BatchNorm-PyTorch")
20
+ subprocess.run(["git", "clone", "--depth", "1",
21
+ "https://github.com/vacancy/Synchronized-BatchNorm-PyTorch", sb], check=True)
22
+ os.rename(os.path.join(sb, "sync_batchnorm"), os.path.join(det, "sync_batchnorm"))
23
+ ck = os.path.join(BOP, "Global", "checkpoints")
24
+ if not os.path.isdir(ck):
25
+ z = os.path.join(BOP, "Global", "checkpoints.zip")
26
+ urllib.request.urlretrieve(CKPT_URL, z)
27
+ with zipfile.ZipFile(z) as f:
28
+ f.extractall(os.path.join(BOP, "Global"))
29
+ os.remove(z)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ ensure_models()