# Copyright (c)2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0(the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=doc-string-missing
import requests
import json
import cv2
import base64
import re
from config_env.config_envi import common
class ImageOCR(object):
def __init__(self):
self.headers ={
"Content-type":"application/json"}
self.url ="http://%s/predict/chinese_ocr_db_crnn_mobile"% common['model_ip_port_server']
self.index =['姓名','性别','民族','出生','住址','公民身份号码','$']
def cv2_to_base64(self, image):
data = cv2.imencode('.jpg', image)[1]return base64.b64encode(data.tostring()).decode('utf8')
def ocr_image(self, img_path):
data ={
'images':[self.cv2_to_base64(cv2.imread(img_path))]}
r = requests.post(url=self.url, headers=self.headers, data=json.dumps(data))
res = r.json()["results"]
res_list =[]for txt in res[0]['data']:
res_list.append(txt['text'])
res_str =''.join(res_list)
res_dict ={
}for i in range(len(self.index)-1):
re_res = re.search(r'%s(.*?)%s'%(self.index[i], self.index[i +1]), res_str)
# print(re_res)
res_dict[self.index[i]]= re.sub(r'[\s。]','', re_res.group(1))if re_res else''return res_dict
if __name__ =='__main__':
image_ocr =ImageOCR()
test_img_path_ ="./11.jpg"print(image_ocr.ocr_image(test_img_path_))
2.2、测试案例request_post.py
# -*- coding: utf-8-*-import os
import requests
from config_env.config_envi import common
def ocr_Paddle(root, name):
# root ='E:\\png'
# name ='2.png'
file = os.path.join(root, name)
files_t ={
'file':(name,open(file,'rb'))}
headers ={
'File-Name': name}
r = requests.post("http://%s/nlp/v1/ocr/ocr_res"% common['model_ip_port_client'], files=files_t, headers=headers)print(eval(r.text))returneval(r.text)if __name__ =='__main__':ocr_Paddle('./','11.jpg')