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

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +41 -3
  2. fill.py +95 -0
app.py CHANGED
@@ -2,6 +2,7 @@ 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
@@ -14,19 +15,41 @@ 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:
@@ -36,7 +59,22 @@ with gr.Blocks(title="PicRest") as demo:
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()
 
2
  import gradio as gr
3
  import numpy as np
4
 
5
+ from fill import deglare, ensure_lama, fill
6
  from setup_models import ensure_models
7
 
8
  try: # ZeroGPU Spaces refuse to start unless at least one function asks for the GPU
 
15
  pass
16
 
17
  ensure_models()
18
+ ensure_lama()
19
  from restore import restore # noqa: E402
20
 
21
+ BRUSH_COLOR = "#ff3b30"
22
+
23
 
24
  def run(image):
25
  if image is None:
26
  raise gr.Error("Upload a photo first.")
27
+ bgr = cv2.cvtColor(np.asarray(image.convert("RGB")), cv2.COLOR_RGB2BGR)
28
  out, info = restore(bgr)
29
  note = ("Found the print edges and straightened it." if info["print_found"]
30
  else "Couldn't find the print's edges, so the whole picture was used. "
31
  "Try a shot with a little background visible around the photo.")
32
  note += f" Repaired damage covering {info['damaged']:.1%} of the photo."
33
+ note += " To fix anything else, paint over it below and press Apply."
34
+ rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
35
+ return rgb, {"background": rgb, "layers": [], "composite": rgb}, note
36
+
37
+
38
+ def touch_up(editor, tool, strength):
39
+ if editor is None or editor.get("background") is None:
40
+ raise gr.Error("Restore a photo first.")
41
+ bg = np.asarray(editor["background"])[..., :3]
42
+ mask = np.zeros(bg.shape[:2], np.uint8)
43
+ for layer in editor.get("layers") or []:
44
+ layer = np.asarray(layer)
45
+ if layer.ndim == 3 and layer.shape[2] == 4:
46
+ mask |= (layer[..., 3] > 0).astype(np.uint8) * 255
47
+ if not mask.any():
48
+ raise gr.Error("Paint over the area you want fixed first.")
49
+ bgr = cv2.cvtColor(bg, cv2.COLOR_RGB2BGR)
50
+ out = fill(bgr, mask) if tool.startswith("Fill") else deglare(bgr, mask, strength)
51
+ rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
52
+ return rgb, {"background": rgb, "layers": [], "composite": rgb}
53
 
54
 
55
  with gr.Blocks(title="PicRest") as demo:
 
59
  inp = gr.Image(type="pil", label="Your photo of the photo")
60
  out = gr.Image(type="numpy", label="Restored", format="png")
61
  note = gr.Markdown()
62
+ restore_btn = gr.Button("Restore", variant="primary")
63
  gr.Examples(["example_couple.jpg", "example_portrait.jpg"], inp)
64
 
65
+ gr.Markdown("## Touch up\nPaint over a torn corner, missing piece, stain or glare, choose a tool, "
66
+ "then press Apply. Only the painted pixels change.")
67
+ editor = gr.ImageEditor(type="numpy", label="Paint the area to fix", sources=(), transforms=(),
68
+ brush=gr.Brush(colors=[BRUSH_COLOR], color_mode="fixed", default_size=30),
69
+ eraser=gr.Eraser(default_size=30), layers=False)
70
+ with gr.Row():
71
+ tool = gr.Radio(["Fill missing or torn area", "Reduce glare"], value="Fill missing or torn area",
72
+ label="Tool")
73
+ strength = gr.Slider(0.5, 2.5, value=1.0, step=0.1, label="Glare strength",
74
+ info="Avoid painting glare over faces; it can shift skin tones.")
75
+ apply_btn = gr.Button("Apply", variant="primary")
76
+
77
+ restore_btn.click(run, inp, [out, editor, note], api_name="restore")
78
+ apply_btn.click(touch_up, [editor, tool, strength], [out, editor], api_name="touch_up")
79
+
80
  demo.queue(max_size=8).launch()
