- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality. - Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability. - Updated various components to utilize the new preprocessing function, improving code organization and readability. - Adjusted configuration values in `config.json` for better performance and consistency. - Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines. - Cleaned up excessive blank lines across multiple files to enhance overall readability.
71 lines
1.8 KiB
Python
71 lines
1.8 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 path_config import get_cut_pic_path
|
||
except Exception:
|
||
# 如果 PIL 或 path_config 不可用,回退到原名
|
||
return cut_pic_name
|
||
|
||
src = get_cut_pic_path(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
|
||
img = Image.open(src)
|
||
img.load()
|
||
# 转灰度
|
||
img = img.convert("L")
|
||
# 放大两倍(Lanczos)
|
||
img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
|
||
# 自动对比并锐化
|
||
img = ImageOps.autocontrast(img)
|
||
img = img.filter(ImageFilter.SHARPEN)
|
||
# 保存为目标路径(覆盖或新文件)
|
||
img.save(dst)
|
||
return pre_name
|
||
except Exception:
|
||
# 任何异常回退到原名,保证不抛出
|
||
try:
|
||
return cut_pic_name
|
||
except Exception:
|
||
return cut_pic_name
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|