简介:本文记录小猪在Python学习中使用pytesseract库进行文字识别的实践过程,包括环境搭建、基础功能演示及优化技巧,帮助读者快速掌握OCR技术入门方法。
在数字化办公场景中,将图片中的文字转换为可编辑文本(OCR技术)具有重要价值。小猪在处理扫描版合同和手写笔记时,发现传统手动录入效率低下且易出错。经过调研,他锁定了Tesseract OCR引擎——这款由Google维护的开源工具,支持100+种语言识别,而pytesseract正是其Python封装库。
相较于商业API(如某云OCR服务需付费调用),pytesseract的零成本特性对学习者极具吸引力。其工作原理包含图像预处理、字符分割、特征匹配三个阶段,通过深度学习模型实现文字识别。但需注意,该库对复杂背景或艺术字体的识别效果有限,这为后续优化埋下伏笔。
在Windows系统下,小猪通过pip install pytesseract pillow完成基础库安装。但首次运行时遇到TesseractNotFoundError,原来还需单独安装Tesseract OCR引擎本体:
# Windows安装命令(需管理员权限)choco install tesseract # 使用Chocolatey包管理器# 或手动下载安装包
Mac用户可通过Homebrew快速安装:
brew install tesseract
安装后需将Tesseract路径添加至系统环境变量。小猪在Windows中通过”此电脑→属性→高级系统设置→环境变量”,在Path变量后追加C:\Program Files\Tesseract-OCR(默认安装路径)。验证是否成功可通过命令行执行:
tesseract --version# 应输出类似"tesseract 5.3.0"的版本信息
为避免依赖冲突,小猪创建了专用虚拟环境:
python -m venv ocr_envsource ocr_env/bin/activate # Linux/Mac.\ocr_env\Scripts\activate # Windowspip install -r requirements.txt # 包含pytesseract和Pillow
小猪首先测试标准印刷体识别:
from PIL import Imageimport pytesseract# 设置Tesseract路径(Windows特有)# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'def simple_ocr(image_path):img = Image.open(image_path)text = pytesseract.image_to_string(img, lang='chi_sim+eng') # 中文简体+英文print("识别结果:\n", text)simple_ocr("test_cn.png")
运行后成功输出图片中的中英文混合文本,但发现某些生僻字被误识别为形似字符。
通过config参数可指定识别区域和输出格式:
# 仅识别左上角(100,100)到(400,400)的区域custom_config = r'--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789'number_text = pytesseract.image_to_string(img,config=custom_config,boxes=True # 输出字符位置信息)
其中--psm 6表示假设文本为统一区块,whitelist参数可限制识别字符集,显著提升数字识别准确率。
对于扫描版PDF,小猪采用两步转换法:
import pdf2imagedef pdf_to_text(pdf_path):# 将PDF转为图片列表images = pdf2image.convert_from_path(pdf_path, dpi=300)full_text = ""for i, image in enumerate(images):text = pytesseract.image_to_string(image, lang='chi_sim')full_text += f"\n第{i+1}页:\n{text}"return full_text
通过提高DPI(每英寸点数)至300,有效解决了低分辨率PDF的识别模糊问题。
小猪发现直接识别效果不佳时,通过OpenCV进行预处理:
import cv2def preprocess_image(img_path):img = cv2.imread(img_path)# 转为灰度图gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 二值化处理thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]# 降噪denoised = cv2.fastNlMeansDenoising(thresh, h=10)return denoisedprocessed_img = preprocess_image("noisy.png")cv2.imwrite("cleaned.png", processed_img)
经测试,该处理使复杂背景图片的识别准确率提升约35%。
面对中英文混排文档时,需指定语言包:
# 下载中文语言包(需单独安装)# Windows安装路径:Tesseract安装目录/tessdatatext = pytesseract.image_to_string(img,lang='chi_sim+eng', # 同时加载中英文模型config='--psm 6')
若识别效果仍不理想,可尝试调整--oem参数(0=传统算法,3=LSTM神经网络)。
为提高效率,小猪编写了批量处理脚本:
import osdef batch_ocr(input_dir, output_file):results = []for filename in os.listdir(input_dir):if filename.lower().endswith(('.png', '.jpg', '.jpeg')):img_path = os.path.join(input_dir, filename)text = pytesseract.image_to_string(Image.open(img_path))results.append(f"{filename}:\n{text}\n{'='*50}")with open(output_file, 'w', encoding='utf-8') as f:f.write('\n'.join(results))print(f"处理完成,结果保存至{output_file}")batch_ocr("images/", "ocr_results.txt")
ModuleNotFoundError: No module named 'pytesseract'
pip install --upgrade pippip uninstall pytesseract pillowpip install pytesseract pillow
当输出出现方框或乱码时:
tessdata目录下应有chi_sim.traineddata等文件)--psm模式(如从默认的3改为6)对于大批量处理,建议:
concurrent.futures模块)通过本次实践,小猪不仅掌握了pytesseract的基础用法,更深刻理解了OCR技术的适用场景与局限性。他计划在下阶段研究中探索如何将传统OCR与深度学习模型相结合,以应对手写体识别等更高阶挑战。