ocr_web_server.py 3.8 KB
Newer Older
W
wangjiawei04 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 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.

from paddle_serving_client import Client
from paddle_serving_app.reader import OCRReader
import cv2
import sys
import numpy as np
import os
from paddle_serving_client import Client
from paddle_serving_app.reader import Sequential, URL2Image, ResizeByFactor
from paddle_serving_app.reader import Div, Normalize, Transpose
24
from paddle_serving_app.reader import DBPostProcess, FilterBoxes, GetRotateCropImage, SortedBoxes
W
wangjiawei04 已提交
25 26 27
from paddle_serving_server_gpu.web_service import WebService
import time
import re
28
import base64
W
wangjiawei04 已提交
29

W
wangjiawei04 已提交
30

W
wangjiawei04 已提交
31 32 33 34 35 36 37 38 39 40
class OCRService(WebService):
    def init_det_client(self, det_port, det_client_config):
        self.det_preprocess = Sequential([
            ResizeByFactor(32, 960), Div(255),
            Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), Transpose(
                (2, 0, 1))
        ])
        self.det_client = Client()
        self.det_client.load_client_config(det_client_config)
        self.det_client.connect(["127.0.0.1:{}".format(det_port)])
41
        self.ocr_reader = OCRReader()
W
wangjiawei04 已提交
42 43

    def preprocess(self, feed=[], fetch=[]):
44 45 46
        data = base64.b64decode(feed[0]["image"].encode('utf8'))
        data = np.fromstring(data, np.uint8)
        im = cv2.imdecode(data, cv2.IMREAD_COLOR)
W
wangjiawei04 已提交
47 48 49
        ori_h, ori_w, _ = im.shape
        det_img = self.det_preprocess(im)
        det_out = self.det_client.predict(
W
wangjiawei04 已提交
50
            feed={"image": det_img}, fetch=["concat_1.tmp_0"])
W
wangjiawei04 已提交
51 52 53 54 55 56 57 58 59
        _, new_h, new_w = det_img.shape
        filter_func = FilterBoxes(10, 10)
        post_func = DBPostProcess({
            "thresh": 0.3,
            "box_thresh": 0.5,
            "max_candidates": 1000,
            "unclip_ratio": 1.5,
            "min_size": 3
        })
60
        sorted_boxes = SortedBoxes()
W
wangjiawei04 已提交
61 62 63 64
        ratio_list = [float(new_h) / ori_h, float(new_w) / ori_w]
        dt_boxes_list = post_func(det_out["concat_1.tmp_0"], [ratio_list])
        dt_boxes = filter_func(dt_boxes_list[0], [ori_h, ori_w])
        dt_boxes = sorted_boxes(dt_boxes)
65
        get_rotate_crop_image = GetRotateCropImage()
W
wangjiawei04 已提交
66 67 68 69 70 71 72 73 74 75
        feed_list = []
        img_list = []
        max_wh_ratio = 0
        for i, dtbox in enumerate(dt_boxes):
            boximg = get_rotate_crop_image(im, dt_boxes[i])
            img_list.append(boximg)
            h, w = boximg.shape[0:2]
            wh_ratio = w * 1.0 / h
            max_wh_ratio = max(max_wh_ratio, wh_ratio)
        for img in img_list:
76
            norm_img = self.ocr_reader.resize_norm_img(img, max_wh_ratio)
W
wangjiawei04 已提交
77 78
            feed = {"image": norm_img}
            feed_list.append(feed)
79
        fetch = ["ctc_greedy_decoder_0.tmp_0", "softmax_0.tmp_0"]
W
wangjiawei04 已提交
80 81 82
        return feed_list, fetch

    def postprocess(self, feed={}, fetch=[], fetch_map=None):
83
        rec_res = self.ocr_reader.postprocess(fetch_map, with_score=True)
W
wangjiawei04 已提交
84 85 86
        res_lst = []
        for res in rec_res:
            res_lst.append(res[0])
87 88
        res = {"res": res_lst}
        return res
W
wangjiawei04 已提交
89 90 91 92 93 94 95 96 97 98


ocr_service = OCRService(name="ocr")
ocr_service.load_model_config("ocr_rec_model")
ocr_service.prepare_server(workdir="workdir", port=9292)
ocr_service.init_det_client(
    det_port=9293,
    det_client_config="ocr_det_client/serving_client_conf.prototxt")
ocr_service.run_rpc_service()
ocr_service.run_web_service()