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

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
文幕地方's avatar
文幕地方 已提交
19
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..')))
W
WenmuZhou 已提交
20 21 22 23 24 25

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'

import cv2
import numpy as np
import time
文幕地方's avatar
文幕地方 已提交
26
import json
W
WenmuZhou 已提交
27 28 29 30 31

import tools.infer.utility as utility
from ppocr.data import create_operators, transform
from ppocr.postprocess import build_post_process
from ppocr.utils.logging import get_logger
32
from ppocr.utils.utility import get_image_file_list, check_and_read
文幕地方's avatar
fix bug  
文幕地方 已提交
33
from ppocr.utils.visual import draw_rectangle
W
WenmuZhou 已提交
34
from ppstructure.utility import parse_args
W
WenmuZhou 已提交
35 36 37 38

logger = get_logger()


文幕地方's avatar
文幕地方 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
def build_pre_process_list(args):
    resize_op = {'ResizeTableImage': {'max_len': args.table_max_len, }}
    pad_op = {
        'PaddingTableImage': {
            'size': [args.table_max_len, args.table_max_len]
        }
    }
    normalize_op = {
        'NormalizeImage': {
            'std': [0.229, 0.224, 0.225] if
            args.table_algorithm not in ['TableMaster'] else [0.5, 0.5, 0.5],
            'mean': [0.485, 0.456, 0.406] if
            args.table_algorithm not in ['TableMaster'] else [0.5, 0.5, 0.5],
            'scale': '1./255.',
            'order': 'hwc'
        }
    }
    to_chw_op = {'ToCHWImage': None}
    keep_keys_op = {'KeepKeys': {'keep_keys': ['image', 'shape']}}
    if args.table_algorithm not in ['TableMaster']:
        pre_process_list = [
            resize_op, normalize_op, pad_op, to_chw_op, keep_keys_op
        ]
    else:
        pre_process_list = [
            resize_op, pad_op, normalize_op, to_chw_op, keep_keys_op
        ]
    return pre_process_list


W
WenmuZhou 已提交
69 70
class TableStructurer(object):
    def __init__(self, args):
文幕地方's avatar
文幕地方 已提交
71
        self.use_onnx = args.use_onnx
文幕地方's avatar
文幕地方 已提交
72 73 74 75 76
        pre_process_list = build_pre_process_list(args)
        if args.table_algorithm not in ['TableMaster']:
            postprocess_params = {
                'name': 'TableLabelDecode',
                "character_dict_path": args.table_char_dict_path,
文幕地方's avatar
文幕地方 已提交
77
                'merge_no_span_structure': args.merge_no_span_structure
W
WenmuZhou 已提交
78
            }
文幕地方's avatar
文幕地方 已提交
79 80 81 82
        else:
            postprocess_params = {
                'name': 'TableMasterLabelDecode',
                "character_dict_path": args.table_char_dict_path,
文幕地方's avatar
文幕地方 已提交
83 84
                'box_shape': 'pad',
                'merge_no_span_structure': args.merge_no_span_structure
W
WenmuZhou 已提交
85 86 87 88
            }

        self.preprocess_op = create_operators(pre_process_list)
        self.postprocess_op = build_post_process(postprocess_params)
W
WenmuZhou 已提交
89
        self.predictor, self.input_tensor, self.output_tensors, self.config = \
W
WenmuZhou 已提交
90
            utility.create_predictor(args, 'table', logger)
W
WenmuZhou 已提交
91 92

    def __call__(self, img):
文幕地方's avatar
文幕地方 已提交
93
        starttime = time.time()
W
WenmuZhou 已提交
94 95 96 97 98 99 100 101
        ori_im = img.copy()
        data = {'image': img}
        data = transform(data, self.preprocess_op)
        img = data[0]
        if img is None:
            return None, 0
        img = np.expand_dims(img, axis=0)
        img = img.copy()
文幕地方's avatar
文幕地方 已提交
102 103 104 105 106 107 108 109 110 111 112
        if self.use_onnx:
            input_dict = {}
            input_dict[self.input_tensor.name] = img
            outputs = self.predictor.run(self.output_tensors, input_dict)
        else:
            self.input_tensor.copy_from_cpu(img)
            self.predictor.run()
            outputs = []
            for output_tensor in self.output_tensors:
                output = output_tensor.copy_to_cpu()
                outputs.append(output)
W
WenmuZhou 已提交
113 114 115 116 117

        preds = {}
        preds['structure_probs'] = outputs[1]
        preds['loc_preds'] = outputs[0]

文幕地方's avatar
文幕地方 已提交
118 119 120 121 122 123
        shape_list = np.expand_dims(data[-1], axis=0)
        post_result = self.postprocess_op(preds, [shape_list])

        structure_str_list = post_result['structure_batch_list'][0]
        bbox_list = post_result['bbox_batch_list'][0]
        structure_str_list = structure_str_list[0]
文幕地方's avatar
文幕地方 已提交
124 125 126
        structure_str_list = [
            '<html>', '<body>', '<table>'
        ] + structure_str_list + ['</table>', '</body>', '</html>']
W
WenmuZhou 已提交
127
        elapse = time.time() - starttime
文幕地方's avatar
文幕地方 已提交
128
        return (structure_str_list, bbox_list), elapse
文幕地方's avatar
文幕地方 已提交
129 130


W
WenmuZhou 已提交
131 132 133 134 135
def main(args):
    image_file_list = get_image_file_list(args.image_dir)
    table_structurer = TableStructurer(args)
    count = 0
    total_time = 0
文幕地方's avatar
文幕地方 已提交
136 137 138 139 140
    os.makedirs(args.output, exist_ok=True)
    with open(
            os.path.join(args.output, 'infer.txt'), mode='w',
            encoding='utf-8') as f_w:
        for image_file in image_file_list:
141
            img, flag, _ = check_and_read(image_file)
文幕地方's avatar
文幕地方 已提交
142 143 144 145 146
            if not flag:
                img = cv2.imread(image_file)
            if img is None:
                logger.info("error in loading image:{}".format(image_file))
                continue
文幕地方's avatar
文幕地方 已提交
147 148
            structure_res, elapse = table_structurer(img)
            structure_str_list, bbox_list = structure_res
文幕地方's avatar
文幕地方 已提交
149 150 151 152 153 154
            bbox_list_str = json.dumps(bbox_list.tolist())
            logger.info("result: {}, {}".format(structure_str_list,
                                                bbox_list_str))
            f_w.write("result: {}, {}\n".format(structure_str_list,
                                                bbox_list_str))

文幕地方's avatar
文幕地方 已提交
155
            if len(bbox_list) > 0 and len(bbox_list[0]) == 4:
文幕地方's avatar
文幕地方 已提交
156
                img = draw_rectangle(image_file, bbox_list)
文幕地方's avatar
文幕地方 已提交
157 158
            else:
                img = utility.draw_boxes(img, bbox_list)
文幕地方's avatar
文幕地方 已提交
159 160 161 162 163 164 165 166
            img_save_path = os.path.join(args.output,
                                         os.path.basename(image_file))
            cv2.imwrite(img_save_path, img)
            logger.info("save vis result to {}".format(img_save_path))
            if count > 0:
                total_time += elapse
            count += 1
            logger.info("Predict time of {}: {}".format(image_file, elapse))
W
WenmuZhou 已提交
167 168 169


if __name__ == "__main__":
W
WenmuZhou 已提交
170
    main(parse_args())