fill.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paint-to-fix: fill only the pixels the user painted (glare, torn corners, stains) with LaMa
2
+ (big-lama, Apache-2.0). Unpainted pixels, faces included, are returned unchanged."""
3
+ import os
4
+ import urllib.request
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import torch
9
+
10
+ ROOT = os.path.dirname(os.path.abspath(__file__))
11
+ LAMA_PATH = os.path.join(ROOT, "big-lama.pt")
12
+ LAMA_URL = "https://github.com/enesmsahin/simple-lama-inpainting/releases/download/v0.1.0/big-lama.pt"
13
+ MAX_SIDE = 1024 # LaMa works on a crop around the painted area, scaled to at most this size
14
+
15
+ _model = None
16
+
17
+
18
+ def ensure_lama():
19
+ if not os.path.exists(LAMA_PATH):
20
+ urllib.request.urlretrieve(LAMA_URL, LAMA_PATH + ".part")
21
+ os.rename(LAMA_PATH + ".part", LAMA_PATH)
22
+
23
+
24
+ def _lama():
25
+ global _model
26
+ if _model is None:
27
+ ensure_lama()
28
+ _model = torch.jit.load(LAMA_PATH, map_location="cpu").eval()
29
+ return _model
30
+
31
+
32
+ def _inpaint(rgb, mask):
33
+ """rgb uint8 HxWx3, mask uint8 HxW (255 = fill). Pads to a multiple of 8 like LaMa expects."""
34
+ h, w = mask.shape
35
+ H, W = (h + 7) // 8 * 8, (w + 7) // 8 * 8
36
+ img = np.pad(rgb, ((0, H - h), (0, W - w), (0, 0)), mode="symmetric")
37
+ m = np.pad(mask, ((0, H - h), (0, W - w)), mode="symmetric")
38
+ t_img = torch.from_numpy(img).permute(2, 0, 1)[None].float() / 255
39
+ t_mask = (torch.from_numpy(m)[None, None] > 127).float()
40
+ with torch.inference_mode():
41
+ out = _lama()(t_img, t_mask)[0].permute(1, 2, 0).numpy()
42
+ return np.clip(out * 255, 0, 255).astype(np.uint8)[:h, :w]
43
+
44
+
45
+ def fill(bgr, mask):
46
+ """bgr uint8 photo, mask uint8 same size (non-zero = painted). Returns the filled photo."""
47
+ mask = (mask > 0).astype(np.uint8) * 255
48
+ if not mask.any():
49
+ return bgr
50
+ mask = cv2.dilate(mask, np.ones((7, 7), np.uint8)) # cover the soft edge of glare/tears
51
+ H, W = mask.shape
52
+ ys, xs = np.nonzero(mask)
53
+ # crop around the painted area with generous context so LaMa sees what to continue
54
+ mh, mw = ys.max() - ys.min() + 1, xs.max() - xs.min() + 1
55
+ pad = int(max(mh, mw) * 0.75) + 32
56
+ y0, y1 = max(0, ys.min() - pad), min(H, ys.max() + pad + 1)
57
+ x0, x1 = max(0, xs.min() - pad), min(W, xs.max() + pad + 1)
58
+ crop = cv2.cvtColor(bgr[y0:y1, x0:x1], cv2.COLOR_BGR2RGB)
59
+ cm = mask[y0:y1, x0:x1]
60
+ k = min(1.0, MAX_SIDE / max(crop.shape[:2]))
61
+ if k < 1:
62
+ size = (int(crop.shape[1] * k), int(crop.shape[0] * k))
63
+ filled = _inpaint(cv2.resize(crop, size, interpolation=cv2.INTER_AREA),
64
+ cv2.resize(cm, size, interpolation=cv2.INTER_NEAREST))
65
+ filled = cv2.resize(filled, (crop.shape[1], crop.shape[0]), interpolation=cv2.INTER_CUBIC)
66
+ else:
67
+ filled = _inpaint(crop, cm)
68
+ filled = cv2.cvtColor(filled, cv2.COLOR_RGB2BGR)
69
+ alpha = cv2.GaussianBlur(cm.astype(np.float32) / 255, (0, 0), 2)[..., None]
70
+ out = bgr.copy()
71
+ out[y0:y1, x0:x1] = np.clip(bgr[y0:y1, x0:x1] * (1 - alpha) + filled * alpha, 0, 255).astype(np.uint8)
72
+ return out
73
+
74
+
75
+ def deglare(bgr, mask, strength=1.0):
76
+ """Glare is a soft white veil over the photo: observed = true * t + 255 * (1 - t).
77
+ We estimate the veil from how much the *darkest* pixels inside the painted area are lifted
78
+ compared with the unpainted surroundings (a bright face still has dark eyes and hair, so it
79
+ is not mistaken for glare), then invert that model. No new content is invented."""
80
+ mask = (mask > 0).astype(np.float32)
81
+ if not mask.any():
82
+ return bgr
83
+ img = bgr.astype(np.float32)
84
+ H, W = mask.shape
85
+ k = max(7, int(max(H, W) / 30) | 1)
86
+ sigma = max(H, W) / 20
87
+ dark = cv2.erode(img.min(axis=2), np.ones((k, k), np.uint8))
88
+ dark = cv2.GaussianBlur(dark, (0, 0), k)
89
+ outside = 1 - np.clip(cv2.dilate(mask, np.ones((15, 15), np.uint8)), 0, 1)
90
+ expected = cv2.GaussianBlur(dark * outside, (0, 0), sigma) / (cv2.GaussianBlur(outside, (0, 0), sigma) + 1e-4)
91
+ soft = cv2.GaussianBlur(mask, (0, 0), k / 2)
92
+ veil = np.clip(dark - expected, 0, None) * soft * strength
93
+ t = np.clip(1 - veil / 255, 0.4, 1)[..., None]
94
+ out = (img - veil[..., None]) / t
95
+ return np.clip(out, 0, 255).astype(np.uint8)