picrest / fill.py
concisewebsesign's picture
Upload 12 files
3154e18 verified
Raw History Blame Contribute Delete
3.03 kB
"""Paint-to-fix: fill only the pixels the user painted (torn corners, stains) with LaMa
(big-lama, Apache-2.0). Unpainted pixels, faces included, are returned unchanged.
The glare brush lives in glare.py."""
import os
import urllib.request
import cv2
import numpy as np
import torch
ROOT = os.path.dirname(os.path.abspath(__file__))
LAMA_PATH = os.path.join(ROOT, "big-lama.pt")
LAMA_URL = "https://github.com/enesmsahin/simple-lama-inpainting/releases/download/v0.1.0/big-lama.pt"
MAX_SIDE = 1024 # LaMa works on a crop around the painted area, scaled to at most this size
_model = None
def ensure_lama():
if not os.path.exists(LAMA_PATH):
urllib.request.urlretrieve(LAMA_URL, LAMA_PATH + ".part")
os.rename(LAMA_PATH + ".part", LAMA_PATH)
def _lama():
global _model
if _model is None:
ensure_lama()
_model = torch.jit.load(LAMA_PATH, map_location="cpu").eval()
return _model
def _inpaint(rgb, mask):
"""rgb uint8 HxWx3, mask uint8 HxW (255 = fill). Pads to a multiple of 8 like LaMa expects."""
h, w = mask.shape
H, W = (h + 7) // 8 * 8, (w + 7) // 8 * 8
img = np.pad(rgb, ((0, H - h), (0, W - w), (0, 0)), mode="symmetric")
m = np.pad(mask, ((0, H - h), (0, W - w)), mode="symmetric")
t_img = torch.from_numpy(img).permute(2, 0, 1)[None].float() / 255
t_mask = (torch.from_numpy(m)[None, None] > 127).float()
with torch.inference_mode():
out = _lama()(t_img, t_mask)[0].permute(1, 2, 0).numpy()
return np.clip(out * 255, 0, 255).astype(np.uint8)[:h, :w]
def fill(bgr, mask):
"""bgr uint8 photo, mask uint8 same size (non-zero = painted). Returns the filled photo."""
mask = (mask > 0).astype(np.uint8) * 255
if not mask.any():
return bgr
mask = cv2.dilate(mask, np.ones((7, 7), np.uint8)) # cover the soft edge of glare/tears
H, W = mask.shape
ys, xs = np.nonzero(mask)
# crop around the painted area with generous context so LaMa sees what to continue
mh, mw = ys.max() - ys.min() + 1, xs.max() - xs.min() + 1
pad = int(max(mh, mw) * 0.75) + 32
y0, y1 = max(0, ys.min() - pad), min(H, ys.max() + pad + 1)
x0, x1 = max(0, xs.min() - pad), min(W, xs.max() + pad + 1)
crop = cv2.cvtColor(bgr[y0:y1, x0:x1], cv2.COLOR_BGR2RGB)
cm = mask[y0:y1, x0:x1]
k = min(1.0, MAX_SIDE / max(crop.shape[:2]))
if k < 1:
size = (int(crop.shape[1] * k), int(crop.shape[0] * k))
filled = _inpaint(cv2.resize(crop, size, interpolation=cv2.INTER_AREA),
cv2.resize(cm, size, interpolation=cv2.INTER_NEAREST))
filled = cv2.resize(filled, (crop.shape[1], crop.shape[0]), interpolation=cv2.INTER_CUBIC)
else:
filled = _inpaint(crop, cm)
filled = cv2.cvtColor(filled, cv2.COLOR_RGB2BGR)
alpha = cv2.GaussianBlur(cm.astype(np.float32) / 255, (0, 0), 2)[..., None]
out = bgr.copy()
out[y0:y1, x0:x1] = np.clip(bgr[y0:y1, x0:x1] * (1 - alpha) + filled * alpha, 0, 255).astype(np.uint8)
return out