68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
from __future__ import annotations
|
|
|
|
"""
|
|
OCR 预处理工具
|
|
提供统一的图像预处理流水线:灰度、放大、自动对比、锐化等,以提高 OCR 识别稳定性。
|
|
接口尽量简单:preprocess_for_ocr(analyser, cut_pic_name) -> 返回用于 OCR 的图片名称(不含扩展名)。
|
|
"""
|
|
|
|
from typing import Any
|
|
import os
|
|
|
|
def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str:
|
|
"""对已由 ScreenshotHandler.cut_pic 生成的裁剪图做预处理,返回可传入 analyse_pic_* 的图片名。
|
|
|
|
参数:
|
|
analyser: fudai_analyse 实例
|
|
cut_pic_name: cut_pic 时使用的名称(不含扩展名)
|
|
返回:
|
|
返回预处理后图片的名称(不含扩展名),调用者应把它传给 analyse_pic_word/analyse_pic_digits
|
|
"""
|
|
try:
|
|
from PIL import Image, ImageOps, ImageFilter
|
|
from douyin.core.path_config import get_cut_pic_path
|
|
except Exception:
|
|
# 如果 PIL 或 path_config 不可用,回退到原名
|
|
return cut_pic_name
|
|
|
|
src = get_cut_pic_path(cut_pic_name)
|
|
if cut_pic_name in {
|
|
"福袋内容",
|
|
"福袋任务列表",
|
|
"参与按钮",
|
|
"live_room_title_mid",
|
|
"福袋倒计时_整行",
|
|
}:
|
|
return cut_pic_name
|
|
pre_name = f"{cut_pic_name}_preprocessed"
|
|
dst = get_cut_pic_path(pre_name)
|
|
|
|
try:
|
|
if not os.path.exists(src):
|
|
return cut_pic_name
|
|
_raw = Image.open(src)
|
|
try:
|
|
_raw.load()
|
|
# 转灰度
|
|
img = _raw.convert("L")
|
|
finally:
|
|
_raw.close()
|
|
is_countdown_digit = str(cut_pic_name or "").startswith("福袋倒计时_")
|
|
# 倒计时分秒小图通常只有几十像素宽,2x 仍容易把 00 识别成空。
|
|
scale = 4 if is_countdown_digit else 2
|
|
img = img.resize((img.width * scale, img.height * scale), Image.LANCZOS)
|
|
# 自动对比并锐化
|
|
img = ImageOps.autocontrast(img)
|
|
img = img.filter(ImageFilter.SHARPEN)
|
|
if is_countdown_digit:
|
|
img = ImageOps.expand(img, border=max(4, scale * 2), fill=255)
|
|
# 保存为目标路径(覆盖或新文件)
|
|
img.save(dst)
|
|
return pre_name
|
|
except Exception:
|
|
# 任何异常回退到原名,保证不抛出
|
|
try:
|
|
return cut_pic_name
|
|
except Exception:
|
|
return cut_pic_name
|