wb.ouyang

毕竟几人真得鹿,不知终日梦为鱼

导航

Tesseract-OCR下载和安装,Python-OCR使用

Tesseract-OCR下载和安装,Python-OCR使用

Tesseract-OCR下载:https://digi.bib.uni-mannheim.de/tesseract/

 

智能体,输入图片,识别图片文本,然后输出指定的结构化数据

我将为您创建一个基于Python的图片文本识别系统,使用Tesseract OCR引擎将图片中的文本提取并转换为结构化数据。以下是完整实现:


## 步骤
    使用Pillow库处理图像输入,Tesseract OCR引擎进行文本识别
    包含原始文本提取和结构化数据处理两个主要功能
    示例结构化处理识别日期、金额和项目名称等常见信息
    结果输出为JSON格式,便于进一步处理和使用
    需要安装Tesseract OCR引擎并配置系统路径

## 安装说明:
    首先安装Tesseract OCR:https://github.com/tesseract-ocr/tesseract
    然后通过pip安装Python依赖:pip install -r requirements.txt
    运行程序:python image_ocr.py

 

image_ocr.py

import pytesseract
from PIL import Image
import re
import json
import argparse

class ChineseOCRProcessor:
    def __init__(self):
        self.lang_config = 'chi_sim+eng'  # 中英文混合识别
        self.preprocess_params = {
            'threshold': 128,
            'sharpness': 2.0
        }

    def preprocess_image(self, img_path):
        """图像预处理流水线"""
        img = Image.open(img_path)
        img = img.convert('L')  # 灰度化
        img = img.point(lambda x: 0 if x < self.preprocess_params['threshold'] else 255)  # 二值化
        return img

    def extract_text(self, img_path):
        """执行OCR识别"""
        processed_img = self.preprocess_image(img_path)
        text = pytesseract.image_to_string(
            processed_img,
            lang=self.lang_config,
            config='--psm 6 --oem 3'
        )
        return text.strip()

    def structure_data(self, raw_text):
        """结构化数据提取规则"""
        patterns = {
            'dates': r'\d{4}[-年]\d{1,2}[-月]\d{1,2}[日]?|\d{1,2}/\d{1,2}/\d{4}',
            'amounts': r'[¥$]\s*\d+(?:,\d{3})*(?:\.\d{2})?|\d+\s*元',
            'chinese_entities': r'[\u4e00-\u9fa5]{2,4}(?:公司|集团|中心|银行)'
        }
        
        structured = {}
        for field, pattern in patterns.items():
            structured[field] = re.findall(pattern, raw_text)
        return structured

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("image_path", help="待识别图片路径")
    parser.add_argument("-o", "--output", help="输出文件路径", default="output.json")
    args = parser.parse_args()

    # 导入ocr安装路径,如果设置了系统环境,就可以不用设置了
    pytesseract.pytesseract.tesseract_cmd=r"D:\studio\Tesseract-OCR\tesseract.exe"

    processor = ChineseOCRProcessor()
    text = processor.extract_text(args.image_path)
    print("识别的文本:" + text)
    result = processor.structure_data(text)
    
    with open(args.output, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=2, ensure_ascii=False)
    print(f"识别结果已保存至 {args.output}")
View Code

ocr_test.py

import pytesseract
from PIL import Image

def ocr_test():
    # 导入ocr安装路径,如果设置了系统环境,就可以不用设置了
    pytesseract.pytesseract.tesseract_cmd=r"D:\studio\Tesseract-OCR\tesseract.exe"

    image = Image.open("d:/a.jpg")
    text = pytesseract.image_to_string(image, lang = 'chi_sim')
    print(text)

if __name__ == '__main__':
    ocr_test()
View Code

 

posted on 2025-09-25 00:07  wenbin_ouyang  阅读(157)  评论(0)    收藏  举报