如何编写OCR简易脚本

wen 实用脚本 33

本文目录导读:

如何编写OCR简易脚本

  1. 使用Tesseract(最简单,适合中文)
  2. 使用百度OCR API(需要API Key)
  3. 使用EasyOCR(支持多种语言)
  4. 完整的GUI界面(使用tkinter)
  5. 命令行工具版本
  6. 安装依赖
  7. 优化建议

我来介绍几种编写简易OCR脚本的方法,从简单到复杂:

使用Tesseract(最简单,适合中文)

安装依赖

# macOS
brew install tesseract
brew install tesseract-lang  # 中文语言包
# Ubuntu/Debian
sudo apt-get install tesseract-ocr
sudo apt-get install tesseract-ocr-chi-sim  # 简体中文包
# Windows 下载安装包:https://github.com/UB-Mannheim/tesseract/wiki

Python脚本示例

import pytesseract
from PIL import Image
import cv2
import numpy as np
def simple_ocr(image_path):
    # 读取图片
    img = cv2.imread(image_path)
    # 预处理(提高识别率)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
    # OCR识别
    text = pytesseract.image_to_string(
        thresh, 
        lang='chi_sim+eng',  # 中英文混合
        config='--psm 6'     # 假设为统一的文本块
    )
    return text.strip()
# 使用示例
result = simple_ocr('image.png')
print(result)

使用百度OCR API(需要API Key)

import requests
import base64
def baidu_ocr(image_path):
    # 获取access_token
    client_id = '你的API Key'
    client_secret = '你的Secret Key'
    token_url = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret
    }
    response = requests.post(token_url, params=params)
    access_token = response.json().get('access_token')
    # OCR识别
    with open(image_path, 'rb') as f:
        image_data = base64.b64encode(f.read()).decode('utf-8')
    ocr_url = f'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={access_token}'
    data = {
        'image': image_data,
        'language_type': 'CHN_ENG'  # 中英文混合
    }
    response = requests.post(ocr_url, data=data)
    result = response.json()
    # 提取文本
    if 'words_result' in result:
        text = '\n'.join([item['words'] for item in result['words_result']])
        return text
    return ''
# 使用示例
result = baidu_ocr('image.png')
print(result)

使用EasyOCR(支持多种语言)

import easyocr
def easy_ocr(image_path):
    # 创建OCR对象
    reader = easyocr.Reader(['ch_sim', 'en'])  # 中英文
    # 识别图片
    result = reader.readtext(image_path)
    # 提取文本
    text = '\n'.join([item[1] for item in result])
    return text
# 使用示例
result = easy_ocr('image.png')
print(result)

完整的GUI界面(使用tkinter)

import tkinter as tk
from tkinter import filedialog, messagebox
import pytesseract
from PIL import Image, ImageTk
import cv2
import numpy as np
class OCRApp:
    def __init__(self, root):
        self.root = root
        self.root.title("简易OCR工具")
        self.root.geometry("800x600")
        # 界面元素
        self.setup_ui()
    def setup_ui(self):
        # 选择文件按钮
        self.btn_select = tk.Button(
            self.root, 
            text="选择图片", 
            command=self.select_image
        )
        self.btn_select.pack(pady=10)
        # 图片预览
        self.image_label = tk.Label(self.root, text="图片预览区域")
        self.image_label.pack(pady=10)
        # 识别结果
        self.result_text = tk.Text(self.root, height=10, width=80)
        self.result_text.pack(pady=10)
        # 识别按钮
        self.btn_ocr = tk.Button(
            self.root, 
            text="开始识别", 
            command=self.perform_ocr
        )
        self.btn_ocr.pack(pady=10)
    def select_image(self):
        file_path = filedialog.askopenfilename(
            filetypes=[("Image files", "*.png *.jpg *.jpeg *.bmp")]
        )
        if file_path:
            self.image_path = file_path
            # 显示缩略图
            img = Image.open(file_path)
            img.thumbnail((400, 300))
            photo = ImageTk.PhotoImage(img)
            self.image_label.config(image=photo)
            self.image_label.image = photo
    def perform_ocr(self):
        if hasattr(self, 'image_path'):
            try:
                # 读取图片并OCR
                img = cv2.imread(self.image_path)
                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
                text = pytesseract.image_to_string(
                    thresh, 
                    lang='chi_sim+eng'
                )
                # 显示结果
                self.result_text.delete(1.0, tk.END)
                self.result_text.insert(1.0, text.strip())
            except Exception as e:
                messagebox.showerror("错误", str(e))
        else:
            messagebox.showwarning("提示", "请先选择图片")
# 运行应用
if __name__ == "__main__":
    root = tk.Tk()
    app = OCRApp(root)
    root.mainloop()

命令行工具版本

# ocr_cli.py
import argparse
import pytesseract
from PIL import Image
def main():
    parser = argparse.ArgumentParser(description='简易OCR工具')
    parser.add_argument('image', help='图片文件路径')
    parser.add_argument('--lang', default='chi_sim+eng', help='识别语言')
    parser.add_argument('--output', help='输出文件路径')
    args = parser.parse_args()
    # 执行OCR
    text = pytesseract.image_to_string(
        Image.open(args.image),
        lang=args.lang
    )
    if args.output:
        with open(args.output, 'w', encoding='utf-8') as f:
            f.write(text)
        print(f"结果已保存到: {args.output}")
    else:
        print(text)
if __name__ == '__main__':
    main()

使用命令行:

python ocr_cli.py image.png --lang chi_sim+eng --output result.txt

安装依赖

# 基本依赖
pip install pillow opencv-python
pip install pytesseract  # 需要先安装Tesseract
pip install easyocr      # EasyOCR方式
pip install requests     # API方式

优化建议

  1. 图片预处理

    • 转换为灰度图
    • 二值化处理
    • 去噪点
    • 倾斜校正
  2. 提高识别率

    • 裁剪图片,只保留文字区域
    • 调整对比度和亮度
    • 使用适当的PSM模式
  3. 错误处理

    • 添加异常捕获
    • 验证输入图片
    • 处理编码问题

选择哪种方法取决于你的具体需求:

  • 本地简单使用:Tesseract
  • 需要高精度:百度OCR API
  • 多语言支持:EasyOCR
  • 批量处理:命令行版本

抱歉,评论功能暂时关闭!