1. 搭建环境
1)安装Python环境
2)安装paddlepaddle、paddleocr 、PIL库;
2. 源码
from paddleocr import PaddleOCR,draw_ocr
from PIL import Image
import os
def ocr_recognition(img_path,saved_path):
# ocr 模型加载两种情况
# 1.离线ocr识别
ocr = PaddleOCR(det_model_dir = './inference/ch_PP-OCRv4_det_infer/',
rec_model_dir = './inference/ch_PP-OCRv4_rec_infer/',
cls_model_dir = './inference/ch_ppocr_mobile_v2.0_cls_infer/',
use_angle_cls = True,
use_gpu = False)
# 2.连网时下载ocr识别所需模型
# ocr = PaddleOCR(use_angle_cls = True, use_gpu = False)
# 获取识别结果
result = ocr.ocr(img_path,cls = True)
boxes = [line[0] for line in result[0]]
txts = [line[1][0] for line in result[0]]
scores = [line[1][1] for line in resul[0]]
# 将结果以图像形式保存
image = Image.open(img_path).convert('RGB')
img_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/simfang.ttf')
img_show = Image.formarray(img_show)
img_show.save(saved_path)
if __name__ == '__main__':
img_path = 'test.jpg' # 测试图片路径
saved_path = 'test_out.jpg' # 识别保存路径
ocr_recognition(img_path, saved_path)
3. 识别效果
原图
识别效果图