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

import os
import sys
import subprocess

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
W
WenmuZhou 已提交
21
sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
W
WenmuZhou 已提交
22 23 24 25 26

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
import cv2
import numpy as np
import time
W
WenmuZhou 已提交
27 28 29

import layoutparser as lp

W
WenmuZhou 已提交
30 31
from ppocr.utils.utility import get_image_file_list, check_and_read_gif
from ppocr.utils.logging import get_logger
W
WenmuZhou 已提交
32 33 34
from tools.infer.predict_system import TextSystem
from ppstructure.table.predict_table import TableSystem, to_excel
from ppstructure.utility import parse_args
W
WenmuZhou 已提交
35 36 37 38

logger = get_logger()


W
WenmuZhou 已提交
39
class OCRSystem(object):
W
WenmuZhou 已提交
40 41
    def __init__(self, args):
        self.text_system = TextSystem(args)
W
WenmuZhou 已提交
42 43 44 45
        self.table_system = TableSystem(args, self.text_system.text_detector, self.text_system.text_recognizer)
        self.table_layout = lp.PaddleDetectionLayoutModel("lp://PubLayNet/ppyolov2_r50vd_dcn_365e_publaynet/config",
                                                          threshold=0.5, enable_mkldnn=args.enable_mkldnn,
                                                          enforce_cpu=not args.use_gpu)
W
WenmuZhou 已提交
46 47 48 49 50
        self.use_angle_cls = args.use_angle_cls
        self.drop_score = args.drop_score

    def __call__(self, img):
        ori_im = img.copy()
W
WenmuZhou 已提交
51 52
        layout_res = self.table_layout.detect(img[..., ::-1])
        res_list = []
W
WenmuZhou 已提交
53
        for region in layout_res:
W
WenmuZhou 已提交
54 55
            x1, y1, x2, y2 = region.coordinates
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
W
WenmuZhou 已提交
56
            roi_img = ori_im[y1:y2, x1:x2, :]
W
WenmuZhou 已提交
57 58 59 60
            if region.type == 'Table':
                res = self.table_system(roi_img)
            elif region.type == 'Figure':
                continue
W
WenmuZhou 已提交
61
            else:
W
WenmuZhou 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
                filter_boxes, filter_rec_res = self.text_system(roi_img)
                filter_boxes = [x.reshape(-1).tolist() for x in filter_boxes]
                res = (filter_boxes, filter_rec_res)
            res_list.append({'type': region.type, 'bbox': [x1, y1, x2, y2], 'res': res})
        return res_list


def save_res(res, save_folder, img_name):
    excel_save_folder = os.path.join(save_folder, img_name)
    os.makedirs(excel_save_folder, exist_ok=True)
    # save res
    for region in res:
        if region['type'] == 'Table':
            excel_path = os.path.join(excel_save_folder, '{}.xlsx'.format(region['bbox']))
            to_excel(region['res'], excel_path)
        elif region['type'] == 'Figure':
            pass
        else:
            with open(os.path.join(excel_save_folder, 'res.txt'), 'a', encoding='utf8') as f:
                for box, rec_res in zip(*region['res']):
                    f.write('{}\t{}\n'.format(np.array(box).reshape(-1).tolist(), rec_res))
W
WenmuZhou 已提交
83 84 85 86


def main(args):
    image_file_list = get_image_file_list(args.image_dir)
W
WenmuZhou 已提交
87
    image_file_list = image_file_list
W
WenmuZhou 已提交
88
    image_file_list = image_file_list[args.process_id::args.total_process_num]
W
WenmuZhou 已提交
89
    save_folder = args.output
W
WenmuZhou 已提交
90
    os.makedirs(save_folder, exist_ok=True)
W
WenmuZhou 已提交
91

W
WenmuZhou 已提交
92
    structure_sys = OCRSystem(args)
W
WenmuZhou 已提交
93 94 95 96
    img_num = len(image_file_list)
    for i, image_file in enumerate(image_file_list):
        logger.info("[{}/{}] {}".format(i, img_num, image_file))
        img, flag = check_and_read_gif(image_file)
W
WenmuZhou 已提交
97
        img_name = os.path.basename(image_file).split('.')[0]
W
WenmuZhou 已提交
98

W
WenmuZhou 已提交
99 100 101
        if not flag:
            img = cv2.imread(image_file)
        if img is None:
W
WenmuZhou 已提交
102
            logger.error("error in loading image:{}".format(image_file))
W
WenmuZhou 已提交
103 104
            continue
        starttime = time.time()
W
WenmuZhou 已提交
105 106 107
        res = structure_sys(img)
        save_res(res, save_folder, img_name)
        logger.info('result save to {}'.format(os.path.join(save_folder, img_name)))
W
WenmuZhou 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        elapse = time.time() - starttime
        logger.info("Predict time : {:.3f}s".format(elapse))


if __name__ == "__main__":
    args = parse_args()
    if args.use_mp:
        p_list = []
        total_process_num = args.total_process_num
        for process_id in range(total_process_num):
            cmd = [sys.executable, "-u"] + sys.argv + [
                "--process_id={}".format(process_id),
                "--use_mp={}".format(False)
            ]
            p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout)
            p_list.append(p)
        for p in p_list:
            p.wait()
    else:
        main(args)