前一段时间用到火车票OCR处理,因为要求不高就自己简单写了一个。首先是模型选择,初步对比了几个开源的OCR产品后,选择了百度的PaddleOCR。自己用Python开发了一个简单的数据结构化功能,并用Gradio写了一个简答的界面。效果如下(火车票图片来自于网络):
代码如下:
import gradio as gr
import os
import cv2
from PIL import Image
from paddleocr import PaddleOCR, draw_ocr
from IPython import display
import re
import numpy as np
import matplotlib.pyplot as plt
# 简单的数据结构化处理,主要思路就是利用关键字
def extract_train(result):
station=0
cc=0
output=[]
for line in result:
if '站' in line[1][0]:
if station==0:
output.append(['始发站',line[1][0]])
elif station==1:
output.append(['到站',line[1][0]])
station=station+1
if (line[1][0][0] in ['C','D','G','Z','T','K','L','A','Y'])&(len(line[1][0])==4):
output.append(['车次',line[1][0]])
if ('年' in line[1][0])&('月' in line[1][0])&('日' in line[1][0]):
output.append(['乘车时间',line[1][0]])
if '****' in line[1][0]:
output.append(['乘车人',line[1][0]])
if '¥' in line[1][0]:
output.append(['票价',line[1][0]])
if '售' in line[1][0]:
output.append(['售票处',line[1][0]])
return output
# OCR处理,包括OCR调用,简单结构化处理以及图像处理
def train_ticket(image,choice):
ocr = PaddleOCR(use_angle_cls=True, lang="ch",gpu=False)
result = ocr.ocr(image, cls=True)
extracted = extract_train(result)
boxes = [line[0] for line in result]
txts = [line[1][0] for line in result]
scores = [line[1][1] for line in result]
im_show = draw_ocr(image, boxes, txts, scores)
im_show = Image.fromarray(im_show)
return result,extracted,im_show
# Gradio界面
image = gr.Image(label="请上传车票图像")
result = gr.Textbox(label="原始内容")
extracted = gr.Textbox(label="结构化处理")
result_image = gr.Image(label="处理后图像")
demo = gr.Interface(fn=train_ticket, inputs=image, outputs=[result,extracted,result_image], api_name="ocr_ticket")
demo.launch()
运行后显示界面:
选择车票图片并点击submit后即可看到效果:
如果您觉得对您有帮主请点个关注,方便看其他内容,谢谢。
代码为本人原创,未经允许,不得转载。