diff --git a/model_zoo/official/cv/FCN8s/README.md b/model_zoo/official/cv/FCN8s/README.md index c8ff04dd32e..de221605fbc 100644 --- a/model_zoo/official/cv/FCN8s/README.md +++ b/model_zoo/official/cv/FCN8s/README.md @@ -12,6 +12,10 @@ - [训练](#训练) - [评估步骤](#评估步骤) - [评估](#评估) + - [导出过程](#导出过程) + - [导出](#导出) + - [推理过程](#推理过程) + - [推理](#推理) - [模型介绍](#模型介绍) - [性能](#性能) - [评估性能](#评估性能) @@ -71,10 +75,12 @@ Dataset used: ├── README.md // descriptions about all the models ├── FCN8s ├── README.md // descriptions about FCN + ├── ascend310_infer // 实现310推理源代码 ├── scripts ├── run_train.sh ├── run_standalone_train.sh ├── run_eval.sh + ├── run_infer_310.sh // Ascend推理shell脚本 ├── build_data.sh ├── src │ ├──data @@ -93,6 +99,8 @@ Dataset used: │ ├──moxing_adapter.py // Decorator ├── default_config.yaml // Parameters config ├── train.py // training script + ├── postprogress.py // 310推理后处理脚本 + ├── export.py // 将checkpoint文件导出到air/mindir ├── eval.py // evaluation script ``` @@ -271,6 +279,33 @@ Dataset used: mean IoU 0.6467 ``` +## 导出过程 + +### 导出 + +在导出之前需要修改default_config.yaml配置文件中的ckpt_file配置项,file_name和file_format配置项根据情况修改. + +```shell +python export.py +``` + +## 推理过程 + +### 推理 + +在还行推理之前我们需要先导出模型。Air模型只能在昇腾910环境上导出,mindir可以在任意环境上导出。batch_size只支持1。 + + ```shell + # Ascend310 inference + bash run_infer_310.sh [MINDIR_PATH] [DATA_LIST_FILE] [IMAGE_PATH] [MASK_PATH] [DEVICE_ID] + ``` + +推理的结果保存在当前目录下,在acc.log日志文件中可以找到类似以下的结果。 + + ```python + mean IoU 0.0.64519877 + ``` + # [模型介绍](#contents) ## [性能](#contents) diff --git a/model_zoo/official/cv/FCN8s/ascend310_infer/CMakeLists.txt b/model_zoo/official/cv/FCN8s/ascend310_infer/CMakeLists.txt new file mode 100644 index 00000000000..ee3c8544734 --- /dev/null +++ b/model_zoo/official/cv/FCN8s/ascend310_infer/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.14.1) +project(Ascend310Infer) +add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g -std=c++17 -Werror -Wall -fPIE -Wl,--allow-shlib-undefined") +set(PROJECT_SRC_ROOT ${CMAKE_CURRENT_LIST_DIR}/) +option(MINDSPORE_PATH "mindspore install path" "") +include_directories(${MINDSPORE_PATH}) +include_directories(${MINDSPORE_PATH}/include) +include_directories(${PROJECT_SRC_ROOT}) +find_library(MS_LIB libmindspore.so ${MINDSPORE_PATH}/lib) +file(GLOB_RECURSE MD_LIB ${MINDSPORE_PATH}/_c_dataengine*) + +add_executable(main src/main.cc src/utils.cc) +target_link_libraries(main ${MS_LIB} ${MD_LIB} gflags) diff --git a/model_zoo/official/cv/FCN8s/ascend310_infer/build.sh b/model_zoo/official/cv/FCN8s/ascend310_infer/build.sh new file mode 100644 index 00000000000..285514e19f2 --- /dev/null +++ b/model_zoo/official/cv/FCN8s/ascend310_infer/build.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# 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. +# ============================================================================ +if [ -d out ]; then + rm -rf out +fi + +mkdir out +cd out || exit + +if [ -f "Makefile" ]; then + make clean +fi + +cmake .. \ + -DMINDSPORE_PATH="`pip3.7 show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`" +make diff --git a/model_zoo/official/cv/FCN8s/ascend310_infer/inc/utils.h b/model_zoo/official/cv/FCN8s/ascend310_infer/inc/utils.h new file mode 100644 index 00000000000..974dc95a4bb --- /dev/null +++ b/model_zoo/official/cv/FCN8s/ascend310_infer/inc/utils.h @@ -0,0 +1,33 @@ +/** + * 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. + */ + +#ifndef MINDSPORE_INFERENCE_UTILS_H_ +#define MINDSPORE_INFERENCE_UTILS_H_ + +#include +#include +#include +#include +#include +#include "include/api/types.h" + +std::vector GetAllFiles(std::string_view dirName); +std::vector GetImagesById(const std::string &idFIle, const std::string &dirName); +DIR *OpenDir(std::string_view dirName); +std::string RealPath(std::string_view path); +mindspore::MSTensor ReadFileToTensor(const std::string &file); +int WriteResult(const std::string& imageFile, const std::vector &outputs); +#endif diff --git a/model_zoo/official/cv/FCN8s/ascend310_infer/src/main.cc b/model_zoo/official/cv/FCN8s/ascend310_infer/src/main.cc new file mode 100644 index 00000000000..07760205b0f --- /dev/null +++ b/model_zoo/official/cv/FCN8s/ascend310_infer/src/main.cc @@ -0,0 +1,223 @@ +/** + * 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. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "include/api/context.h" +#include "include/api/model.h" +#include "include/api/types.h" +#include "include/api/serialization.h" +#include "include/dataset/vision.h" +#include "include/dataset/execute.h" +#include "../inc/utils.h" + +using mindspore::Context; +using mindspore::Serialization; +using mindspore::Model; +using mindspore::Status; +using mindspore::ModelType; +using mindspore::GraphCell; +using mindspore::kSuccess; +using mindspore::MSTensor; +using mindspore::DataType; +using mindspore::dataset::Execute; +using mindspore::dataset::TensorTransform; +using mindspore::dataset::vision::Resize; +using mindspore::dataset::vision::Pad; +using mindspore::dataset::vision::HWC2CHW; +using mindspore::dataset::vision::Normalize; +using mindspore::dataset::vision::SwapRedBlue; +using mindspore::dataset::vision::Decode; + + +DEFINE_string(mindir_path, "", "mindir path"); +DEFINE_string(image_list, "", "image list"); +DEFINE_string(dataset_path, ".", "dataset path"); +DEFINE_int32(device_id, 0, "device id"); + +const int IMAGEWIDTH = 512; +const int IMAGEHEIGHT = 512; + +int PadImage(const MSTensor &input, MSTensor *output) { + std::shared_ptr normalize(new Normalize({103.53, 116.28, 123.675}, + {57.375, 57.120, 58.395})); + Execute composeNormalize({normalize}); + std::vector shape = input.Shape(); + auto imgResize = MSTensor(); + auto imgNormalize = MSTensor(); + + float widthScale, heightScale; + widthScale = static_cast(IMAGEWIDTH) / shape[1]; + heightScale = static_cast(IMAGEHEIGHT) / shape[0]; + Status ret; + if (widthScale < heightScale) { + int heightSize = shape[0]*widthScale; + std::shared_ptr resize(new Resize({heightSize, IMAGEWIDTH})); + Execute composeResizeWidth({resize}); + ret = composeResizeWidth(input, &imgResize); + if (ret != kSuccess) { + std::cout << "ERROR: Resize Width failed." << std::endl; + return 1; + } + + ret = composeNormalize(imgResize, &imgNormalize); + if (ret != kSuccess) { + std::cout << "ERROR: Normalize failed." << std::endl; + return 1; + } + + int paddingSize = IMAGEHEIGHT - heightSize; + std::shared_ptr pad(new Pad({0, 0, 0, paddingSize})); + Execute composePad({pad}); + ret = composePad(imgNormalize, output); + if (ret != kSuccess) { + std::cout << "ERROR: Height Pad failed." << std::endl; + return 1; + } + } else { + int widthSize = shape[1]*heightScale; + std::shared_ptr resize(new Resize({IMAGEHEIGHT, widthSize})); + Execute composeResizeHeight({resize}); + ret = composeResizeHeight(input, &imgResize); + if (ret != kSuccess) { + std::cout << "ERROR: Resize Height failed." << std::endl; + return 1; + } + + ret = composeNormalize(imgResize, &imgNormalize); + if (ret != kSuccess) { + std::cout << "ERROR: Normalize failed." << std::endl; + return 1; + } + + int paddingSize = IMAGEWIDTH - widthSize; + std::shared_ptr pad(new Pad({0, 0, paddingSize, 0})); + Execute composePad({pad}); + ret = composePad(imgNormalize, output); + if (ret != kSuccess) { + std::cout << "ERROR: Width Pad failed." << std::endl; + return 1; + } + } + return 0; +} + +int main(int argc, char **argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + if (RealPath(FLAGS_mindir_path).empty()) { + std::cout << "Invalid mindir" << std::endl; + return 1; + } + + auto context = std::make_shared(); + auto ascend310 = std::make_shared(); + ascend310->SetDeviceID(FLAGS_device_id); + ascend310->SetPrecisionMode("allow_fp32_to_fp16"); + context->MutableDeviceInfo().push_back(ascend310); + mindspore::Graph graph; + Serialization::Load(FLAGS_mindir_path, ModelType::kMindIR, &graph); + + Model model; + Status ret = model.Build(GraphCell(graph), context); + if (ret != kSuccess) { + std::cout << "ERROR: Build failed." << std::endl; + return 1; + } + std::vector model_inputs = model.GetInputs(); + if (model_inputs.empty()) { + std::cout << "Invalid model, inputs is empty." << std::endl; + return 1; + } + + auto all_files = GetImagesById(FLAGS_image_list, FLAGS_dataset_path); + if (all_files.empty()) { + std::cout << "ERROR: no input data." << std::endl; + return 1; + } + + std::map costTime_map; + size_t size = all_files.size(); + std::shared_ptr decode(new Decode()); + Execute composeDecode({decode}); + std::shared_ptr hwc2chw(new HWC2CHW()); + Execute composeTranspose({hwc2chw}); + + for (size_t i = 0; i < size; ++i) { + struct timeval start = {0}; + struct timeval end = {0}; + double startTimeMs; + double endTimeMs; + std::vector inputs; + std::vector outputs; + std::string file = all_files[i] + ".jpg"; + std::cout << "Start predict input files:" << file << std::endl; + auto imgDecode = MSTensor(); + + auto image = ReadFileToTensor(file); + ret = composeDecode(image, &imgDecode); + if (ret != kSuccess) { + std::cout << "ERROR: Decode failed." << std::endl; + return 1; + } + auto imgPad = MSTensor(); + PadImage(imgDecode, &imgPad); + auto img = MSTensor(); + composeTranspose(imgPad, &img); + + inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(), + img.Data().get(), img.DataSize()); + + gettimeofday(&start, nullptr); + ret = model.Predict(inputs, &outputs); + gettimeofday(&end, nullptr); + if (ret != kSuccess) { + std::cout << "Predict " << file << " failed." << std::endl; + return 1; + } + startTimeMs = (1.0 * start.tv_sec * 1000000 + start.tv_usec) / 1000; + endTimeMs = (1.0 * end.tv_sec * 1000000 + end.tv_usec) / 1000; + costTime_map.insert(std::pair(startTimeMs, endTimeMs)); + WriteResult(file, outputs); + } + double average = 0.0; + int inferCount = 0; + + for (auto iter = costTime_map.begin(); iter != costTime_map.end(); iter++) { + double diff = 0.0; + diff = iter->second - iter->first; + average += diff; + inferCount++; + } + average = average / inferCount; + std::stringstream timeCost; + timeCost << "NN inference cost average time: "<< average << " ms of infer_count " << inferCount << std::endl; + std::cout << "NN inference cost average time: "<< average << "ms of infer_count " << inferCount << std::endl; + + std::string fileName = "./time_Result" + std::string("/test_perform_static.txt"); + std::ofstream fileStream(fileName.c_str(), std::ios::trunc); + fileStream << timeCost.str(); + fileStream.close(); + costTime_map.clear(); + return 0; +} diff --git a/model_zoo/official/cv/FCN8s/ascend310_infer/src/utils.cc b/model_zoo/official/cv/FCN8s/ascend310_infer/src/utils.cc new file mode 100644 index 00000000000..f4dffa4ab28 --- /dev/null +++ b/model_zoo/official/cv/FCN8s/ascend310_infer/src/utils.cc @@ -0,0 +1,145 @@ +/** + * 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. + */ + +#include +#include +#include +#include "../inc/utils.h" + +using mindspore::MSTensor; +using mindspore::DataType; + +std::vector GetAllFiles(std::string_view dirName) { + struct dirent *filename; + DIR *dir = OpenDir(dirName); + if (dir == nullptr) { + return {}; + } + std::vector res; + while ((filename = readdir(dir)) != nullptr) { + std::string dName = std::string(filename->d_name); + if (dName == "." || dName == ".." || filename->d_type != DT_REG) { + continue; + } + res.emplace_back(std::string(dirName) + "/" + filename->d_name); + } + std::sort(res.begin(), res.end()); + for (auto &f : res) { + std::cout << "image file: " << f << std::endl; + } + return res; +} + +std::vector GetImagesById(const std::string &idFile, const std::string &dirName) { + std::ifstream readFile(idFile); + std::string id; + std::vector result; + + if (!readFile.is_open()) { + std::cout << "can not open image id txt file" << std::endl; + return result; + } + + while (getline(readFile, id)) { + result.emplace_back(dirName + "/" + id); + } + + return result; +} + +int WriteResult(const std::string& imageFile, const std::vector &outputs) { + std::string homePath = "./result_Files"; + for (size_t i = 0; i < outputs.size(); ++i) { + size_t outputSize; + std::shared_ptr netOutput; + netOutput = outputs[i].Data(); + outputSize = outputs[i].DataSize(); + int pos = imageFile.rfind('/'); + std::string fileName(imageFile, pos + 1); + fileName.replace(fileName.find('.'), fileName.size() - fileName.find('.'), '_' + std::to_string(i) + ".bin"); + std::string outFileName = homePath + "/" + fileName; + FILE * outputFile = fopen(outFileName.c_str(), "wb"); + fwrite(netOutput.get(), outputSize, sizeof(char), outputFile); + fclose(outputFile); + outputFile = nullptr; + } + return 0; +} + +MSTensor ReadFileToTensor(const std::string &file) { + if (file.empty()) { + std::cout << "Pointer file is nullptr" << std::endl; + return MSTensor(); + } + + std::ifstream ifs(file); + if (!ifs.good()) { + std::cout << "File: " << file << " is not exist" << std::endl; + return MSTensor(); + } + + if (!ifs.is_open()) { + std::cout << "File: " << file << "open failed" << std::endl; + return MSTensor(); + } + + ifs.seekg(0, std::ios::end); + size_t size = ifs.tellg(); + MSTensor buffer(file, mindspore::DataType::kNumberTypeUInt8, {static_cast(size)}, nullptr, size); + + ifs.seekg(0, std::ios::beg); + ifs.read(reinterpret_cast(buffer.MutableData()), size); + ifs.close(); + + return buffer; +} + +DIR *OpenDir(std::string_view dirName) { + if (dirName.empty()) { + std::cout << " dirName is null ! " << std::endl; + return nullptr; + } + std::string realPath = RealPath(dirName); + struct stat s; + lstat(realPath.c_str(), &s); + if (!S_ISDIR(s.st_mode)) { + std::cout << "dirName is not a valid directory !" << std::endl; + return nullptr; + } + DIR *dir; + dir = opendir(realPath.c_str()); + if (dir == nullptr) { + std::cout << "Can not open dir " << dirName << std::endl; + return nullptr; + } + std::cout << "Successfully opened the dir " << dirName << std::endl; + return dir; +} + +std::string RealPath(std::string_view path) { + char realPathMem[PATH_MAX] = {0}; + char *realPathRet = nullptr; + realPathRet = realpath(path.data(), realPathMem); + + if (realPathRet == nullptr) { + std::cout << "File: " << path << " is not exist."; + return ""; + } + + std::string realPath(realPathMem); + std::cout << path << " realpath is: " << realPath << std::endl; + return realPath; +} diff --git a/model_zoo/official/cv/FCN8s/default_config.yaml b/model_zoo/official/cv/FCN8s/default_config.yaml index b0468554e2c..645dc8fb2b1 100644 --- a/model_zoo/official/cv/FCN8s/default_config.yaml +++ b/model_zoo/official/cv/FCN8s/default_config.yaml @@ -52,6 +52,10 @@ flip: False freeze_bn: False ckpt_file: "/data/mjq/ckpt/FCN8s_1-133_300.ckpt" +# ====================================================================================== +# Export options +file_name: "fcn8s" +file_format: MINDIR --- # Help description for each configuration @@ -82,4 +86,6 @@ eval_batch_size: "eval batch size" data_lst: "list of val data" scales: "scales of evaluation" flip: "freeze bn" -ckpt_file: "model to evaluate" \ No newline at end of file +ckpt_file: "model to evaluate" +file_name: "export file name" +file_format: "export model type" \ No newline at end of file diff --git a/model_zoo/official/cv/FCN8s/export.py b/model_zoo/official/cv/FCN8s/export.py new file mode 100644 index 00000000000..0cdac6a6dee --- /dev/null +++ b/model_zoo/official/cv/FCN8s/export.py @@ -0,0 +1,37 @@ +# 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. +# ============================================================================ +"""export FCN8s.""" + +import numpy as np + +import mindspore as ms +from mindspore import Tensor +from mindspore import context +from mindspore.train.serialization import load_checkpoint, load_param_into_net, export +from src.nets.FCN8s import FCN8s +from src.model_utils.config import config +from src.model_utils.device_adapter import get_device_id + +context.set_context(mode=context.GRAPH_MODE, device_target=config.device_target, device_id=get_device_id()) + +if __name__ == '__main__': + net = FCN8s(n_class=config.num_classes) + + # load model + param_dict = load_checkpoint(config.ckpt_file) + load_param_into_net(net, param_dict) + + input_arr = Tensor(np.zeros([1, 3, config.crop_size, config.crop_size]), ms.float32) + export(net, input_arr, file_name=config.file_name, file_format=config.file_format) diff --git a/model_zoo/official/cv/FCN8s/postprocess.py b/model_zoo/official/cv/FCN8s/postprocess.py new file mode 100644 index 00000000000..23ffb7c1be4 --- /dev/null +++ b/model_zoo/official/cv/FCN8s/postprocess.py @@ -0,0 +1,78 @@ +# 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. +# ============================================================================ +"""post process for 310 inference""" + +import os +import argparse +import numpy as np +import cv2 +from PIL import Image + +parser = argparse.ArgumentParser(description="FasterRcnn inference") +parser.add_argument("--image_list", type=str, required=True, help="result file path.") +parser.add_argument("--result_path", type=str, required=True, help="result file path.") +parser.add_argument("--data_path", type=str, required=True, help="mask file path.") +parser.add_argument("--mask_path", type=str, required=True, help="mask file path.") +args = parser.parse_args() + +NUM_CLASSES = 21 + +def get_img_size(file_name): + img = Image.open(file_name) + return img.size + +def get_resized_size(org_h, org_w, long_size=512): + if org_h > org_w: + new_h = long_size + new_w = int(1.0 * long_size * org_w / org_h) + else: + new_w = long_size + new_h = int(1.0 * long_size * org_h / org_w) + + return new_h, new_w + +def cal_hist(a, b, n): + k = (a >= 0) & (a < n) + return np.bincount(n * a[k].astype(np.int32) + b[k], minlength=n ** 2).reshape(n, n) + +def cal_acc(image_list, data_path, result_path, mask_path): + hist = np.zeros((NUM_CLASSES, NUM_CLASSES)) + with open(image_list) as f: + img_list = f.readlines() + + for img in img_list: + img_file = os.path.join(data_path, img.strip() + ".jpg") + org_width, org_height = get_img_size(img_file) + + resize_h, resize_w = get_resized_size(org_height, org_width) + + result_file = os.path.join(result_path, img.strip() + "_0.bin") + result = np.fromfile(result_file, dtype=np.float32).reshape(21, 512, 512) + probs_ = result[:, :resize_h, :resize_w].transpose((1, 2, 0)) + probs_ = cv2.resize(probs_.astype(np.float32), (org_width, org_height)) + result_msk = probs_.argmax(axis=2) + + mask_file = os.path.join(mask_path, img.strip() + ".png") + mask = np.array(Image.open(mask_file), dtype=np.uint8) + + hist += cal_hist(mask.flatten(), result_msk.flatten(), NUM_CLASSES) + + #print(hist) + iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist)) + print('per-class IoU', iu) + print('mean IoU', np.nanmean(iu)) + +if __name__ == '__main__': + cal_acc(args.image_list, args.data_path, args.result_path, args.mask_path) diff --git a/model_zoo/official/cv/FCN8s/scripts/run_infer_310.sh b/model_zoo/official/cv/FCN8s/scripts/run_infer_310.sh new file mode 100755 index 00000000000..b49bda4aa2f --- /dev/null +++ b/model_zoo/official/cv/FCN8s/scripts/run_infer_310.sh @@ -0,0 +1,108 @@ +#!/bin/bash +# 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. +# ============================================================================ + +if [[ $# -lt 4 || $# -gt 5 ]]; then + echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [DATA_LIST_FILE] [IMAGE_PATH] [MASK_PATH] [DEVICE_ID] + DEVICE_ID is optional, it can be set by environment variable device_id, otherwise the value is zero" +exit 1 +fi + +get_real_path(){ + if [ "${1:0:1}" == "/" ]; then + echo "$1" + else + echo "$(realpath -m $PWD/$1)" + fi +} + +model=$(get_real_path $1) +data_list_file=$(get_real_path $2) +image_path=$(get_real_path $3) +mask_path=$(get_real_path $4) + +device_id=0 +if [ $# == 5 ]; then + device_id=$5 +elif [ $# == 4 ]; then + if [ ! -z $device_id ]; then + device_id=$device_id + fi +fi + +echo $model +echo $image_path +echo $mask_path +echo $device_id + +export ASCEND_HOME=/usr/local/Ascend/ +if [ -d ${ASCEND_HOME}/ascend-toolkit ]; then + export PATH=$ASCEND_HOME/fwkacllib/bin:$ASCEND_HOME/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/atc/bin:$PATH + export LD_LIBRARY_PATH=$ASCEND_HOME/fwkacllib/lib64:/usr/local/lib:$ASCEND_HOME/ascend-toolkit/latest/atc/lib64:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/lib64:$ASCEND_HOME/driver/lib64:$ASCEND_HOME/add-ons:$LD_LIBRARY_PATH + export TBE_IMPL_PATH=$ASCEND_HOME/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe + export PYTHONPATH=$ASCEND_HOME/fwkacllib/python/site-packages:${TBE_IMPL_PATH}:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/python/site-packages:$PYTHONPATH + export ASCEND_OPP_PATH=$ASCEND_HOME/ascend-toolkit/latest/opp +else + export PATH=$ASCEND_HOME/fwkacllib/bin:$ASCEND_HOME/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/atc/ccec_compiler/bin:$ASCEND_HOME/atc/bin:$PATH + export LD_LIBRARY_PATH=$ASCEND_HOME/fwkacllib/lib64:/usr/local/lib:$ASCEND_HOME/atc/lib64:$ASCEND_HOME/acllib/lib64:$ASCEND_HOME/driver/lib64:$ASCEND_HOME/add-ons:$LD_LIBRARY_PATH + export PYTHONPATH=$ASCEND_HOME/fwkacllib/python/site-packages:$ASCEND_HOME/atc/python/site-packages:$PYTHONPATH + export ASCEND_OPP_PATH=$ASCEND_HOME/opp +fi + +function compile_app() +{ + cd ../ascend310_infer || exit + if [ -f "Makefile" ]; then + make clean + fi + sh build.sh &> build.log + + if [ $? -ne 0 ]; then + echo "compile app code failed" + exit 1 + fi + cd - || exit +} + +function infer() +{ + if [ -d result_Files ]; then + rm -rf ./result_Files + fi + if [ -d time_Result ]; then + rm -rf ./time_Result + fi + mkdir result_Files + mkdir time_Result + ../ascend310_infer/out/main --image_list=$data_list_file --mindir_path=$model --dataset_path=$image_path --device_id=$device_id &> infer.log + + if [ $? -ne 0 ]; then + echo "execute inference failed" + exit 1 + fi +} + +function cal_acc() +{ + python ../postprocess.py --image_list=$data_list_file --data_path=$image_path --mask_path=$mask_path --result_path=result_Files &> acc.log + if [ $? -ne 0 ]; then + echo "calculate accuracy failed" + exit 1 + fi +} + +compile_app +infer +cal_acc