在 Python 3 中,快速获取图片中的文字(OCR) 最成熟、最省事的做法是直接使用 Tesseract OCR 。下面给你一套从零到可用的方案,兼顾速度和准确率。
一、安装依赖
1️、安装 Tesseract OCR
Windows
下载:https://github.com/UB-Mannheim/tesseract/wiki
安装后记住路径,例如:
C:\Program Files\Tesseract-OCR\tesseract.exe
Linux
sudo apt install tesseract-ocr
macOS
brew install tesseract
验证:
tesseract --version
2️、安装 Python 库
pip install pytesseract pillow
二、最简示例(5 行代码)
import pytesseract
from PIL import Image
text = pytesseract.image_to_string(Image.open("test.png"), lang="chi_sim+eng")
print(text)
✅ 支持:
-
中文:
chi_sim -
英文:
eng -
中英混合:
chi_sim+eng
三、中文识别必须做的事
安装中文语言包
- Windows:安装时勾选 Chinese
Linux:
sudo apt install tesseract-ocr-chi-sim
✅ 提高准确率的关键技巧(很重要)
1️、灰度 + 二值化
from PIL import Image
img = Image.open("test.png").convert("L")
img = img.point(lambda x: 0 if x < 140 else 255)
print(pytesseract.image_to_string(img))
2️、指定页面分割模式(PSM)
custom_config = r'--oem 3 --psm 6'
text = pytesseract.image_to_string(img, config=custom_config)
常用 PSM:
-
3:自动分页(默认) -
6:统一文本块 -
7:单行文本 -
11:稀疏文本
3️、Windows 指定 Tesseract 路径
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
✅ 批量识别图片
import os
for f in os.listdir("images"):
if f.endswith(".png"):
text = pytesseract.image_to_string(Image.open(f"images/{f}"))
print(f, text.strip())
✅ 获取文字位置(做标注 / 审核)
data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
print(data["text"])
print(data["left"])
print(data["top"])