"""Hand-listed leftovers: in each rectangle, inpaint whatever is darker than the surface around it (a stray print fragment).
usage: patch.py dir '{"85":[[x0,x1,y0,y1],...],...}'  — in place"""
import cv2, numpy as np, json, sys
d, J = sys.argv[1], json.loads(sys.argv[2])
for k, rects in J.items():
    fr = cv2.imread(f'{d}/f{int(k):03d}.png'); g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY).astype(np.float32); fg = np.zeros(g.shape, np.uint8)
    for x0, x1, y0, y1 in rects:
        box = g[y0:y1, x0:x1]; bg = cv2.GaussianBlur(cv2.dilate(box, np.ones((11, 11), np.uint8)), (0, 0), 7)
        fg[y0:y1, x0:x1] = (box < bg - 10).astype(np.uint8)
    cv2.imwrite(f'{d}/f{int(k):03d}.png', cv2.inpaint(fr, cv2.dilate(fg, np.ones((5, 5), np.uint8)), 5, cv2.INPAINT_TELEA))
