Распознать текст на изображениях
Прогоняет скриншоты и сканы через Tesseract и сохраняет распознанный текст в отдельные файлы.
Что делает скрипт
Скрипт открывает изображение, применяет поворот из EXIF и передает его в локальный Tesseract. Язык и режим сегментации задаются параметрами, результат можно вывести на экран или записать в TXT. Оригиналы не изменяются, для Windows можно указать путь к tesseract.exe.
- Качество распознавания зависит от резкости, контраста и разрешения исходника.
Быстрый старт
python ocr_tesseract.py --dir ./scans --out ./text --lang rus+eng
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python ocr_tesseract.py --dir ./scans --out ./textpython ocr_tesseract.py --dir ./screens --lang eng --psm 6 --recursivepython ocr_tesseract.py --input ./receipt.png --lang rus
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install Pillow
python3 -m pip install Pillow
python3 -m pip install Pillow
py -m pip install pytesseract
python3 -m pip install pytesseract
python3 -m pip install pytesseract
winget install UB-Mannheim.TesseractOCR
brew install tesseract tesseract-lang
sudo apt install tesseract-ocr tesseract-ocr-rus
ocr_tesseract.py
#!/usr/bin/env python3
"""Распознавание текста на изображениях через Tesseract."""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
try:
from PIL import Image, ImageOps
except ImportError:
sys.exit("Нужен Pillow: python3 -m pip install Pillow")
try:
import pytesseract
except ImportError:
sys.exit("Нужен pytesseract: python3 -m pip install pytesseract")
EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
def collect(source: Path, recursive: bool) -> list[Path]:
if source.is_file():
return [source]
pattern = "**/*" if recursive else "*"
return sorted(
path for path in source.glob(pattern)
if path.is_file() and path.suffix.lower() in EXTENSIONS
)
def main() -> int:
parser = argparse.ArgumentParser(description="Распознать текст на изображениях")
parser.add_argument("--input", type=Path)
parser.add_argument("--dir", type=Path)
parser.add_argument("--out", type=Path, help="Папка для TXT, без нее текст печатается")
parser.add_argument("--lang", default="eng")
parser.add_argument("--psm", type=int, default=3)
parser.add_argument("--tesseract", type=Path, help="Путь к tesseract.exe на Windows")
parser.add_argument("--recursive", action="store_true")
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if bool(args.input) == bool(args.dir):
parser.error("Укажите либо --input, либо --dir")
if args.tesseract:
pytesseract.pytesseract.tesseract_cmd = str(args.tesseract.expanduser().resolve())
elif shutil.which("tesseract") is None:
print("Tesseract не найден в PATH. Установите его или укажите --tesseract.")
return 2
source = (args.input or args.dir).expanduser().resolve()
if not source.exists():
parser.error(f"Источник не найден: {source}")
files = collect(source, args.recursive)
if not files:
print("Изображения не найдены.")
return 0
out_dir = None
if args.out:
out_dir = args.out.expanduser().resolve()
out_dir.mkdir(parents=True, exist_ok=True)
done = skipped = failed = 0
for path in files:
target = out_dir / (path.stem + ".txt") if out_dir else None
if target and target.exists() and not args.overwrite:
skipped += 1
continue
try:
with Image.open(path) as opened:
image = ImageOps.exif_transpose(opened).convert("RGB")
text = pytesseract.image_to_string(
image,
lang=args.lang,
config=f"--psm {args.psm}",
).strip()
if target:
target.write_text(text + "\n", encoding="utf-8")
print(f"Готово: {path.name} -> {target.name} ({len(text)} символов)")
else:
print(f"--- {path.name} ---")
print(text if text else "(текст не найден)")
except Exception as error:
print(f"Ошибка {path}: {error}")
failed += 1
continue
done += 1
print(f"Итог: {done} обработано, {skipped} пропущено, {failed} ошибок")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.