PaddleOCR/tools/infer_rec.py

207 lines
8.6 KiB
Python
Raw Normal View History

2020-05-10 16:26:57 +08:00
# 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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
2020-10-13 17:13:33 +08:00
2020-06-12 13:49:24 +08:00
import os
import sys
2021-06-05 11:58:17 +08:00
import json
2020-10-13 17:13:33 +08:00
__dir__ = os.path.dirname(os.path.abspath(__file__))
2020-06-12 13:49:24 +08:00
sys.path.append(__dir__)
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "..")))
2020-05-10 16:26:57 +08:00
os.environ["FLAGS_allocator_strategy"] = "auto_growth"
2020-12-22 15:57:21 +08:00
2020-10-13 17:13:33 +08:00
import paddle
2020-06-02 19:03:27 +08:00
2020-10-13 17:13:33 +08:00
from ppocr.data import create_operators, transform
2020-11-09 16:40:24 +08:00
from ppocr.modeling.architectures import build_model
2020-10-13 17:13:33 +08:00
from ppocr.postprocess import build_post_process
from ppocr.utils.save_load import load_model
2020-11-09 16:40:24 +08:00
from ppocr.utils.utility import get_image_file_list
2020-10-13 17:13:33 +08:00
import tools.program as program
2020-05-10 16:26:57 +08:00
def main():
global_config = config["Global"]
2020-10-13 17:13:33 +08:00
# build post process
post_process_class = build_post_process(config["PostProcess"], global_config)
2020-10-13 17:13:33 +08:00
# build model
if hasattr(post_process_class, "character"):
char_num = len(getattr(post_process_class, "character"))
if config["Architecture"]["algorithm"] in [
"Distillation",
]: # distillation model
for key in config["Architecture"]["Models"]:
if (
config["Architecture"]["Models"][key]["Head"]["name"] == "MultiHead"
): # multi head
out_channels_list = {}
if config["PostProcess"]["name"] == "DistillationSARLabelDecode":
char_num = char_num - 2
if config["PostProcess"]["name"] == "DistillationNRTRLabelDecode":
char_num = char_num - 3
out_channels_list["CTCLabelDecode"] = char_num
out_channels_list["SARLabelDecode"] = char_num + 2
out_channels_list["NRTRLabelDecode"] = char_num + 3
config["Architecture"]["Models"][key]["Head"][
"out_channels_list"
] = out_channels_list
else:
config["Architecture"]["Models"][key]["Head"][
"out_channels"
] = char_num
elif config["Architecture"]["Head"]["name"] == "MultiHead": # multi head
out_channels_list = {}
char_num = len(getattr(post_process_class, "character"))
if config["PostProcess"]["name"] == "SARLabelDecode":
char_num = char_num - 2
if config["PostProcess"]["name"] == "NRTRLabelDecode":
char_num = char_num - 3
out_channels_list["CTCLabelDecode"] = char_num
out_channels_list["SARLabelDecode"] = char_num + 2
out_channels_list["NRTRLabelDecode"] = char_num + 3
config["Architecture"]["Head"]["out_channels_list"] = out_channels_list
2021-06-04 10:46:45 +08:00
else: # base rec model
config["Architecture"]["Head"]["out_channels"] = char_num
if config["Architecture"].get("algorithm") in ["LaTeXOCR"]:
config["Architecture"]["Backbone"]["is_predict"] = True
config["Architecture"]["Backbone"]["is_export"] = True
config["Architecture"]["Head"]["is_export"] = True
model = build_model(config["Architecture"])
2020-10-13 17:13:33 +08:00
load_model(config, model)
2020-10-13 17:13:33 +08:00
# create data ops
transforms = []
for op in config["Eval"]["dataset"]["transforms"]:
2020-10-13 17:13:33 +08:00
op_name = list(op)[0]
if "Label" in op_name:
2020-10-13 17:13:33 +08:00
continue
elif op_name in ["RecResizeImg"]:
op[op_name]["infer_mode"] = True
elif op_name == "KeepKeys":
if config["Architecture"]["algorithm"] == "SRN":
op[op_name]["keep_keys"] = [
"image",
"encoder_word_pos",
"gsrm_word_pos",
"gsrm_slf_attn_bias1",
"gsrm_slf_attn_bias2",
2020-12-30 16:15:49 +08:00
]
elif config["Architecture"]["algorithm"] == "SAR":
op[op_name]["keep_keys"] = ["image", "valid_ratio"]
elif config["Architecture"]["algorithm"] == "RobustScanner":
op[op_name]["keep_keys"] = ["image", "valid_ratio", "word_positons"]
2020-12-30 16:15:49 +08:00
else:
op[op_name]["keep_keys"] = ["image"]
2020-10-13 17:13:33 +08:00
transforms.append(op)
global_config["infer_mode"] = True
2020-10-13 17:13:33 +08:00
ops = create_operators(transforms, global_config)
save_res_path = config["Global"].get(
"save_res_path", "./output/rec/predicts_rec.txt"
)
2021-04-25 20:49:45 +08:00
if not os.path.exists(os.path.dirname(save_res_path)):
os.makedirs(os.path.dirname(save_res_path))
2020-10-13 17:13:33 +08:00
model.eval()
infer_imgs = config["Global"]["infer_img"]
infer_list = config["Global"].get("infer_list", None)
2021-04-25 20:49:45 +08:00
with open(save_res_path, "w") as fout:
for file in get_image_file_list(infer_imgs, infer_list=infer_list):
2021-04-25 20:49:45 +08:00
logger.info("infer_img: {}".format(file))
with open(file, "rb") as f:
2021-04-25 20:49:45 +08:00
img = f.read()
data = {"image": img}
2021-04-25 20:49:45 +08:00
batch = transform(data, ops)
if config["Architecture"]["algorithm"] == "SRN":
2021-04-25 20:49:45 +08:00
encoder_word_pos_list = np.expand_dims(batch[1], axis=0)
gsrm_word_pos_list = np.expand_dims(batch[2], axis=0)
gsrm_slf_attn_bias1_list = np.expand_dims(batch[3], axis=0)
gsrm_slf_attn_bias2_list = np.expand_dims(batch[4], axis=0)
others = [
paddle.to_tensor(encoder_word_pos_list),
paddle.to_tensor(gsrm_word_pos_list),
paddle.to_tensor(gsrm_slf_attn_bias1_list),
paddle.to_tensor(gsrm_slf_attn_bias2_list),
2021-04-25 20:49:45 +08:00
]
if config["Architecture"]["algorithm"] == "SAR":
2021-08-24 11:49:26 +08:00
valid_ratio = np.expand_dims(batch[-1], axis=0)
img_metas = [paddle.to_tensor(valid_ratio)]
if config["Architecture"]["algorithm"] == "RobustScanner":
2022-05-22 13:16:52 +08:00
valid_ratio = np.expand_dims(batch[1], axis=0)
word_positons = np.expand_dims(batch[2], axis=0)
2022-10-08 11:20:36 +08:00
img_metas = [
paddle.to_tensor(valid_ratio),
paddle.to_tensor(word_positons),
]
if config["Architecture"]["algorithm"] == "CAN":
2022-10-15 20:27:05 +08:00
image_mask = paddle.ones(
(np.expand_dims(batch[0], axis=0).shape), dtype="float32"
)
label = paddle.ones((1, 36), dtype="int64")
2021-04-25 20:49:45 +08:00
images = np.expand_dims(batch[0], axis=0)
images = paddle.to_tensor(images)
if config["Architecture"]["algorithm"] == "SRN":
2021-04-25 20:49:45 +08:00
preds = model(images, others)
elif config["Architecture"]["algorithm"] == "SAR":
2021-08-24 11:49:26 +08:00
preds = model(images, img_metas)
elif config["Architecture"]["algorithm"] == "RobustScanner":
2022-05-22 13:16:52 +08:00
preds = model(images, img_metas)
elif config["Architecture"]["algorithm"] == "CAN":
2022-10-15 20:27:05 +08:00
preds = model([images, image_mask, label])
2021-04-25 20:49:45 +08:00
else:
preds = model(images)
post_result = post_process_class(preds)
2021-06-05 11:58:17 +08:00
info = None
if isinstance(post_result, dict):
rec_info = dict()
for key in post_result:
if len(post_result[key][0]) >= 2:
rec_info[key] = {
"label": post_result[key][0][0],
"score": float(post_result[key][0][1]),
2021-06-05 11:58:17 +08:00
}
2022-05-04 22:57:57 +08:00
info = json.dumps(rec_info, ensure_ascii=False)
elif isinstance(post_result, list) and isinstance(post_result[0], int):
# for RFLearning CNT branch
2022-10-08 11:20:36 +08:00
info = str(post_result[0])
elif config["Architecture"]["algorithm"] == "LaTeXOCR":
info = str(post_result[0])
2021-06-05 11:58:17 +08:00
else:
if len(post_result[0]) >= 2:
info = post_result[0][0] + "\t" + str(post_result[0][1])
if info is not None:
logger.info("\t result: {}".format(info))
fout.write(file + "\t" + info + "\n")
2020-10-13 17:13:33 +08:00
logger.info("success!")
2020-05-10 16:26:57 +08:00
if __name__ == "__main__":
2020-11-09 16:40:24 +08:00
config, device, logger, vdl_writer = program.preprocess()
2020-05-10 16:26:57 +08:00
main()