Image OCR (Tesseract)
Extract text from images using Tesseract OCR engine with Python wrapper. Cross-platform support for Windows, macOS, and Linux.
Prerequisites
- Tesseract OCR (v5.0+)
- Python packages:
pytesseract,Pillow - Language packs: Chinese (
chi_sim) and English (eng) recommended
Install Tesseract
| Platform | Command |
|----------|---------|
| Windows | Download from UB-Mannheim/tesseract |
| macOS | brew install tesseract |
| Linux | sudo apt install tesseract-ocr (Debian/Ubuntu) |
Install Python Dependencies
pip install pytesseract Pillow
Usage
Basic OCR
python scripts/ocr.py <image_path> [-l LANGUAGE] [--psm PSM]
Examples:
# Auto-detect Tesseract, use default language (chi_sim+eng)
python scripts/ocr.py screenshot.png
# Specify language
python scripts/ocr.py document.jpg -l chi_sim+eng
# Specify page segmentation mode
python scripts/ocr.py photo.jpg -l eng --psm 6
# Specify Tesseract path manually
python scripts/ocr.py image.png --tesseract-path "C:\Program Files\Tesseract-OCR"
# List installed language packs
python scripts/ocr.py --list-langs
Tesseract Discovery (auto-detection order)
The script finds Tesseract automatically in this order:
--tesseract-pathCLI argumentTESSERACT_PATHenvironment variable- Config file (
~/.config/image-ocr/config.jsonor%APPDATA%/image-ocr/config.json) - Common install locations:
- Windows:
C:\Program Files\Tesseract-OCR,C:\Program Files (x86)\Tesseract-OCR - macOS:
/usr/local/bin/tesseract,/opt/homebrew/bin/tesseract - Linux:
/usr/bin/tesseract,/usr/local/bin/tesseract
- Windows:
- System
PATH
Persistent Configuration
Create a JSON config file to set a persistent Tesseract path:
Windows: %APPDATA%\image-ocr\config.json
macOS/Linux: ~/.config/image-ocr/config.json
{
"tesseract_path": "/path/to/tesseract"
}
Supported Languages
| Language | Code | Description |
|----------|------|-------------|
| Chinese Simplified | chi_sim | 简体中文 |
| Chinese Traditional | chi_tra | 繁體中文 |
| English | eng | English |
| Japanese | jpn | 日本語 |
| Korean | kor | 한국어 |
Combine multiple languages: chi_sim+eng
Script Location
scripts/ocr.py - Main OCR script
Notes
- For best results, ensure images are clear and well-lit
- Chinese recognition requires
chi_simlanguage pack - Output is plain text; use
--psmflag for specific page segmentation modes - Verbose diagnostic info (Tesseract version, path, language) is printed to stderr
微信扫一扫