picrest / prep.py
concisewebsesign's picture
Upload 12 files
3154e18 verified
Raw History Blame Contribute Delete
4.17 kB
"""Step 1 of PicRest: turn a phone shot of a print into a flat, cropped scan.
Non-generative: only geometry (crop/straighten) and gentle global tone fixes.
"""
import cv2
import numpy as np
def _order(pts):
s, d = pts.sum(1), np.diff(pts, axis=1).ravel()
return np.float32([pts[s.argmin()], pts[d.argmin()], pts[s.argmax()], pts[d.argmax()]])
def find_print(img):
"""Return the 4 corners of the photo print, or None if not confidently found."""
h, w = img.shape[:2]
k = 800 / max(h, w)
small = cv2.resize(img, None, fx=k, fy=k, interpolation=cv2.INTER_AREA)
gray = cv2.GaussianBlur(cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), (5, 5), 0)
best = None
for lo, hi in ((30, 90), (50, 150), (75, 200)):
edges = cv2.dilate(cv2.Canny(gray, lo, hi), np.ones((3, 3), np.uint8))
cnts, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
area = cv2.contourArea(c)
if area < 0.2 * small.shape[0] * small.shape[1] or area > 0.98 * small.shape[0] * small.shape[1]:
continue
approx = cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), True)
if len(approx) == 4 and cv2.isContourConvex(approx):
if best is None or area > best[0]:
best = (area, approx.reshape(4, 2) / k)
break
return None if best is None else _order(best[1].astype(np.float32))
def flatten(img, quad):
tl, tr, br, bl = quad
W = int(max(np.linalg.norm(tr - tl), np.linalg.norm(br - bl)))
H = int(max(np.linalg.norm(bl - tl), np.linalg.norm(br - tr)))
M = cv2.getPerspectiveTransform(quad, np.float32([[0, 0], [W, 0], [W, H], [0, H]]))
return cv2.warpPerspective(img, M, (W, H), flags=cv2.INTER_CUBIC)
def trim_border(img):
"""Drop a plain light border (white print margin) around the picture."""
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 5).astype(np.float32)
h, w = gray.shape
m = int(0.15 * min(h, w))
def edge(lines):
# a border line is bright and smooth (lighting may still vary slowly along it).
# The outermost few lines can still hold table pixels, so the border may start a bit in.
seen = False
for i, line in enumerate(lines[:m]):
core = line[int(.1 * len(line)):int(.9 * len(line))]
is_border = core.mean() > 120 and np.abs(np.diff(core)).mean() < 2.5
if is_border:
seen = True
elif seen or i >= 10:
return i if seen else 0
return 0
t, b = edge(gray), edge(gray[::-1])
l, r = edge(gray.T), edge(gray.T[::-1])
if not (t + b + l + r):
return img
pad = 3
return img[t + pad:h - b - pad, l + pad:w - r - pad]
def even_lighting(img, strength=0.7):
"""Remove soft glare / uneven light by flattening very low-frequency brightness."""
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB).astype(np.float32)
L = lab[..., 0]
sigma = max(img.shape[:2]) / 6
illum = cv2.GaussianBlur(L, (0, 0), sigma)
corrected = L / np.maximum(illum, 1) * illum.mean()
lab[..., 0] = np.clip((1 - strength) * L + strength * corrected, 0, 255)
return cv2.cvtColor(lab.astype(np.uint8), cv2.COLOR_LAB2BGR)
def prepare(img, max_side=1600, light=True):
"""light=False skips evening out the light, for photos that are combined first (glare.fuse)."""
quad = find_print(img)
found = quad is not None
if found:
img = trim_border(flatten(img, quad))
if light:
img = even_lighting(img)
k = max_side / max(img.shape[:2])
if k < 1:
img = cv2.resize(img, None, fx=k, fy=k, interpolation=cv2.INTER_AREA)
return img, found
if __name__ == "__main__":
import sys, os
src, dst = sys.argv[1], sys.argv[2]
os.makedirs(dst, exist_ok=True)
for f in sorted(os.listdir(src)):
out, found = prepare(cv2.imread(os.path.join(src, f)))
print(f, "print found" if found else "no print edge found", out.shape)
cv2.imwrite(os.path.join(dst, os.path.splitext(f)[0] + ".png"), out)