Document

python--easyocr安装提速教程

很多人使用easyocr的时候,识别很慢,一次差不多13秒。

其实是可以提速的

就说美不美

# 基础安装
pip install easyocr opencv-python

# 如需GPU支持(需先安装CUDA 11.8+)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

或者

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

安装完成之后,测试一下,是否gpu安装成功

import torch
print(torch.cuda.is_available()) # Should output `True`

安装好之后,我们来优化代码,GPU加速

reader = easyocr.Reader(['en'], gpu=True)  # 必须安装CUDA环境

批量处理

# 同时处理多张图片
batch_results = reader.readtext_batch([img1, img2, img3])

压缩图片

# 调整图像尺寸(保持宽高比)
img = cv2.resize(img, None, fx=0.5, fy=0.5) # 缩小50%

选择模型

reader = easyocr.Reader(model_storage_directory='custom_models/')  # 自定义轻量模型

需要再优化速度的,可以配置下面的内容

reader.readtext(img,
  batch_size=4, # 增大批处理量
  decoder='beamsearch', # 快速解码模式
  beamWidth=5, # 平衡速度与精度
  width_ths=0.8, # 放宽合并阈值
  height_ths=0.8
)

最终优化代码

def safe_resize(img, scale_factor=0.5):
"""安全的图像缩放函数"""
if img is None:
raise ValueError("输入图像为空!")

# 计算新尺寸(确保整数)
new_w = int(img.shape[1] * scale_factor)
new_h = int(img.shape[0] * scale_factor)
img_resized=cv2.resize(img, dsize=(new_w, new_h),interpolation=cv2.INTER_AREA)
# 使用明确的尺寸参数
return img_resized, (new_w, new_h)

 
def text_images(image_path):

print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
img = cv2.imread(image_path)
if img is None:
print(f"错误:无法读取图片 {image_path}")
return []
try:
# 安全缩放(可选)
img_resized, (new_w, new_h) = safe_resize(img, 0.5) # 缩放系数改为0.5
# OCR识别
reader = easyocr.Reader(['ch_sim'],gpu=True,model_storage_directory='custom_models/')
results = reader.readtext(img_resized)

# 坐标还原到原图尺寸
scale_x = img.shape[1] / new_w
scale_y = img.shape[0] / new_h

formatted = []
for (bbox, text, conf) in results:
# 缩放坐标回原始尺寸
original_bbox = [(int(x * scale_x), int(y * scale_y)) for (x, y) in bbox]
formatted.append({'text': text, 'bbox': original_bbox, 'confidence': conf})
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
return formatted

except Exception as e:
print(f"OCR处理失败: {str(e)}")
return []
 
有问题留言即可

 

posted on 2025-03-17 17:06  小排顾  阅读(556)  评论(0)    收藏  举报

导航