需先安装Tesseract引擎再安装pytesseract库;Windows下载安装包并勾选“Add to PATH”,macOS用brew install tesseract,Linux用apt install tesseract-ocr;随后pip install pytesseract,并按需配置tesseract_cmd路径。
要让Python调用OCR功能,得先装好Tesseract引擎本身,再装Python封装库pytesseract。
Windows用户可去Tesseract官方Wiki页面下载安装包(推荐带训练数据的完整版),安装时勾选“Add to PATH”;macOS用户用Homebrew执行brew install tesseract;Linux(如Ubuntu)运行sudo apt install tesseract-ocr libtesseract-dev。
接着在终端或命令行中安装Python接口:
pip install pytesseractpytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'(Windows)pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract'(macOS/Linux)最常用场景是把一张清晰截图或扫描图转成字符串。支持格式包括PNG、JPG、BMP等。
示例代码:
from PIL import Image import pytesseract打开图片
img = Image.open('receipt.png')
直接识别,默认使用eng语言包
text = pytesseract.image_to_string(img) print(text)
注意点:
chi_sim或chi_tra),并传入lang='chi_sim'
config='--psm 6'参数提升单行/规则文本识别率(PSM模式详见下节)Tesseract提供Page Segmentation Mode(PSM)和OCR Engine Mode(OEM)两个核心配置项,直接影响结果质量。
常用PSM值说明:
调用方式:
text = pytesseract.image_to_string(
img,
lang='chi_sim',
config='--psm 6 --oem 3'
)
OEM推荐始终用--oem 3(LSTM神经网络引擎,Tesseract 4+默认),老版本才考虑OEM 0/1。
Tesseract对输入图像很敏感。原始图片常需简单预处理:
img.convert('L')
point函数或OpenCV的threshold
ImageFilter.MedianFilter();大面积噪点建议用OpenCV的形态学操作skimage.transform.rotate
一个轻量预处理示例:
from PIL import Image, ImageEnhancedef preprocess(img): img = img.convert('L') # 灰度 enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(2.0) # 提高对比度 return img.point(lambda x: 0 if x < 128 else 255, '1') # 二值化
clean_img = preprocess(Image.open('id_card.jpg')) text = pytesseract.image_to_string(clean_img, lang='chi_sim', config='--psm 6')
除了纯文本,Tesseract还能返回每个字符/单词的位置、置信度等结构化数据。
image_to_boxes(img):返回字符级坐标(左下角x,y + 右上角x,y + 字符)image_to_data(img):返回DataFrame格式,含level、page_num、block_num、par_num、line_num、word_num、left、top、width、height、conf、text等字段,conf即识别置信度(-1表示跳过)df = df[df.conf != -1],再用df[df.conf > 60]['text'].str.cat(sep=' ')拼接高可信文本这些输出可用于构建带定位的OCR系统,比如提取发票中的“金额”“日期”字段,或做图文对齐。