Files
douyin_guaji-main/douyin/utils/ocr_preprocess.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

53 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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