加入照片转pdf功能支持
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
"""PDF 产出的通用质量检验(渲染真实页面后评估)。
|
||||
|
||||
检验对象是最终交付的 PDF,不是中间图:把每页按固定 DPI 渲染成位图,
|
||||
在渲染结果上做统计判定,所见即交付物。
|
||||
|
||||
检验项:
|
||||
1. 页数与源图数一致
|
||||
2. 有效内容分辨率(页面渲染后纸面区域的像素尺寸)
|
||||
3. 纸张比例失真(纸面外接框的宽高比,对照页面书写比例)
|
||||
4. 纸面外背景残留(边带亮度显著低于纸面)
|
||||
5. 内容贴边被切(页边存在成片文字级暗像素)
|
||||
|
||||
判据全部基于该页自身像素分布自适应(Otsu / 分位数),不含针对特定文档的常量。
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/check.py 结果.pdf [--expect-pages 2] [--dpi 100]
|
||||
python3 doc_deskew/check.py 结果.pdf --render # 导出渲染图供目视
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def render(pdf, dpi=100, outdir='.tmp/pdfcheck'):
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
for f in os.listdir(outdir):
|
||||
if f.startswith('page'):
|
||||
os.remove(os.path.join(outdir, f))
|
||||
base = os.path.join(outdir, 'page')
|
||||
if shutil.which('pdftoppm'):
|
||||
subprocess.run(['pdftoppm', '-r', str(dpi), '-png', pdf, base], check=True)
|
||||
else: # 退路:pypdfium2
|
||||
import pypdfium2 as pdfium
|
||||
doc = pdfium.PdfDocument(pdf)
|
||||
scale = dpi / 72
|
||||
for i in range(len(doc)):
|
||||
doc[i].render(scale=scale).to_pil().save('%s-%d.png' % (base, i + 1))
|
||||
files = sorted(f for f in os.listdir(outdir) if f.startswith('page') and f.endswith('.png'))
|
||||
return [os.path.join(outdir, f) for f in files]
|
||||
|
||||
|
||||
def otsu(vals):
|
||||
v = np.asarray(vals, dtype=np.float64).ravel()
|
||||
if v.size == 0:
|
||||
return 128.0
|
||||
hist, edges = np.histogram(v, bins=64)
|
||||
centers = (edges[:-1] + edges[1:]) / 2.0
|
||||
total = hist.sum()
|
||||
w0 = np.cumsum(hist)
|
||||
w1 = total - w0
|
||||
m0 = np.cumsum(hist * centers)
|
||||
mt = m0[-1]
|
||||
with np.errstate(divide='ignore', invalid='ignore'):
|
||||
score = (mt * w0 / total - m0) ** 2 / (w0 * w1 / total ** 2)
|
||||
score = np.nan_to_num(score)
|
||||
return float(centers[int(np.argmax(score))])
|
||||
|
||||
|
||||
def analyse(img):
|
||||
g = np.asarray(img.convert('L')).astype(np.float32)
|
||||
h, w = g.shape
|
||||
res = {'w': w, 'h': h, 'ratio': w / h}
|
||||
|
||||
# 纸面亮度:取全图高分位(纸面是主体亮区)
|
||||
res['paper'] = float(np.percentile(g, 80))
|
||||
# 背景亮度:低分位
|
||||
res['back'] = float(np.percentile(g, 2))
|
||||
# 内容区阈值
|
||||
res['ink'] = min(otsu(g), res['paper'] * 0.8)
|
||||
|
||||
# 纸面内容框:A4 页面上纸面之外是纯白留白,故"非纯白"区域即实际纸面
|
||||
# 用相对亮度判定,避免把扫描白纸的轻微灰底误判成内容
|
||||
flat = float(np.percentile(g, 99.5))
|
||||
nonwhite = g < (flat - 8)
|
||||
row_frac = nonwhite.mean(axis=1)
|
||||
col_frac = nonwhite.mean(axis=0)
|
||||
# 取占比超过 5% 的连续范围作为纸面主体
|
||||
rows = np.where(row_frac > 0.05)[0]
|
||||
cols = np.where(col_frac > 0.05)[0]
|
||||
if rows.size > 4 and cols.size > 4:
|
||||
res['paper_box'] = (int(cols[0]), int(rows[0]), int(cols[-1]), int(rows[-1]))
|
||||
pw = cols[-1] - cols[0] + 1
|
||||
ph = rows[-1] - rows[0] + 1
|
||||
res['paper_ratio'] = pw / ph
|
||||
res['paper_px'] = (int(pw), int(ph))
|
||||
else:
|
||||
res['paper_box'] = None
|
||||
res['paper_ratio'] = res['ratio']
|
||||
res['paper_px'] = (w, h)
|
||||
|
||||
# 边缘背景残留:四周窄带的平均亮度明显低于纸面亮度
|
||||
# 边带宽度按比例取,过窄会漏判
|
||||
b = max(4, int(min(w, h) * 0.012))
|
||||
border = {
|
||||
'top': float(g[:b, :].mean()), 'bottom': float(g[-b:, :].mean()),
|
||||
'left': float(g[:, :b].mean()), 'right': float(g[:, -b:].mean()),
|
||||
}
|
||||
res['border'] = border
|
||||
res['border_bad'] = [k for k, v in border.items() if v < res['paper'] * 0.80]
|
||||
# 另一路判据:边带内是否存在"整行整列偏暗"的条带(纸外背景)
|
||||
edge_dark = {}
|
||||
for k, band in (('top', g[:b, :]), ('bottom', g[-b:, :]),
|
||||
('left', g[:, :b]), ('right', g[:, -b:])):
|
||||
edge_dark[k] = float((band < res['paper'] * 0.6).mean())
|
||||
res['edge_dark'] = edge_dark
|
||||
|
||||
# 内容贴边:最外窄带内成片文字级暗像素 <=> 内容被切
|
||||
m = max(2, int(min(w, h) * 0.003))
|
||||
cut = []
|
||||
for k, band in (('top', g[:m, :]), ('bottom', g[-m:, :]),
|
||||
('left', g[:, :m]), ('right', g[:, -m:])):
|
||||
frac = float((band < res['ink']).mean())
|
||||
if frac > 0.05:
|
||||
cut.append((k, frac))
|
||||
res['cut'] = cut
|
||||
return res
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('pdf')
|
||||
ap.add_argument('--expect-pages', type=int, default=None)
|
||||
ap.add_argument('--dpi', type=int, default=100)
|
||||
ap.add_argument('--min-short', type=int, default=800)
|
||||
ap.add_argument('--ratio-tol', type=float, default=0.08)
|
||||
ap.add_argument('--render', action='store_true')
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.exists(args.pdf):
|
||||
raise SystemExit('找不到 PDF: %s' % args.pdf)
|
||||
|
||||
files = render(args.pdf, args.dpi)
|
||||
print('PDF: %s' % args.pdf)
|
||||
print('文件大小: %.0f KB' % (os.path.getsize(args.pdf) / 1024))
|
||||
print('页数: %d' % len(files))
|
||||
|
||||
ok = True
|
||||
if args.expect_pages is not None:
|
||||
good = len(files) == args.expect_pages
|
||||
ok &= good
|
||||
print(' [%s] 页数与源图一致(期望 %d,实际 %d)'
|
||||
% ('OK' if good else 'XX', args.expect_pages, len(files)))
|
||||
|
||||
for i, f in enumerate(files, 1):
|
||||
img = Image.open(f)
|
||||
r = analyse(img)
|
||||
print('\n第 %d 页 渲染 %dx%d px @%ddpi' % (i, r['w'], r['h'], args.dpi))
|
||||
|
||||
# 纸张实际像素尺寸(按渲染图里纸面外接框估算,换算回原分辨率)
|
||||
if r['paper_box']:
|
||||
x0, y0, x1, y1 = r['paper_box']
|
||||
scale = 1.0 # 渲染已是实际像素
|
||||
short = min(x1 - x0, y1 - y0)
|
||||
good = short >= args.min_short * args.dpi / 150.0
|
||||
ok &= good
|
||||
print(' [%s] 纸面短边 %d px(下限 %d)'
|
||||
% ('OK' if good else 'XX', short,
|
||||
int(args.min_short * args.dpi / 150.0)))
|
||||
|
||||
# 纸张比例本身不是硬性标准:非 A4 材料(Letter / 16K / 票据)
|
||||
# 塞进 A4 页面时必然有留白,纸张比例 != 页面比例是正常的。
|
||||
# 这里只做"提示",判错交给内容贴边与背景残留两项。
|
||||
dev = abs(r['paper_ratio'] - r['ratio']) / r['ratio'] * 100
|
||||
note = '' if dev <= args.ratio_tol else '(留白 %.1f%%,非 A4 纸张属正常)' % dev
|
||||
print(' [--] 纸张比例 %.3f(页面 %.3f)%s'
|
||||
% (r['paper_ratio'], r['ratio'], note))
|
||||
else:
|
||||
print(' [XX] 未能识别纸面区域')
|
||||
ok = False
|
||||
|
||||
bad_dark = [k for k, v in r.get('edge_dark', {}).items() if v > 0.35]
|
||||
good = (not r['border_bad']) and (not bad_dark)
|
||||
ok &= good
|
||||
detail = ', '.join('%s=%.0f' % (k, v) for k, v in r['border'].items())
|
||||
print(' [%s] 边缘背景残留 %s(纸面 %.0f / 背景 %.0f)'
|
||||
% ('OK' if good else 'XX',
|
||||
'无' if good else '、'.join(r['border_bad']), r['paper'], r['back']))
|
||||
if not good:
|
||||
print(' 边带亮度: %s' % detail)
|
||||
if bad_dark:
|
||||
print(' 偏高暗占比: %s'
|
||||
% '、'.join('%s %.0f%%' % (k, r['edge_dark'][k] * 100) for k in bad_dark))
|
||||
|
||||
good = not r['cut']
|
||||
ok &= good
|
||||
print(' [%s] 内容贴边 %s'
|
||||
% ('OK' if good else 'XX',
|
||||
'、'.join('%s %.1f%%' % (k, v * 100) for k, v in r['cut']) if r['cut'] else '无'))
|
||||
|
||||
print('\n总判定:%s' % ('全部通过' if ok else '存在不达标项'))
|
||||
if args.render:
|
||||
print('渲染图: .tmp/pdfcheck/')
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,45 @@
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import sys
|
||||
|
||||
FONT = '/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc'
|
||||
|
||||
# 网格配色:100px 红线(主线,带坐标刻度)+ 50px 蓝线(辅助),两者同宽,
|
||||
# 只靠颜色分主次;线太细时缩略图上看不见,所以不靠粗细区分。
|
||||
COLOR_MAJOR = (255, 0, 0, 110)
|
||||
COLOR_MINOR = (0, 96, 255, 70)
|
||||
LINE_WIDTH = 2
|
||||
|
||||
|
||||
def draw_grid_on(im, step=50, major=100):
|
||||
"""在原图上叠加坐标网格,返回同一个 Image 对象(不落盘)。"""
|
||||
W, H = im.size
|
||||
d = ImageDraw.Draw(im, 'RGBA')
|
||||
try:
|
||||
f = ImageFont.truetype(FONT, 18)
|
||||
except Exception:
|
||||
f = ImageFont.load_default()
|
||||
for x in range(0, W, step):
|
||||
d.line([(x, 0), (x, H)],
|
||||
fill=COLOR_MAJOR if x % major == 0 else COLOR_MINOR,
|
||||
width=LINE_WIDTH)
|
||||
for y in range(0, H, step):
|
||||
d.line([(0, y), (W, y)],
|
||||
fill=COLOR_MAJOR if y % major == 0 else COLOR_MINOR,
|
||||
width=LINE_WIDTH)
|
||||
# 坐标数字:每 100px 在顶部和左侧标注
|
||||
for x in range(0, W, major):
|
||||
d.rectangle([x + 1, 1, x + 38, 21], fill=(255, 255, 255, 220))
|
||||
d.text((x + 3, 1), str(x), fill=(200, 0, 0), font=f)
|
||||
for y in range(0, H, major):
|
||||
d.rectangle([1, y + 1, 46, y + 21], fill=(255, 255, 255, 220))
|
||||
d.text((2, y + 1), str(y), fill=(0, 0, 200), font=f)
|
||||
return im
|
||||
|
||||
|
||||
def draw_grid(src, dst, step=50, major=100):
|
||||
im = draw_grid_on(Image.open(src).convert('RGB'), step, major)
|
||||
im.save(dst)
|
||||
print('written', dst, im.size)
|
||||
|
||||
if __name__ == '__main__':
|
||||
draw_grid(sys.argv[1], sys.argv[2])
|
||||
@@ -0,0 +1,81 @@
|
||||
"""纯 numpy 单应变换:等价于 cv2.warpPerspective,只依赖 Pillow + numpy。
|
||||
|
||||
用法:
|
||||
python homography.py in.jpg out.png --quad x1,y1 x2,y2 x3,y3 x4,y4
|
||||
四角顺序:左上、右上、右下、左下。不给 --quad 时按整幅图重采样。
|
||||
"""
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _solve_h(src, dst):
|
||||
A = []
|
||||
for (x, y), (u, v) in zip(src, dst):
|
||||
A.append([x, y, 1, 0, 0, 0, -u * x, -u * y, -u])
|
||||
A.append([0, 0, 0, x, y, 1, -v * x, -v * y, -v])
|
||||
_, _, vt = np.linalg.svd(np.asarray(A, dtype=np.float64))
|
||||
return vt[-1].reshape(3, 3)
|
||||
|
||||
|
||||
def warp_perspective(img, quad, out_size=None, fill=(255, 255, 255)):
|
||||
arr = np.asarray(img.convert('RGB') if isinstance(img, Image.Image) else img)
|
||||
quad = np.asarray(quad, dtype=np.float64)
|
||||
tl, tr, br, bl = quad
|
||||
if out_size is None:
|
||||
w = int(round(max(np.linalg.norm(tr - tl), np.linalg.norm(br - bl))))
|
||||
h = int(round(max(np.linalg.norm(bl - tl), np.linalg.norm(br - tr))))
|
||||
out_size = (w, h)
|
||||
out_w, out_h = out_size
|
||||
dst = np.array([[0, 0], [out_w - 1, 0], [out_w - 1, out_h - 1], [0, out_h - 1]],
|
||||
dtype=np.float64)
|
||||
Hinv = np.linalg.inv(_solve_h(quad, dst))
|
||||
xs, ys = np.meshgrid(np.arange(out_w), np.arange(out_h))
|
||||
dst_h = np.stack([xs.ravel(), ys.ravel(), np.ones(xs.size)]).astype(np.float64)
|
||||
src_h = Hinv @ dst_h
|
||||
sx = src_h[0] / src_h[2]
|
||||
sy = src_h[1] / src_h[2]
|
||||
h, w = arr.shape[:2]
|
||||
valid = (sx >= 0) & (sx <= w - 1) & (sy >= 0) & (sy <= h - 1)
|
||||
sx = np.clip(sx, 0, w - 1); sy = np.clip(sy, 0, h - 1)
|
||||
x0 = np.floor(sx).astype(np.int32); x1 = np.minimum(x0 + 1, w - 1)
|
||||
y0 = np.floor(sy).astype(np.int32); y1 = np.minimum(y0 + 1, h - 1)
|
||||
fx = (sx - x0)[:, None]; fy = (sy - y0)[:, None]
|
||||
a = arr[y0, x0].astype(np.float64); b = arr[y0, x1].astype(np.float64)
|
||||
c = arr[y1, x0].astype(np.float64); d = arr[y1, x1].astype(np.float64)
|
||||
out = (a * (1 - fx) * (1 - fy) + b * fx * (1 - fy) +
|
||||
c * (1 - fx) * fy + d * fx * fy)
|
||||
out[~valid] = fill
|
||||
out = np.clip(out, 0, 255).astype(np.uint8).reshape(out_h, out_w, -1)
|
||||
return Image.fromarray(out)
|
||||
|
||||
|
||||
def trim(img, px=3):
|
||||
w, h = img.size
|
||||
px = max(0, min(px, (min(w, h) - 1) // 2))
|
||||
return img.crop((px, px, w - px, h - px))
|
||||
|
||||
|
||||
def brighten(img, target=245, pct=97):
|
||||
arr = np.asarray(img.convert('RGB')).astype(np.float32)
|
||||
hi = np.percentile(arr, pct)
|
||||
if hi > 1:
|
||||
arr = np.clip(arr * (target / hi), 0, 255)
|
||||
return Image.fromarray(arr.astype(np.uint8))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('src'); ap.add_argument('dst')
|
||||
ap.add_argument('--quad', nargs=4, metavar='x,y')
|
||||
ap.add_argument('--trim', type=int, default=3)
|
||||
a = ap.parse_args()
|
||||
im = Image.open(a.src).convert('RGB')
|
||||
if a.quad:
|
||||
quad = [tuple(float(v) for v in p.split(',')) for p in a.quad]
|
||||
else:
|
||||
w, h = im.size
|
||||
quad = [(0, 0), (w - 1, 0), (w - 1, h - 1), (0, h - 1)]
|
||||
out = trim(brighten(warp_perspective(im, quad)), a.trim)
|
||||
out.save(a.dst)
|
||||
print('written %s %dx%d' % (a.dst, out.size[0], out.size[1]))
|
||||
@@ -0,0 +1,25 @@
|
||||
"""多张图等比缩放居中,合并为一个 PDF。默认 A4 纵向 @150dpi。"""
|
||||
import sys
|
||||
from PIL import Image
|
||||
|
||||
A4_W, A4_H = 1240, 1754
|
||||
MARGIN = 40
|
||||
DPI = 150
|
||||
|
||||
|
||||
def fit_page(path):
|
||||
im = Image.open(path).convert('RGB')
|
||||
bw, bh = A4_W - MARGIN * 2, A4_H - MARGIN * 2
|
||||
s = min(bw / im.width, bh / im.height)
|
||||
nw, nh = max(1, int(round(im.width * s))), max(1, int(round(im.height * s)))
|
||||
im = im.resize((nw, nh), Image.LANCZOS)
|
||||
page = Image.new('RGB', (A4_W, A4_H), 'white')
|
||||
page.paste(im, ((A4_W - nw) // 2, (A4_H - nh) // 2))
|
||||
return page
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
*srcs, out = sys.argv[1:]
|
||||
pages = [fit_page(p) for p in srcs]
|
||||
pages[0].save(out, 'PDF', resolution=DPI, save_all=True, append_images=pages[1:])
|
||||
print('written %s (%d pages)' % (out, len(pages)))
|
||||
@@ -0,0 +1,416 @@
|
||||
#!/usr/bin/env python3
|
||||
"""文档照片 -> 校正 PDF:全流程串起来的一站式脚本。
|
||||
|
||||
把原来手工分步的活(网格图 -> 读角点 -> 落盘 -> 回画确认 -> 出 PDF -> 检验)
|
||||
压成几条命令,且**产物都落在 out/ 里按序号命名**:
|
||||
|
||||
out/1-网格-<原图名>.png 每页的坐标网格图(读角点用)
|
||||
out/1-角标-<原图名>.png 每页角点回画图(原图 + 网格 + 四角标注,核查是否贴纸边)
|
||||
out/1-成品-<原图名>.png 每页矫正后的页面图
|
||||
out/corners.json 角点坐标(落盘,跨会话可用)
|
||||
out/<名字>.pdf 最终 PDF
|
||||
|
||||
角点约定(顺序固定,别写反):
|
||||
左上 ; 右上 ; 右下 ; 左下 —— 屏幕坐标,原点在图片左上角,单位像素
|
||||
|
||||
子命令:
|
||||
prepare 出网格图 + 生成 corners.json 模板(坐标留空待填)
|
||||
set 把某一页的四角坐标写进 corners.json(可反复调用)
|
||||
build 回画角标图 + 校验 + 出 PDF + 出成品图 + PDF 检验,一次跑完
|
||||
all prepare + build 合体(角点已存在则直接 build)
|
||||
check 复检已有 PDF(只渲染检验,不重新出件)
|
||||
|
||||
典型用法(脚本用绝对路径调用:cwd 是会话任务目录,不是本目录):
|
||||
# 1) 出网格图
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py prepare 图1.jpg 图2.jpg
|
||||
# 2) 看 out/1-网格-图1.png,把坐标写进文件
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py set "图1.jpg" --quad "150,360;1020,355;1050,1690;90,1660"
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py set "图2.jpg" --quad "120,345;1010,345;1010,1710;120,1710"
|
||||
# 3) 一路出 PDF
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py build --out 合同_校正.pdf
|
||||
|
||||
# 想一步到位(角点已落盘):
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py all 图1.jpg 图2.jpg --out 合同_校正.pdf
|
||||
|
||||
# 列出 / 检查已落盘角点
|
||||
python3 /workspace/skills/document-photo-to-pdf/doc_deskew/pipeline.py show
|
||||
|
||||
退出码:0 全部通过;2 角点校验未通过(已出件但需人工判断);3 PDF 检验未通过。
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
# 提示里回显的命令:cwd 是会话任务目录,必须用脚本绝对路径,写相对的跑不起来
|
||||
SELF = 'python3 ' + os.path.join(HERE, 'pipeline.py')
|
||||
|
||||
OUT_DIR = 'out'
|
||||
CORNERS = os.path.join(OUT_DIR, 'corners.json')
|
||||
LABELS = ('左上', '右上', '右下', '左下')
|
||||
|
||||
IMG_EXT = ('.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 基础工具
|
||||
|
||||
def natural_key(name):
|
||||
return [int(t) if t.isdigit() else t.lower()
|
||||
for t in re.split(r'(\d+)', os.path.basename(name))]
|
||||
|
||||
|
||||
def quad_to_str(quad):
|
||||
return ';'.join('%g,%g' % (p[0], p[1]) for p in quad)
|
||||
|
||||
|
||||
def load_corners(path=CORNERS):
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, encoding='utf-8') as f:
|
||||
raw = json.load(f)
|
||||
out = {}
|
||||
for name, v in raw.items():
|
||||
if isinstance(v, dict):
|
||||
v = v.get('quad') or v.get('corners')
|
||||
if not v:
|
||||
continue
|
||||
out[name] = [(float(p[0]), float(p[1])) for p in v]
|
||||
return out
|
||||
|
||||
|
||||
def save_corners(data, path=CORNERS):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(path)) or '.', exist_ok=True)
|
||||
tmp = path + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
json.dump({k: [[int(c) if float(c).is_integer() else c for c in p]
|
||||
for p in v] for k, v in data.items()},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
f.write('\n')
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def parse_quad(text):
|
||||
quad = []
|
||||
for pt in text.replace(';', ';').split(';'):
|
||||
pt = pt.strip()
|
||||
if not pt:
|
||||
continue
|
||||
xy = pt.replace(' ', '').split(',')
|
||||
if len(xy) != 2:
|
||||
raise SystemExit('角点格式不对:%r(应为 x,y)' % pt)
|
||||
try:
|
||||
quad.append((float(xy[0]), float(xy[1])))
|
||||
except ValueError:
|
||||
raise SystemExit('角点不是数字:%r' % pt)
|
||||
if len(quad) != 4:
|
||||
raise SystemExit('角点必须 4 个(左上;右上;右下;左下),实际 %d 个' % len(quad))
|
||||
return quad
|
||||
|
||||
|
||||
def collect_images(args):
|
||||
"""参数里的图片 + 当前目录全部图片(去重、按自然序)。"""
|
||||
names = list(args)
|
||||
if not names:
|
||||
names = [f for f in os.listdir('.')
|
||||
if f.lower().endswith(IMG_EXT) and os.path.isfile(f)]
|
||||
seen, out = set(), []
|
||||
for n in names:
|
||||
if n not in seen:
|
||||
seen.add(n)
|
||||
out.append(n)
|
||||
if not out:
|
||||
raise SystemExit('没有找到图片:可在命令后面直接列文件名')
|
||||
missing = [n for n in out if not os.path.exists(n)]
|
||||
if missing:
|
||||
raise SystemExit('图片不存在:%s' % ', '.join(missing))
|
||||
return sorted(out, key=natural_key)
|
||||
|
||||
|
||||
def page_tag(i):
|
||||
return '%d' % i
|
||||
|
||||
|
||||
def out_path(prefix, i, name, ext='.png'):
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
return os.path.join(OUT_DIR, '%s-%s-%s%s' % (page_tag(i), prefix, base, ext))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- prepare
|
||||
|
||||
def cmd_prepare(images):
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
from grid import draw_grid
|
||||
data = load_corners()
|
||||
for i, name in enumerate(images, 1):
|
||||
dst = out_path('网格', i, name)
|
||||
draw_grid(name, dst)
|
||||
data.setdefault(name, None)
|
||||
save_corners({k: v for k, v in data.items() if v})
|
||||
print('\n网格图已写入 %s/' % OUT_DIR)
|
||||
print('下一步:照着网格图读数,把角点写进 %s:' % CORNERS)
|
||||
for i, name in enumerate(images, 1):
|
||||
print(' %s set "%s" --quad "左上x,左上y;右上x,右上y;'
|
||||
'右下x,右下y;左下x,左下y"' % (SELF, name))
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- set / show
|
||||
|
||||
def cmd_set(args):
|
||||
"""一次只写一张图:参数是 图片 + 一个 --quad,不批配、不错位。"""
|
||||
if '|' in args.image or ':' in args.image:
|
||||
raise SystemExit('图片名里不要带 : 或 |:%s' % args.image)
|
||||
if not os.path.exists(args.image):
|
||||
raise SystemExit('图片不存在:%s' % args.image)
|
||||
if len(args.quad) != 1:
|
||||
raise SystemExit('set 只能给一个 --quad(实际 %d 个)。一张图一次。'
|
||||
% len(args.quad))
|
||||
|
||||
name = args.image
|
||||
quad_s = args.quad[0]
|
||||
|
||||
data = load_corners()
|
||||
old = data.get(name)
|
||||
data[name] = parse_quad(quad_s)
|
||||
save_corners(data)
|
||||
if old is not None:
|
||||
print('已更新 %-36s %s(原 %s)'
|
||||
% (name, quad_to_str(data[name]), quad_to_str(old)))
|
||||
else:
|
||||
print('已写入 %-36s %s' % (name, quad_to_str(data[name])))
|
||||
print('→ %s(已存:%s)'
|
||||
% (CORNERS, '、'.join(sorted(data, key=natural_key))))
|
||||
left = [n for n in data if not os.path.exists(n)]
|
||||
if left:
|
||||
print('[注意] 这些图在 corners.json 里但文件不存在:%s' % '、'.join(left))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_show():
|
||||
data = load_corners()
|
||||
if not data:
|
||||
print('%s 里还没有角点' % CORNERS)
|
||||
return 1
|
||||
for i, name in enumerate(sorted(data, key=natural_key), 1):
|
||||
print('%d. %-40s %s' % (i, name, quad_to_str(data[name])))
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 角标图
|
||||
|
||||
def draw_marks(name, pts, dst):
|
||||
"""把四角画回原图(底图叠加与网格图相同的网格),供人工核查。"""
|
||||
from preview_quad import draw_quad
|
||||
im = draw_quad(name, pts, with_grid=True)
|
||||
im.save(dst)
|
||||
return dst
|
||||
|
||||
|
||||
def make_zooms(name, marked_png, idx, zoom):
|
||||
"""从角标图上裁出四侧放大块,命名同其它核查图的序号规则。"""
|
||||
from PIL import Image
|
||||
from preview_quad import zoom_boxes
|
||||
im = Image.open(marked_png)
|
||||
boxes = zoom_boxes(im, [(0, 0), (im.width, 0), (im.width, im.height), (0, im.height)])
|
||||
keys = list(boxes) if zoom == 'all' else [zoom]
|
||||
base = os.path.join(OUT_DIR, '%d-角标放大-%s' % (idx, os.path.basename(name)))
|
||||
base = os.path.splitext(base)[0]
|
||||
for k in keys:
|
||||
box = tuple(int(v) for v in boxes[k])
|
||||
if box[2] <= box[0] or box[3] <= box[1]:
|
||||
continue
|
||||
crop = im.crop(box)
|
||||
# 细长条按方向切成两段,否则 585x5760 没法看
|
||||
segs = []
|
||||
if k in ('left', 'right') and crop.height > crop.width * 2.2:
|
||||
h = crop.height // 2
|
||||
segs = [('上', crop.crop((0, 0, crop.width, h))),
|
||||
('下', crop.crop((0, h, crop.width, crop.height)))]
|
||||
elif k in ('top', 'bottom') and crop.width > crop.height * 2.2:
|
||||
w = crop.width // 2
|
||||
segs = [('左', crop.crop((0, 0, w, crop.height))),
|
||||
('右', crop.crop((w, 0, crop.width, crop.height)))]
|
||||
else:
|
||||
segs = [('', crop)]
|
||||
for tag, c in segs:
|
||||
f = min(3.0, max(1.0, 700.0 / max(1, c.width)))
|
||||
if f > 1.0:
|
||||
c = c.resize((int(c.width * f), int(c.height * f)), Image.LANCZOS)
|
||||
z = '%s-%s%s.png' % (base, k, tag)
|
||||
c.save(z)
|
||||
print(' 放大块 %s (%dx%d)' % (z, c.width, c.height))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- build
|
||||
|
||||
def cmd_build(images, out_pdf, paper, dpi, force, zoom):
|
||||
data = load_corners()
|
||||
if images:
|
||||
names = images
|
||||
else:
|
||||
names = sorted(data, key=natural_key)
|
||||
if not names:
|
||||
raise SystemExit('还没有角点。先跑 prepare 出网格图,再用 set 落盘角点。')
|
||||
|
||||
lacking = [n for n in names if n not in data]
|
||||
if lacking:
|
||||
raise SystemExit('这些图还没有角点:%s\n先跑 %s set ...'
|
||||
% (', '.join(lacking), SELF))
|
||||
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
from verify_quad import check as verify_quad
|
||||
from run import build, PAPERS
|
||||
|
||||
ratio = None
|
||||
if paper:
|
||||
key = paper.strip().lower()
|
||||
ratio = PAPERS.get(key)
|
||||
if ratio is None:
|
||||
try:
|
||||
ratio = float(paper)
|
||||
except ValueError:
|
||||
raise SystemExit('未知纸张:%s(可选 %s 或数字比例)'
|
||||
% (paper, '/'.join(PAPERS)))
|
||||
|
||||
# 1. 角标图 + 校验
|
||||
print('=== 步骤 1/4:回画角点(核查用) ===')
|
||||
verdicts = []
|
||||
for i, name in enumerate(names, 1):
|
||||
dst = out_path('角标', i, name)
|
||||
draw_marks(name, data[name], dst)
|
||||
print('\n第 %d 页 %s → %s' % (i, name, dst))
|
||||
ok = verify_quad(name, data[name])
|
||||
verdicts.append(ok)
|
||||
if zoom:
|
||||
make_zooms(name, dst, i, zoom)
|
||||
print('\n>>> 请打开上面这些 角标 图,逐个角确认是否压在纸角上。\n')
|
||||
|
||||
bad_pages = [i for i, ok in enumerate(verdicts, 1) if not ok]
|
||||
if bad_pages:
|
||||
print('!! 角点校验未通过:第 %s 页(上面标 [XX] 的项)。'
|
||||
% '、'.join(map(str, bad_pages)))
|
||||
if not force:
|
||||
print('已停止,未出件。按上面的提示调整角点,再重跑 set + build。')
|
||||
return 2
|
||||
print('已按 --force 继续出件:结果需人工确认,不能当作校验通过交付。\n')
|
||||
|
||||
# 2. 出 PDF
|
||||
print('=== 步骤 2/4:透视矫正 + 合成 PDF ===')
|
||||
workdir = os.path.join(OUT_DIR, '_pages')
|
||||
specs = ['%s:%s' % (n, quad_to_str(data[n])) for n in names]
|
||||
pages = build(specs, out_pdf, workdir, ratio)
|
||||
|
||||
# 成品图按页序号重命名进 out/
|
||||
for i, (name, page) in enumerate(zip(names, pages), 1):
|
||||
dst = out_path('成品', i, name)
|
||||
os.replace(page, dst)
|
||||
print(' 成品图 %s' % dst)
|
||||
|
||||
# 3. PDF 检验
|
||||
print('\n=== 步骤 3/4:最终 PDF 检验 ===')
|
||||
rc = subprocess.run([sys.executable, os.path.join(HERE, 'check.py'), out_pdf,
|
||||
'--dpi', str(dpi), '--expect-pages', str(len(names))]).returncode
|
||||
|
||||
# 4. 汇总
|
||||
bad = bad_pages
|
||||
print('\n=== 步骤 4/4:汇总 ===')
|
||||
print('PDF :%s(%.0f KB,%d 页)' % (out_pdf, os.path.getsize(out_pdf) / 1024, len(names)))
|
||||
print('角点校验 :%s' % ('全部通过' if not bad else '第 %s 页未通过' % '、'.join(map(str, bad))))
|
||||
print('PDF 检验 :%s' % ('通过' if rc == 0 else '未通过'))
|
||||
print('核查材料 :')
|
||||
for i, name in enumerate(names, 1):
|
||||
print(' %s %s %s' % (out_path('网格', i, name), out_path('角标', i, name),
|
||||
out_path('成品', i, name)))
|
||||
if bad or rc != 0:
|
||||
print('注意:以上为原样结果,未做任何自动修正。')
|
||||
return 2 if bad else 3
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- check
|
||||
|
||||
def cmd_check(pdf, expect_pages, dpi):
|
||||
"""复检已有 PDF:只渲染检验,不重新校正、不改动文件。"""
|
||||
if not os.path.exists(pdf):
|
||||
raise SystemExit('找不到 PDF:%s' % pdf)
|
||||
cmd = [sys.executable, os.path.join(HERE, 'check.py'), pdf, '--dpi', str(dpi)]
|
||||
if expect_pages is not None:
|
||||
cmd += ['--expect-pages', str(expect_pages)]
|
||||
return subprocess.run(cmd).returncode
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='文档照片 -> 校正 PDF 全流程脚本',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__)
|
||||
sub = ap.add_subparsers(dest='cmd', required=True)
|
||||
|
||||
p = sub.add_parser('prepare', help='出网格图(out/1-网格-*.png)')
|
||||
p.add_argument('images', nargs='*', help='图片名,省略则取当前目录所有图片')
|
||||
|
||||
p = sub.add_parser('set', help='把一张图的角点写进 out/corners.json')
|
||||
p.add_argument('image', metavar='IMG', help='图片名(一次一张)')
|
||||
p.add_argument('--quad', action='append', default=[], required=True,
|
||||
metavar='左上x,左上y;右上x,右上y;右下x,右下y;左下x,左下y',
|
||||
help='这一张图的四个角点(顺序固定:左上 右上 右下 左下)')
|
||||
|
||||
p = sub.add_parser('show', help='查看已落盘角点')
|
||||
|
||||
p = sub.add_parser('check', help='复检已有 PDF(只渲染检验,不重新出件)')
|
||||
p.add_argument('pdf', metavar='PDF')
|
||||
p.add_argument('--expect-pages', type=int, default=None)
|
||||
p.add_argument('--dpi', type=int, default=100)
|
||||
|
||||
p = sub.add_parser('build', help='回画角标 + 校验 + 出 PDF + 检验')
|
||||
p.add_argument('images', nargs='*', help='图片名,省略则用 corners.json 里的全部')
|
||||
p.add_argument('--out', default='文档_校正.pdf')
|
||||
p.add_argument('--paper', default=None, help='a4/letter/16k/b5 或比例数字')
|
||||
p.add_argument('--dpi', type=int, default=100, help='PDF 检验渲染 dpi')
|
||||
p.add_argument('--force', action='store_true', help='角点校验不通过也继续')
|
||||
p.add_argument('--zoom', default=None,
|
||||
choices=['left', 'right', 'top', 'bottom', 'all'],
|
||||
help='另存边角放大块,便于细看')
|
||||
|
||||
p = sub.add_parser('all', help='prepare + build 一步到位')
|
||||
p.add_argument('images', nargs='*')
|
||||
p.add_argument('--out', default='文档_校正.pdf')
|
||||
p.add_argument('--paper', default=None)
|
||||
p.add_argument('--dpi', type=int, default=100)
|
||||
p.add_argument('--force', action='store_true')
|
||||
p.add_argument('--zoom', default=None)
|
||||
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.cmd == 'prepare':
|
||||
return cmd_prepare(collect_images(args.images))
|
||||
if args.cmd == 'set':
|
||||
return cmd_set(args)
|
||||
if args.cmd == 'show':
|
||||
return cmd_show()
|
||||
if args.cmd == 'check':
|
||||
return cmd_check(args.pdf, args.expect_pages, args.dpi)
|
||||
if args.cmd == 'build':
|
||||
imgs = collect_images(args.images) if args.images else []
|
||||
return cmd_build(imgs, args.out, args.paper, args.dpi, args.force, args.zoom)
|
||||
if args.cmd == 'all':
|
||||
imgs = collect_images(args.images)
|
||||
cmd_prepare(imgs)
|
||||
data = load_corners()
|
||||
lacking = [n for n in imgs if n not in data]
|
||||
if lacking:
|
||||
print('\n这些图还没有角点,填好后重跑 build:%s' % ', '.join(lacking))
|
||||
return 2
|
||||
return cmd_build(imgs, args.out, args.paper, args.dpi, args.force, args.zoom)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,185 @@
|
||||
"""角点回画预览:把已落盘的四角画回原图,供二次确认。
|
||||
|
||||
用途:把落盘的数字角点重新变成可看的画面。
|
||||
本脚本把四边形 + 四角标记 + 边标签画回原图,让"数字"重新变成可看的画面,
|
||||
在出件前确认四条边是否真的压在纸张亮面与桌面暗面的交界线上。
|
||||
|
||||
图上元素:
|
||||
绿色四边形 —— 当前角点连线,应紧贴纸边
|
||||
红色十字 + 序号 —— 四个角点(1左上 2右上 3右下 4左下)
|
||||
黄色短刻度线 —— 每条边中点的外法线,用于看边是否贴边
|
||||
右下角文字 —— 两行:文件名 / 角点串(避开顶部/左侧刻度)
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/preview_quad.py 图1.jpg 图2.jpg
|
||||
python3 doc_deskew/preview_quad.py --corners .tmp/corners.json
|
||||
python3 doc_deskew/preview_quad.py --corners .tmp/corners.json --zoom 右
|
||||
|
||||
输出:.tmp/quad_<名称>.png
|
||||
--zoom 另存右侧/左侧/上边/下边放大块,.tmp/quad_<名称>_<区域>.png
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
DEFAULT_CORNERS = '.tmp/corners.json'
|
||||
OUT_DIR = '.tmp'
|
||||
|
||||
LABELS = ['1 左上', '2 右上', '3 右下', '4 左下']
|
||||
COLOR_QUAD = (0, 255, 0)
|
||||
COLOR_CORNER = (255, 40, 40)
|
||||
COLOR_EDGE = (255, 220, 0)
|
||||
|
||||
|
||||
def load_corners(path):
|
||||
with open(path, encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
out = {}
|
||||
for name, quad in data.items():
|
||||
if isinstance(quad, dict):
|
||||
quad = quad.get('quad') or quad.get('corners')
|
||||
out[name] = [(float(p[0]), float(p[1])) for p in quad]
|
||||
return out
|
||||
|
||||
|
||||
def get_font(size=26):
|
||||
# 先找中文字体(图上要画 "1 左上" 这类标签,西文字体会变成豆腐块)
|
||||
for p in ('/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc',
|
||||
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
|
||||
'/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf'):
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
return ImageFont.truetype(p, size)
|
||||
except Exception:
|
||||
pass
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def draw_quad(img_path, pts, scale=1.0, with_grid=False):
|
||||
im = Image.open(img_path).convert('RGB')
|
||||
# 角标图默认叠上与网格图同一套网格:坐标读数与框边可以对着看
|
||||
if with_grid:
|
||||
from grid import draw_grid_on
|
||||
im = draw_grid_on(im)
|
||||
if scale != 1.0:
|
||||
im = im.resize((int(im.width * scale), int(im.height * scale)),
|
||||
Image.LANCZOS)
|
||||
d = ImageDraw.Draw(im)
|
||||
font = get_font(max(14, int(26 * min(1.0, scale + 0.15))))
|
||||
sml = get_font(max(11, int(18 * min(1.0, scale + 0.15))))
|
||||
w = max(2, int(3 * scale + 0.5))
|
||||
P = [(x * scale, y * scale) for x, y in pts]
|
||||
|
||||
# 四边形
|
||||
d.line(P + [P[0]], fill=COLOR_QUAD, width=w)
|
||||
|
||||
# 四角十字 + 序号
|
||||
r = max(10, int(22 * scale + 0.5))
|
||||
for i, (x, y) in enumerate(P):
|
||||
d.line([(x - r, y), (x + r, y)], fill=COLOR_CORNER, width=w)
|
||||
d.line([(x, y - r), (x, y + r)], fill=COLOR_CORNER, width=w)
|
||||
tx, ty = x + r + 4, y - r - 4
|
||||
d.text((tx, ty), LABELS[i], fill=COLOR_CORNER, font=sml,
|
||||
stroke_width=2, stroke_fill=(0, 0, 0))
|
||||
|
||||
# 每条边中点外法线刻度
|
||||
cx = sum(p[0] for p in P) / 4.0
|
||||
cy = sum(p[1] for p in P) / 4.0
|
||||
L = max(16, int(40 * scale + 0.5))
|
||||
for i in range(4):
|
||||
a, b = P[i], P[(i + 1) % 4]
|
||||
mx, my = (a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0
|
||||
dx, dy = mx - cx, my - cy
|
||||
n = (dx * dx + dy * dy) ** 0.5 or 1.0
|
||||
dx, dy = dx / n, dy / n
|
||||
d.line([(mx, my), (mx + dx * L, my + dy * L)],
|
||||
fill=COLOR_EDGE, width=max(2, w - 1))
|
||||
|
||||
# 右下角信息条(避开顶部/左侧的网格刻度):第一行文件名,第二行角点串
|
||||
lines = [os.path.basename(img_path),
|
||||
';'.join('%g,%g' % (p[0], p[1]) for p in pts)]
|
||||
pad = 8
|
||||
gap = 6
|
||||
tw = int(max(d.textlength(s, font=font) for s in lines))
|
||||
ascent, descent = font.getmetrics()
|
||||
line_h = ascent + descent
|
||||
th = line_h * len(lines) + gap * (len(lines) - 1)
|
||||
tx = max(pad, im.width - tw - pad * 2)
|
||||
ty = max(pad, im.height - th - pad * 2)
|
||||
d.rectangle([tx - 4, ty - 4, tx + tw + 4, ty + th + 4], fill=(0, 0, 0))
|
||||
for i, s in enumerate(lines):
|
||||
d.text((tx, ty + i * (line_h + gap)), s, fill=(255, 255, 255), font=font)
|
||||
return im
|
||||
|
||||
|
||||
def zoom_boxes(im, pts):
|
||||
"""按角点外接框给出四侧放大区域。"""
|
||||
xs = [p[0] for p in pts]
|
||||
ys = [p[1] for p in pts]
|
||||
x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
|
||||
W, H = im.size
|
||||
mx = (x1 - x0) * 0.18
|
||||
my = (y1 - y0) * 0.18
|
||||
boxes = {
|
||||
'left': (max(0, x0 - mx), max(0, y0 - my), min(W, x0 + mx), min(H, y1 + my)),
|
||||
'right': (max(0, x1 - mx), max(0, y0 - my), min(W, x1 + mx), min(H, y1 + my)),
|
||||
'top': (max(0, x0 - mx), max(0, y0 - my), min(W, x1 + mx), min(H, y0 + my)),
|
||||
'bottom': (max(0, x0 - mx), max(0, y1 - my), min(W, x1 + mx), min(H, y1 + my)),
|
||||
}
|
||||
return boxes
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description='把角点画回原图做二次确认')
|
||||
ap.add_argument('images', nargs='*', help='图片文件名(角点已在 corners.json 中)')
|
||||
ap.add_argument('--corners', default=DEFAULT_CORNERS)
|
||||
ap.add_argument('--zoom', choices=['left', 'right', 'top', 'bottom', 'all'],
|
||||
default=None, help='另存某侧放大块')
|
||||
ap.add_argument('--scale', type=float, default=1.0, help='整体缩放,>1 放大')
|
||||
ap.add_argument('--out', default=None, help='输出目录,默认 .tmp')
|
||||
args = ap.parse_args()
|
||||
|
||||
data = load_corners(args.corners)
|
||||
names = args.images or list(data.keys())
|
||||
missing = [n for n in names if n not in data]
|
||||
if missing:
|
||||
raise SystemExit('corners.json 中没有这些图的角点:%s' % ', '.join(missing))
|
||||
|
||||
outdir = args.out or OUT_DIR
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
|
||||
for name in names:
|
||||
pts = data[name]
|
||||
im = draw_quad(name, pts, args.scale)
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
dst = os.path.join(outdir, 'quad_%s.png' % base)
|
||||
im.save(dst)
|
||||
print('written %s (%dx%d) %s' % (dst, im.width, im.height,
|
||||
';'.join('%g,%g' % p for p in pts)))
|
||||
if args.zoom:
|
||||
boxes = zoom_boxes(im, [(x * args.scale, y * args.scale) for x, y in pts])
|
||||
keys = list(boxes) if args.zoom == 'all' else [args.zoom]
|
||||
for k in keys:
|
||||
box = tuple(int(v) for v in boxes[k])
|
||||
if box[2] <= box[0] or box[3] <= box[1]:
|
||||
continue
|
||||
crop = im.crop(box)
|
||||
f = min(3.0, max(1.0, 700.0 / max(1, crop.width)))
|
||||
if f > 1.0:
|
||||
crop = crop.resize((int(crop.width * f), int(crop.height * f)),
|
||||
Image.LANCZOS)
|
||||
z = os.path.join(outdir, 'quad_%s_%s.png' % (base, k))
|
||||
crop.save(z)
|
||||
print('written %s (%dx%d)' % (z, crop.width, crop.height))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""拉正合成的核心模块:四边形透视变换 + 按页拼版。
|
||||
|
||||
由 pipeline.py 的 build 子命令调用,不单独提供命令行入口(原来那套
|
||||
--grid/--page/--check 已分别由 prepare / build / check 接管,免得两个入口各说各话)。
|
||||
|
||||
设计原则:
|
||||
1. 不做中间校正。角点只用来定义纸张四边,几何变换一次到位,
|
||||
校正结果直接进 PDF;所有质量判定都在最终 PDF 上做。
|
||||
2. 不在流程里"自动收紧/自动修补"。这类启发式规则容易误裁内容,
|
||||
只保留能明确判定对错的检验项。
|
||||
3. 判定阈值来自每页图像自身统计,不是针对某份文档调出来的常量。
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import numpy as np
|
||||
from homography import brighten, warp_perspective
|
||||
from PIL import Image
|
||||
|
||||
# 纸张宽高比(宽/高):pipeline 与 run 共用这一份,避免两套系数漂移
|
||||
PAPERS = {'a4': 210 / 297, 'letter': 8.5 / 11, '16k': 185 / 260, 'b5': 176 / 250}
|
||||
|
||||
|
||||
def parse_page(spec):
|
||||
src, _, quad_s = spec.partition(':')
|
||||
if not src or not quad_s:
|
||||
raise SystemExit('格式应为 "图片:左上;右上;右下;左下":%s' % spec)
|
||||
quad = []
|
||||
for pt in quad_s.split(';'):
|
||||
x, y = pt.split(',')
|
||||
quad.append((float(x), float(y)))
|
||||
if len(quad) != 4:
|
||||
raise SystemExit('角点必须 4 个:%s' % spec)
|
||||
return src, quad
|
||||
|
||||
|
||||
def build(specs, out_pdf, workdir='out', ratio=None):
|
||||
"""一次几何变换得到页面图,直接合并。不做二次裁切。
|
||||
|
||||
ratio=None 时按四边形自然尺寸输出(保留照片原始比例);
|
||||
给定 ratio(如 A4=0.707)时强制映射到该纸张比例,纠正透视压缩。
|
||||
"""
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
pages = []
|
||||
for i, spec in enumerate(specs, 1):
|
||||
src, quad = parse_page(spec)
|
||||
im = Image.open(src).convert('RGB')
|
||||
if ratio is None:
|
||||
page = brighten(warp_perspective(im, quad))
|
||||
else:
|
||||
q = np.array(quad, float)
|
||||
wpx = (np.linalg.norm(q[1] - q[0]) + np.linalg.norm(q[2] - q[3])) / 2
|
||||
hpx = wpx / ratio
|
||||
page = brighten(warp_perspective(
|
||||
im, quad, out_size=(int(round(wpx)), int(round(hpx)))))
|
||||
path = os.path.join(workdir, 'p%d.png' % i)
|
||||
page.save(path)
|
||||
pages.append(path)
|
||||
nw, nh = page.size
|
||||
print(' 第 %d 页 %-28s -> %s %dx%d 比例 %.3f'
|
||||
% (i, os.path.basename(src), path, nw, nh, nw / nh))
|
||||
|
||||
subprocess.run([sys.executable, os.path.join(HERE, 'make_pdf.py')]
|
||||
+ pages + [out_pdf], check=True)
|
||||
return pages
|
||||
@@ -0,0 +1,185 @@
|
||||
"""几何校验:四角坐标是否合理覆盖了纸张。
|
||||
|
||||
不依赖图像亮度,只看几何关系,因此不受白底干扰:
|
||||
1. 四边形必须凸,且顺序为 左上→右上→右下→左下
|
||||
2. 四边形必须落在源图范围内(允许少量越界,用于角点出画面的情况)
|
||||
3. 四边形内应基本是纸面(亮像素占多数),说明没有取到桌面
|
||||
4. 沿四条边外侧一圈应是桌面(暗像素占多数),说明没有少取纸张
|
||||
|
||||
任一项失败即说明该角点需调整,并指出是哪条边。
|
||||
|
||||
用法:
|
||||
python3 doc_deskew/verify_quad.py 图.jpg "左上;右上;右下;左下"
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def parse(qs):
|
||||
pts = []
|
||||
for pt in qs.split(';'):
|
||||
x, y = pt.split(',')
|
||||
pts.append((float(x), float(y)))
|
||||
if len(pts) != 4:
|
||||
raise SystemExit('需要 4 个角点')
|
||||
return pts
|
||||
|
||||
|
||||
def sample_map(a, pts, n=60, shrink=1.0, outward=0.0):
|
||||
"""在四边形内部取网格点(shrink<1 向内收),或在外部环带取点(outward>0)。"""
|
||||
|
||||
h, w = a.shape
|
||||
tl, tr, br, bl = [np.asarray(p, float) for p in pts]
|
||||
c = (tl + tr + br + bl) / 4.0
|
||||
if shrink != 1.0:
|
||||
tl, tr, br, bl = [c + (p - c) * shrink for p in (tl, tr, br, bl)]
|
||||
if outward > 0:
|
||||
tl, tr, br, bl = [c + (p - c) * (1 + outward) for p in (tl, tr, br, bl)]
|
||||
vals = []
|
||||
for u in np.linspace(0.03, 0.97, n):
|
||||
p1 = tl + (tr - tl) * u
|
||||
p2 = bl + (br - bl) * u
|
||||
for v in np.linspace(0.03, 0.97, n):
|
||||
x, y = p1 + (p2 - p1) * v
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
vals.append(a[yi, xi])
|
||||
return np.asarray(vals)
|
||||
|
||||
|
||||
def cross(o, a, b):
|
||||
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
|
||||
|
||||
def check(img, pts, verbose=True):
|
||||
a = np.asarray(Image.open(img).convert('L')).astype(np.float32)
|
||||
h, w = a.shape
|
||||
paper = float(np.percentile(a, 80))
|
||||
back = float(np.percentile(a, 2))
|
||||
thr = back + (paper - back) * 0.5
|
||||
ok = True
|
||||
|
||||
# 1. 凸性与顺序
|
||||
signs = [cross(pts[i], pts[(i + 1) % 4], pts[(i + 2) % 4]) for i in range(4)]
|
||||
convex = all(s > 0 for s in signs)
|
||||
if verbose:
|
||||
print(' [%s] 角点顺序/凸性' % ('OK' if convex else 'XX'))
|
||||
if not convex:
|
||||
print(' 方向不一致,顺序应为 左上→右上→右下→左下')
|
||||
ok = False
|
||||
|
||||
# 2. 越界幅度
|
||||
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
|
||||
out = [max(0, -min(xs)), max(0, max(xs) - w), max(0, -min(ys)), max(0, max(ys) - h)]
|
||||
oob = max(out) / max(w, h) * 100
|
||||
good = oob < 15
|
||||
if verbose:
|
||||
print(' [%s] 越界幅度 %.1f%%(角点出画面属正常,上限 15%%)'
|
||||
% ('OK' if good else 'XX', oob))
|
||||
ok &= good
|
||||
|
||||
# 3. 内部应是纸面(亮)
|
||||
inner = sample_map(a, pts, shrink=0.88)
|
||||
frac_paper = float((inner > thr).mean())
|
||||
good = frac_paper > 0.6
|
||||
if verbose:
|
||||
print(' [%s] 框内纸面占比 %.0f%%(应 >60%%,偏低说明取到桌面)'
|
||||
% ('OK' if good else 'XX', frac_paper * 100))
|
||||
ok &= good
|
||||
|
||||
# 4. 四条边外侧应是桌面(暗)——逐边判定,指出问题边
|
||||
names = ['上边', '右边', '下边', '左边']
|
||||
bad_edges = []
|
||||
for i in range(4):
|
||||
p1, p2 = pts[i], pts[(i + 1) % 4]
|
||||
mid = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
c = sum(np.asarray(p, float) for p in pts) / 4
|
||||
d = mid - c
|
||||
norm = np.linalg.norm(d)
|
||||
if norm < 1e-6:
|
||||
continue
|
||||
d = d / norm
|
||||
# 沿该边外侧取样
|
||||
tc = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
fracs = []
|
||||
for t in np.linspace(0.15, 0.85, 12):
|
||||
base = np.asarray(p1) + (np.asarray(p2) - np.asarray(p1)) * t
|
||||
span = max(w, h)
|
||||
for k in (span * 0.02, span * 0.035, span * 0.05): # 外移 2%%~5%% 图幅
|
||||
x, y = base + d * k
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
fracs.append(a[yi, xi])
|
||||
if len(fracs) < 8:
|
||||
continue
|
||||
fracs = np.asarray(fracs)
|
||||
dark_frac = float((fracs < thr).mean())
|
||||
# 外侧大部分应是暗背景;若几乎全亮,说明该边取进了纸内,纸边被切
|
||||
if dark_frac < 0.35:
|
||||
bad_edges.append((names[i], dark_frac))
|
||||
# 5. 沿四条边内侧取样: 应全是纸面; 若混入桌面说明该边取到纸外
|
||||
outside_edges = []
|
||||
for i in range(4):
|
||||
p1, p2 = pts[i], pts[(i + 1) % 4]
|
||||
mid = (np.asarray(p1) + np.asarray(p2)) / 2
|
||||
c = sum(np.asarray(p, float) for p in pts) / 4
|
||||
d = mid - c
|
||||
norm = np.linalg.norm(d)
|
||||
if norm < 1e-6:
|
||||
continue
|
||||
d = d / norm
|
||||
vals = []
|
||||
span = max(w, h)
|
||||
for t in np.linspace(0.15, 0.85, 12):
|
||||
base = np.asarray(p1) + (np.asarray(p2) - np.asarray(p1)) * t
|
||||
for k in (span * 0.015, span * 0.03, span * 0.045):
|
||||
x, y = base - d * k # 向内
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
vals.append(a[yi, xi])
|
||||
if len(vals) < 8:
|
||||
continue
|
||||
vals = np.asarray(vals)
|
||||
paper_frac = float((vals > thr).mean())
|
||||
if paper_frac < 0.75:
|
||||
outside_edges.append((names[i], paper_frac))
|
||||
good2 = not outside_edges
|
||||
|
||||
if verbose:
|
||||
if not bad_edges:
|
||||
print(' [OK] 四边外侧检测到桌面,纸边已被框住')
|
||||
else:
|
||||
# 外侧仍偏亮有两种可能:取点偏内(会切内容),或纸边本身倾斜导致
|
||||
# 固定外移采样仍落在纸内。二者无法用亮度区分,故只作提示不判错。
|
||||
print(' [--] 提示:下列边外侧仍偏亮(可能取点偏内,也可能是纸边倾斜):')
|
||||
for n, f in bad_edges:
|
||||
print(' %s 外侧纸面占比 %.0f%% → 可尝试再向外扩 3~5px 后目视确认'
|
||||
% (n, (1 - f) * 100))
|
||||
|
||||
if verbose:
|
||||
if good2:
|
||||
print(' [OK] 四边内侧均为纸面')
|
||||
else:
|
||||
print(' [XX] 下列边内侧混入桌面,说明取点落在纸外:')
|
||||
for n, f in outside_edges:
|
||||
print(' %s(内侧纸面仅 %.0f%%)→ 该边角点向内收 5px' % (n, f * 100))
|
||||
ok &= good2
|
||||
return ok
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('img'); ap.add_argument('quad')
|
||||
a = ap.parse_args()
|
||||
pts = parse(a.quad)
|
||||
print('校验 %s 角点 %s' % (a.img, a.quad))
|
||||
ok = check(a.img, pts)
|
||||
print('\n结论:%s' % ('角点可用' if ok else '需调整上面标 XX 的项'))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user