diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/LICENSE b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a40d2cafc5d0f94c3a3e41707922f1d92cb890b --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 Guillaume Chevalier and Yu Zhao + + 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. diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/README.md b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a62a8f8c5e2d9d603244aeddfdceccd3cf8a9d4a --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/README.md @@ -0,0 +1,52 @@ +## 模型功能 + + 对Rebar的tensorflow模型的输出进行解析, 使用固化后outom1021.om模型进行推理。 + +## 原始模型 + +参考实现 : +``` +https://gitee.com/ascend/ModelZoo-TensorFlow/tree/master/TensorFlow/contrib/cv/Rebar_ID2016_for_TensorFlow +``` + + +原始ckpt模型网络下载地址 : +``` +链接:https://pan.baidu.com/s/1sWukTQUzzdbqWbjqwkjhHg +提取码:1111 + +``` +原始pb模型网络下载地址 : +``` +链接:https://pan.baidu.com/s/1cK8-e22Oi4zIl7Sc_U1qmg +提取码:1111 +``` + + +## om模型 + +om模型网络下载地址 : +``` +链接:https://pan.baidu.com/s/14wHs1QrGirvdmoICWnlniQ +提取码:1111 +``` + +使用ATC模型转换工具进行模型转换时可以参考如下指令: + +``` +atc --model=./frozen_model1025.pb --framework=3 --input_shape="Placeholder_1:12,784" --output=./outom1021 --soc_version=Ascend910 +``` + +## 使用msame工具推理 + +参考 https://gitee.com/ascend/tools/tree/master/msame, 获取msame推理工具及使用方法。 + +## 性能测试 + +使用msame推理工具,参考如下命令,发起推理性能测试: + +``` +./msame --model "./outom1021.om" --input "/home/TestUser01/Pycode/rebar_npu/img2bin/bin" --output "./output" --outfmt TXT --loop 5 +``` + + diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/ckpt2pb.py b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/ckpt2pb.py new file mode 100644 index 0000000000000000000000000000000000000000..f165fd162fb44076dff89f76c91b6f6501e5e208 --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/ckpt2pb.py @@ -0,0 +1,126 @@ +## Copyright 2021 Huawei Technologies Co., Ltd +# +# 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 multiprocessing.heap import rebuild_arena +import tensorflow as tf +from tensorflow.python.tools import freeze_graph +from npu_bridge.estimator import npu_ops +from tensorflow.python.framework import graph_util +from ops import * +from data import * +from utils import * +from datasets import * +import rebar +import rebar_train +import numpy as np +import datasets +#添加导入NPU库的头文件 +import npu_bridge +from npu_bridge.npu_init import * +from npu_bridge.estimator.npu import util +from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig +from rebar_train import eval + + +config = tf.ConfigProto() +# keras迁移添加内容 +custom_op = config.graph_options.rewrite_options.custom_optimizers.add() +custom_op.name = "NpuOptimizer" +custom_op.parameter_map["use_off_line"].b = True +config.graph_options.rewrite_options.memory_optimization = RewriterConfig.OFF +config.graph_options.rewrite_options.remapping = RewriterConfig.OFF # 必须显示关闭remap + +batch_size = 12 + +#dataset = DataSet("./train.txt", 30, batch_size) + +ckpt_path = "./root/rebar/data/output.trial_1/model.ckpt-2000847" + +def main(): + tf.reset_default_graph() + inputs1 = tf.placeholder(tf.float32, [None,1,784 ], name="input1") + FLAGS = tf.flags.FLAGS + hparams = rebar.default_hparams + hparams.parse(FLAGS.hparams) + print(hparams.values()) + train_xs, valid_xs, test_xs = datasets.load_data(hparams) + print(train_xs.shape) + mean_xs = np.mean(train_xs, axis=0) # Compute mean centering on training + + #training_steps = 2000000 + model = getattr(rebar, hparams.model) + sbn = model(hparams, mean_xs) + n_samples = 100 + + + #c_logits = net.conditioning_logits + #p_logits = net.prior_logits + #c_logits1, c_logits2 = tf.identity(sbn._create_train_op, name='c_logits1, c_logits2') + with tf.Session(config=config) as sess: + sbn.initialize(sess) + batch_xs = valid_xs[0:24] + #c_logits = sbn.partial_eval(batch_xs, n_samples) + graph_def = tf.get_default_graph().as_graph_def(add_shapes=True) + node_list = [n.name for n in graph_def.node] + for node in node_list: + print("node_name", node) + tf.train.write_graph(sess.graph_def, './pb_model1021', 'model.pb') + freeze_graph.freeze_graph( + input_graph='./pb_model/model.pb', + input_saver='', + input_binary=False, + input_checkpoint=ckpt_path, + output_node_names='Mean_11', + restore_op_name='save/restore_all', + filename_tensor_name='save/Const:0', + output_graph='./pb_model1021/rebar1021.pb', + clear_devices=False, + initializer_nodes='') + print("done") + +if __name__ == '__main__': + main() + +''' + + +def freeze_graph(input_checkpoint,output_graph): + + # checkpoint = tf.train.get_checkpoint_state(model_folder) #检查目录下ckpt文件状态是否可用 + # input_checkpoint = checkpoint.model_checkpoint_path #得ckpt文件路径 + + # 指定输出的节点名称,该节点名称必须是原模型中存在的节点 + # 直接用最后输出的节点,可以在tensorboard中查找到,tensorboard只能在linux中使用 + output_node_names = "cond_1/Merge" + saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True) + graph = tf.get_default_graph() # 获得默认的图 + input_graph_def = graph.as_graph_def() # 返回一个序列化的图代表当前的图 + + with tf.Session() as sess: + saver.restore(sess, input_checkpoint) #恢复图并得到数据 + output_graph_def = graph_util.convert_variables_to_constants( # 模型持久化,将变量值固定 + sess=sess, + input_graph_def=input_graph_def,# 等于:sess.graph_def + output_node_names=output_node_names.split(","))# 如果有多个输出节点,以逗号隔开 + + with tf.gfile.GFile(output_graph, "wb") as f: #保存模型 + f.write(output_graph_def.SerializeToString()) #序列化输出 + print("%d ops in the final graph." % len(output_graph_def.node)) #得到当前图有几个操作节点 + +# input_checkpoint='inceptionv1/model.ckpt-0' +# out_pb_path='inceptionv1/frozen_model.pb' + +input_checkpoint='./output/model.ckpt-280000' +out_pb_path='frozen_model.pb' +freeze_graph(input_checkpoint, out_pb_path) +''' \ No newline at end of file diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/img2bin.py b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/img2bin.py new file mode 100644 index 0000000000000000000000000000000000000000..d8551eb3954a5a150df7c288aee5ffdbfacc922f --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/img2bin.py @@ -0,0 +1,316 @@ +# -*- coding: UTF-8 -*- +# +# ======================================================================= +# +# Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1 Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2 Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3 Neither the names of the copyright holders nor the names of the +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# ======================================================================= +#Copyright 2021 Huawei Technologies Co., Ltd +# +# 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 print_function +import argparse +import os +import sys +import json +# import getpass + +IMG_EXT = ['.jpg', '.JPG', '.png', '.PNG', '.bmp', '.BMP', '.jpeg', '.JPEG'] + +try: + import cv2 as cv +except ImportError: + if sys.version_info.major == 2: + confirm = raw_input("[info] Begin to install opencv-python, input[Y/N]:") + else: + confirm = input("[info] Begin to install opencv-python, input[Y/N]:") + + if confirm == 'Y' or confirm == 'y': + print('[info] Starting to install opencv-python...') + if sys.version_info.major == 2: + import commands + retu, output = commands.getstatusoutput("sudo yum install -y opencv-python") + if retu != 0: + retu, output = commands.getstatusoutput("sudo apt-get install -y python-opencv") + if retu != 0: + print('[ERROR] install opencv-python failed,please check env.') + exit(0) + else: + retu = os.system('sudo python3 -m pip install opencv-python') + if retu != 0: + print('[ERROR] install opencv-python failed,please check env.') + exit(0) + + import cv2 as cv + else: + print("[info] The installation has been cancled.") + exit(0) + +try: + import numpy as np +except ImportError: + if sys.version_info.major == 2: + os.system('pip2 install numpy') + else: + os.system('python3 -m pip install numpy') + import numpy as np + +def get_args(): + parser = argparse.ArgumentParser( + conflict_handler='resolve', + description='''eg1: python2 img2bin.py + -i ./images -w 416 -h 416 -f BGR -a NHWC -t uint8 -m [104,117,123] -c [1,1,1] -o ./out + eg2: python2 img2bin.py -i ./test.txt -t uint8 -o ./out''') + parser.add_argument('-i', '--input', required=True, type=str, \ + help='folder of input image or file of other input.') + parser.add_argument('-w', '--width', required=True, type=int, \ + help='resized image width before inference.') + parser.add_argument('-h', '--height', required=True, type=int, \ + help='resized image height before inference.') + parser.add_argument('-f', '--output_image_format', default='BGR', type=str, \ + help='output image format in (BGR/RGB/YUV/GRAY).') + parser.add_argument('-a', '--output_format', default='NCHW', type=str, \ + help='output format in (NCHW/NHWC).') + parser.add_argument('-t', '--output_type', required=True, type=str, \ + help='output type in (float32/uint8/int32/uint32).') + parser.add_argument('-m', '--mean', default='[0, 0, 0]', \ + help='reduce mean for each channel.') + parser.add_argument('-c', '--coefficient', default='[1, 1, 1]', \ + help='multiplying coefficients for each channel.') + parser.add_argument('-o', '--output', default='./', \ + help='output path.') + return parser.parse_args() + + +def eprint(*args, **kwargs): + """print error message to stderr + """ + print(*args, file=sys.stderr, **kwargs) + + +def check_args(args): + """ + check console parameters according to restrictions. + return: True or False + """ + check_flag = True + is_dir = True + if os.path.isdir(args.input): + if not os.listdir(args.input): + eprint('[ERROR] input image path=%r is empty.' % args.input) + check_flag = False + elif os.path.isfile(args.input): + is_dir = False + else: + eprint('[ERROR] input path=%r does not exist.' % args.input) + check_flag = False + if args.output_image_format not in ('BGR','RGB', 'YUV', 'GRAY'): + eprint("[ERROR] Convert to %d is not support." % (args.output_image_format)) + check_flag = False + if args.height <= 0 or args.width <= 0: + eprint("[ERROR] image height or image width must be greater than 0.") + check_flag = False + elif args.output_image_format == 'YUV': + if args.width % 2 == 1 or args.height % 2 == 1: + eprint("[ERROR] when the output color format is YUV, the width and height of the picture must be even.") + check_flag = False + return check_flag, is_dir + + +def convert_img_2_yuv(input_img): + input_img_height = input_img.shape[0] + input_img_width = input_img.shape[1] + bgr2y_list = np.array([29, 150, 77]) + bgr2y_data = input_img.reshape(input_img_height * input_img_width, 3) + y_data = np.dot(bgr2y_data, bgr2y_list) >> 8 + bgr2u_list = np.array([131, -87, -44]) + bgr2v_list = np.array([-21, -110, 131]) + bgr2uv_matrix = np.transpose(np.append(bgr2u_list, bgr2v_list).reshape((2, 3))) + bgr2uv_data = input_img[0::2, 0::2, :].reshape((input_img_height // 2 * input_img_width // 2, 3)) + yuv_base_data = np.dot(bgr2uv_data, bgr2uv_matrix) >> 8 + u_data = yuv_base_data[:,0] + 128 + v_data = yuv_base_data[:,1] + 128 + u_v_data = np.transpose(np.append(u_data.flatten(), v_data.flatten()).reshape((2, input_img_height //2 * input_img_width // 2))) + nv12_data = np.append(y_data.flatten(), u_v_data.flatten()).reshape((input_img_height // 2 * 3, input_img_width)).astype(np.uint8) + return nv12_data + + +def convert_img(args, input_img): + if args.output_image_format == 'BGR': + converted_input_img = input_img + elif args.output_image_format == 'RGB': + converted_input_img = cv.cvtColor(input_img, cv.COLOR_BGR2RGB) + elif args.output_image_format == 'YUV': + converted_input_img = convert_img_2_yuv(input_img) + elif args.output_image_format == 'GRAY': + converted_input_img = cv.cvtColor(input_img, cv.COLOR_BGR2GRAY) + return converted_input_img + + +def resize_img(args, input_img): + old_size = input_img.shape[0:2] + target_size = [args.height, args.width] + ratio = min(float(target_size[i]) / (old_size[i]) for i in range(len(old_size))) + new_size = tuple([int(i*ratio) for i in old_size]) + img_new = cv.resize(input_img,(new_size[1], new_size[0])) + pad_w = target_size[1] - new_size[1] + pad_h = target_size[0] - new_size[0] + top, bottom = pad_h // 2, pad_h - (pad_h // 2) + left, right = pad_w // 2, pad_w - (pad_w // 2) + resized_img = cv.copyMakeBorder(img_new, top, bottom, left, right, cv.BORDER_CONSTANT, None,(0, 0, 0)) + return resized_img + + +def change_type(args, input_img): + if args.output_type == 'float32': + change_type_img = input_img.astype(np.float32) + elif args.output_type == 'int32': + change_type_img = input_img.astype(np.int32) + elif args.output_type == 'uint32': + change_type_img = input_img.astype(np.uint32) + else: + change_type_img = input_img.astype(np.uint8) + return change_type_img + + +def mean(args, input_img): + if isinstance (args.mean, str): + args.mean = json.loads(args.mean) + input_img = input_img.astype(np.float32) + if args.output_image_format == 'GRAY': + input_img[:, :] -= args.mean[0] + elif args.output_image_format in ('BGR', 'RGB'): + input_img[:, :, 0] -= args.mean[0] + input_img[:, :, 1] -= args.mean[1] + input_img[:, :, 2] -= args.mean[2] + return input_img + + +def coefficient(args, input_img): + """ + Normalize the input image + """ + if isinstance(args.coefficient, str): + args.coefficient = json.loads(args.coefficient) + input_img = input_img.astype(np.float32) + if args.output_image_format == 'GRAY': + input_img[:, :] *= args.coefficient[0] + elif args.output_image_format in ('BGR', 'RGB'): + input_img[:, :, 0] *= args.coefficient[0] + input_img[:, :, 1] *= args.coefficient[1] + input_img[:, :, 2] *= args.coefficient[2] + return input_img + + +def change_format(args, input_img): + if args.output_format == 'NCHW': + if args.output_image_format in ('RGB', 'BGR'): + change_format_img = input_img.transpose(2,0,1).copy() + return change_format_img + return input_img + + +def mkdir_output(args): + if not os.path.exists(args.output): + os.makedirs(args.output) + return + + +def process(args, file_path): + if file_path.endswith(".txt"): + if sys.version_info.major == 2: + import ConfigParser as configparser + else: + import configparser + + config = configparser.ConfigParser() + config.read(file_path) + if sys.version_info.major == 2: + input_node = json.loads(config.get('baseconf', 'input_node')) + shape = json.loads(config.get('baseconf', 'shape')) + else: + input_node = json.loads(config['baseconf']['input_node']) + shape = json.loads(config['baseconf']['shape']) + input_node_np = np.array(input_node) + change_type_img_info = change_type(args, input_node_np) + img_info = np.reshape(change_type_img_info, shape) + out_path = os.path.join(args.output, os.path.splitext(os.path.split(file_path)[1])[0] + ".bin") + mkdir_output(args) + img_info.tofile(out_path) + else: + input_img = cv.imread(file_path) + resized_img1 = resize_img(args, input_img) + converted_img = convert_img(args, resized_img1) + if args.output_image_format == "YUV": + change_format_img = converted_img + else: + mean_img = mean(args, converted_img) + coefficient_img = coefficient(args, mean_img) + change_type_img = change_type(args, coefficient_img) + change_format_img = change_format(args, change_type_img) + out_path = os.path.join(args.output, os.path.splitext(os.path.split(file_path)[1])[0] + ".bin") + mkdir_output(args) + change_format_img.tofile(out_path) + + +def main(): + """main function to receive params them change data to bin. + """ + args = get_args() + ret, is_dir = check_args(args) + if ret: + if is_dir: + files_name = os.listdir(args.input) + for file_name in files_name: + if os.path.splitext(file_name)[1] in IMG_EXT: + file_path = os.path.join(args.input, file_name) + process(args, file_path) + print("[info] bin file generated successfully.") + else: + if os.path.splitext(args.input)[1] in IMG_EXT or os.path.splitext(args.input)[1] == "txt": + process(args, args.input) + print("[info] bin file generated successfully.") + else: + eprint("[ERROR] input file must be image or end with '.txt'.") + +if __name__ == '__main__': + main() + + + + diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/modelzoo_level.txt b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/modelzoo_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f4eeb699cb9bfd53ef6361efe5807c90ff799c8 --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/modelzoo_level.txt @@ -0,0 +1,6 @@ +ModelConvert:OK +QuantStatus:NOK +FuncStatus:OK +PrecisionStatus:OK +AutoTune:NOK +PerfStatus:NOK diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/msame b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/msame new file mode 100644 index 0000000000000000000000000000000000000000..5647e05a02c561a05fa71c512cf58872ffc6e366 Binary files /dev/null and b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/msame differ diff --git a/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/pb2om.sh b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/pb2om.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f89fee3539db3d013a6e559872a05d73951d961 --- /dev/null +++ b/ACL_TensorFlow/contrib/cv/Rebar_ID2016_for_ACL/pb2om.sh @@ -0,0 +1 @@ +atc --model=./frozen_model1025.pb --framework=3 --input_shape="Placeholder_1:12,784" --output=./outom1021 --soc_version=Ascend910 \ No newline at end of file