最近接到一个需求:需要从邮件中自动下载某些邮件的附件,而这些附件是经过加密的压缩包,解压码在对应的图片中,所以需要自动识别图片中的解压码,然后去解压文件。

经过各种调研,对比了几种OCR,最后选定了EasyOCR,轻量、识别率高、开源免费!
1. 简介
EasyOCR 是一个用 Python 编写的 OCR(光学字符识别)库,支持 80+ 种语言的文字识别。它具有以下特点:
-
使用简单,仅需几行代码即可完成文字识别 -
支持多种语言,包括中文、英文、日文等 -
基于 PyTorch 深度学习框架 -
支持 GPU 加速 -
完全开源,可以自由使用

2. 环境准备
2.1 系统要求
-
Python 3.6+ -
PyTorch 1.7.0+
2.2 安装步骤
# 使用 pip 安装
pip install easyocr
# 如果需要支持 GPU,请确保已安装 CUDA
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
3. 基础使用
3.1 简单示例
import easyocr
# 初始化读取器
reader = easyocr.Reader(['ch_sim','en']) # 这里选择中文简体和英文
# 读取图像
result = reader.readtext('image.jpg')
# 输出结果
for (bbox, text, prob) in result:
print(f'识别文本: {text}')
print(f'置信度: {prob}')
3.2 高级参数配置
result = reader.readtext(
'image.jpg',
detail = 0, # 设置为 0 只返回文本,坐标和置信度会隐藏
paragraph = True, # 将临近文本合并为段落
min_size = 10, # 最小文本框大小
contrast_ths = 0.15, # 对比度阈值
adjust_contrast = 0.5, # 对比度调整
text_threshold = 0.7, # 文本检测阈值
low_text = 0.4, # 文本检测低阈值
link_threshold = 0.4, # 文本行连接阈值
)
4. 实践应用场景
4.1 与 Web 应用集成或者对外提供API


对外提供API:

部分代码如下:
from flask import Flask, request, jsonify, render_template, json
import easyocr
import numpy as np
from PIL import Image
app = Flask(__name__)
reader = easyocr.Reader(['ch_sim','en'])
@app.route('/', methods=['GET'])
def index():
pass
@app.route('/ocr', methods=['POST'])
def ocr_endpoint():
try:
if'image'notin request.files:
return jsonify({'error': 'No image provided'}), 400
image = request.files['image']
img = Image.open(image)
result = reader.readtext(np.array(img))
processed_result = []
current_line = []
current_line_boxes = []
sorted_result = sorted(result, key=lambda x: (x[0][0][1] + x[0][2][1]) / 2)
y_threshold = 10
for i, (bbox, text, prob) in enumerate(sorted_result):
current_y = (bbox[0][1] + bbox[2][1]) / 2
ifnot current_line:
current_line.append((bbox, text))
current_line_boxes.append(bbox)
else:
prev_y = (current_line[0][0][0][1] + current_line[0][0][2][1]) / 2
if abs(current_y - prev_y) <= y_threshold:
current_line.append((bbox, text))
current_line_boxes.append(bbox)
else:
current_line.sort(key=lambda x: x[0][0][0])
processed_result.append({
'text': ' '.join(item[1] for item in current_line)
})
current_line = [(bbox, text)]
current_line_boxes = [bbox]
if current_line:
current_line.sort(key=lambda x: x[0][0][0])
processed_result.append({
'text': ' '.join(item[1] for item in current_line)
})
response = app.response_class(
response=json.dumps(
{'result': processed_result},
ensure_ascii=False,
indent=2
),
status=200,
mimetype='application/json'
)
return response
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
5. 性能优化建议
-
GPU 加速
-
在有 GPU 的环境下,确保正确安装 CUDA 和对应版本的 PyTorch -
首次运行时会自动下载模型,建议预先下载 -
内存优化
-
处理大量图片时,注意及时释放内存 -
可以使用生成器进行批量处理 -
图像预处理
-
对图像进行适当的预处理可以提高识别准确率 -
考虑使用图像增强技术,如对比度调整、去噪等
6. 常见问题解决
-
内存不足
-
降低处理图片的分辨率 -
使用批处理时减小批次大小
识别准确率不高
-
调整识别参数 -
优化图像质量 -
考虑使用特定语言模型
个人觉得EasyOCR 是一个功能强大且易用的 OCR 工具,适合各种文字识别场景,如果你也遇到需要和我一样的需求场景,也可以试试。

