补扫:默认关(要开用 gap_scan=True),修坐标没除 1.4 倍导致的越界框(240 测试)

This commit is contained in:
dsh
2026-11-22 21:23:53 +08:00
parent bde4170423
commit 8a93058855
4 changed files with 45 additions and 11 deletions
+21 -5
View File
@@ -35,6 +35,8 @@ GAP_MAX = 2 # 一页最多补扫两条,再多就是在赌
GAP_INK = 0.004 # 条带里墨迹像素占比下限(低于它基本是空白)
GAP_MAX_INK = 0.55 # 高于它更像照片/阴影,不是文字
GAP_PAD = 24
# 补扫的条带会放大再送 OCR,返回的框是放大后的坐标,要按这个数除回去
GAP_SCALE = 1.4
def _pil():
@@ -70,8 +72,15 @@ def save_draft(image_bytes: bytes, filename: str = "page.jpg") -> dict:
def _gap_enabled() -> bool:
return os.environ.get("OCR_GAP_SCAN", "1").strip().lower() not in (
"0", "false", "no", "off")
"""补扫要不要做:默认由 detect(gap_scan=) 决定,环境变量只用来「强制关」。
补扫在真实卷子上救回过整块(看图写数、比大小),但每页多 1–2 次调用,
所以默认关闭;要开就 detect(..., gap_scan=True),线上想临时全关就设 OCR_GAP_SCAN=0。
"""
v = os.environ.get("OCR_GAP_SCAN")
if v is None:
return True
return v.strip().lower() not in ("0", "false", "no", "off")
def _ink_rows(src: Path) -> list[float]:
@@ -147,7 +156,7 @@ def _crop_band(src: Path, y0: int, y1: int) -> bytes | None:
with Image.open(src) as im:
im = im.convert("RGB")
crop = im.crop((0, y0, im.width, y1))
crop = crop.resize((int(crop.width * 1.4), int(crop.height * 1.4)),
crop = crop.resize((int(crop.width * GAP_SCALE), int(crop.height * GAP_SCALE)),
Image.LANCZOS)
crop = ImageOps.autocontrast(crop, cutoff=1)
buf = io.BytesIO()
@@ -193,7 +202,14 @@ def _gap_blocks(src: Path, blocks: list[dict], w: int, h: int) -> list[dict]:
continue
if box["w"] < MIN_BOX_SIDE or box["h"] < MIN_BOX_SIDE:
continue
moved = {"x": box["x"], "y": box["y"] + y0, "w": box["w"], "h": box["h"]}
# 补扫图是放大 1.4 倍再送的,坐标要除回去;再整体下移到条带在原图里的位置
bx = int(round(box["x"] / GAP_SCALE))
by = int(round(box["y"] / GAP_SCALE)) + y0
bw = int(round(box["w"] / GAP_SCALE))
bh = int(round(box["h"] / GAP_SCALE))
if by < 0 or by >= h or bx >= w:
continue
moved = {"x": bx, "y": by, "w": bw, "h": bh}
if _center_in(moved, blocks) or _center_in(moved, added):
continue
seen.add(key)
@@ -210,7 +226,7 @@ def _gap_blocks(src: Path, blocks: list[dict], w: int, h: int) -> list[dict]:
def detect(image_bytes: bytes, filename: str = "page.jpg",
gap_scan: bool = True) -> dict:
gap_scan: bool = False) -> dict:
"""整页切块。返回题块 + 草稿 id;切不出题就抛 422 让前端提示重拍。"""
d = save_draft(image_bytes, filename)
res = tencent_ocr.split_questions(image_bytes)