简介:本文详细解析Python OCR工具pytesseract,涵盖安装配置、基础用法、高级功能及实战案例,助力开发者高效实现图像文字识别。
在数字化时代,OCR(光学字符识别)技术已成为处理图像文本的核心工具。Python的pytesseract库作为Tesseract OCR引擎的封装,凭借其开源、跨平台、支持多语言等特性,成为开发者首选。本文从安装配置、基础用法、高级功能到实战案例,系统解析pytesseract的完整使用流程,并提供优化建议与常见问题解决方案,助力开发者高效实现图像文字识别。
pytesseract是Python对Tesseract OCR引擎的封装库,通过调用Tesseract的命令行接口实现图像到文本的转换。Tesseract由Google开发,支持100+种语言,并具备学习自定义模型的能力,而pytesseract将其功能无缝集成到Python生态中。
安装Tesseract引擎:
tesseract-ocr-w64-setup-v5.3.0.20230401.exe),安装时勾选附加语言包。brew install tesseract。sudo apt install tesseract-ocr。安装pytesseract库:
pip install pytesseract
C:\Program Files\Tesseract-OCR)添加到系统PATH。
import pytesseractpytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
from PIL import Imageimport pytesseract# 读取图像image = Image.open('example.png')# 执行OCRtext = pytesseract.image_to_string(image)print(text)
输出示例:
Hello, World!这是一段测试文本。
# 指定中文识别text_cn = pytesseract.image_to_string(image, lang='chi_sim')# 使用PSM模式(页面分割模式)text_psm = pytesseract.image_to_string(image, config='--psm 6')
参数说明:
lang:语言代码(如eng英文,chi_sim简体中文)。config:传递Tesseract参数,如--psm 6假设文本为统一块。结合OpenCV进行二值化、降噪等预处理:
import cv2import numpy as npdef preprocess_image(image_path):# 读取图像为灰度图img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)# 二值化处理_, binary = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)# 降噪(可选)binary = cv2.medianBlur(binary, 3)return binary# 预处理后识别processed_img = preprocess_image('example.png')text = pytesseract.image_to_string(processed_img)
# 获取单词级位置信息data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)for i in range(len(data['text'])):if int(data['conf'][i]) > 60: # 过滤低置信度结果print(f"文本: {data['text'][i]}, 位置: ({data['left'][i]}, {data['top'][i]})")
输出字段:
level:文本层级(字符、单词、行等)。conf:置信度(0-100)。left, top, width, height:边界框坐标。
import osdef batch_ocr(input_dir, output_file):results = []for filename in os.listdir(input_dir):if filename.endswith(('.png', '.jpg')):image_path = os.path.join(input_dir, filename)text = pytesseract.image_to_string(Image.open(image_path))results.append(f"{filename}:\n{text}\n")with open(output_file, 'w', encoding='utf-8') as f:f.write('\n'.join(results))batch_ocr('images/', 'output.txt')
从发票图像中提取关键字段(如金额、日期、发票号)。
def extract_invoice_data(image_path):img = cv2.imread(image_path)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 假设发票号位于左上角(50,50)到(200,100)区域invoice_no_region = gray[50:100, 50:200]invoice_no = pytesseract.image_to_string(invoice_no_region, config='--psm 7')# 假设金额位于右下角(300,400)到(500,450)区域amount_region = gray[400:450, 300:500]amount = pytesseract.image_to_string(amount_region, config='--psm 7')return {'invoice_no': invoice_no.strip(),'amount': amount.strip()}data = extract_invoice_data('invoice.png')print(data)
sudo apt install tesseract-ocr-chi-sim)。cv2.resize(img, (0,0), fx=0.5, fy=0.5))。lang='chi_sim'参数。simsun.ttc)。pytesseract通过简化Tesseract的调用流程,为Python开发者提供了高效的OCR解决方案。结合图像预处理与参数调优,可显著提升识别准确率。
通过本文的系统学习,开发者可快速掌握pytesseract的核心功能,并应用于实际项目中的文本提取场景。