diff --git a/model_zoo/official/cv/crnn/Dockerfile b/model_zoo/official/cv/crnn/Dockerfile new file mode 100644 index 0000000000..fcb31f207f --- /dev/null +++ b/model_zoo/official/cv/crnn/Dockerfile @@ -0,0 +1,6 @@ +ARG FROM_IMAGE_NAME +FROM ${FROM_IMAGE_NAME} + +RUN apt install libgl1-mesa-glx -y +COPY requirements.txt . +RUN pip3.7 install -r requirements.txt diff --git a/model_zoo/official/cv/crnn/ascend310_infer/CMakeLists.txt b/model_zoo/official/cv/crnn/ascend310_infer/CMakeLists.txt new file mode 100644 index 0000000000..ee3c854473 --- /dev/null +++ b/model_zoo/official/cv/crnn/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/crnn/ascend310_infer/build.sh b/model_zoo/official/cv/crnn/ascend310_infer/build.sh new file mode 100644 index 0000000000..4e1817bac6 --- /dev/null +++ b/model_zoo/official/cv/crnn/ascend310_infer/build.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Copyright 2020-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 + mkdir out +fi +cd out +cmake .. \ + -DMINDSPORE_PATH="`pip show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`" +make diff --git a/model_zoo/official/cv/crnn/ascend310_infer/inc/utils.h b/model_zoo/official/cv/crnn/ascend310_infer/inc/utils.h new file mode 100644 index 0000000000..efebe03a8c --- /dev/null +++ b/model_zoo/official/cv/crnn/ascend310_infer/inc/utils.h @@ -0,0 +1,32 @@ +/** + * 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); +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/crnn/ascend310_infer/src/main.cc b/model_zoo/official/cv/crnn/ascend310_infer/src/main.cc new file mode 100644 index 0000000000..a815c4b95c --- /dev/null +++ b/model_zoo/official/cv/crnn/ascend310_infer/src/main.cc @@ -0,0 +1,148 @@ +/** + * 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/api/model.h" +#include "include/api/context.h" +#include "include/api/serialization.h" +#include "include/api/types.h" +#include "include/minddata/dataset/include/vision.h" +#include "include/minddata/dataset/include/execute.h" +#include "minddata/dataset/include/vision.h" + +#include "inc/utils.h" + +using mindspore::GlobalContext; +using mindspore::Serialization; +using mindspore::Model; +using mindspore::ModelContext; +using mindspore::Status; +using mindspore::ModelType; +using mindspore::GraphCell; +using mindspore::kSuccess; +using mindspore::MSTensor; +using mindspore::dataset::Execute; +using mindspore::dataset::vision::Decode; +using mindspore::dataset::vision::Resize; +using mindspore::dataset::vision::Normalize; +using mindspore::dataset::vision::HWC2CHW; + +using mindspore::dataset::transforms::TypeCast; + +DEFINE_string(mindir_path, "", "mindir path"); +DEFINE_string(dataset_path, ".", "dataset path"); +DEFINE_int32(device_id, 0, "device id"); +DEFINE_string(precision_mode, "allow_fp32_to_fp16", "precision mode"); +DEFINE_string(op_select_impl_mode, "", "op select impl mode"); +DEFINE_string(aipp_path, "", "aipp config file"); + +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; + } + + GlobalContext::SetGlobalDeviceTarget(mindspore::kDeviceTypeAscend310); + GlobalContext::SetGlobalDeviceID(FLAGS_device_id); + auto graph = Serialization::LoadModel(FLAGS_mindir_path, ModelType::kMindIR); + auto model_context = std::make_shared(); + if (!FLAGS_aipp_path.empty()) { + ModelContext::SetInsertOpConfigPath(model_context, FLAGS_aipp_path); + } + + Model model(GraphCell(graph), model_context); + Status ret = model.Build(); + if (ret != kSuccess) { + std::cout << "ERROR: Build failed." << std::endl; + return 1; + } + + auto allFiles = GetAllFiles(FLAGS_dataset_path); + if (allFiles.empty()) { + std::cout << "ERROR: no input data." << std::endl; + return 1; + } + + Execute compose({std::shared_ptr(new Decode()), + std::shared_ptr(new Resize({32, 100})), + std::shared_ptr(new Normalize({127.5, 127.5, 127.5}, + {127.5, 127.5, 127.5})), + std::shared_ptr(new HWC2CHW())}); + Execute composeCast(std::shared_ptr(new TypeCast("float16"))); + + struct timeval start; + struct timeval end; + double startTime_ms; + double endTime_ms; + std::map costTime_map; + size_t size = allFiles.size(); + + for (size_t i = 0; i < size; ++i) { + std::vector inputs; + std::vector outputs; + std::cout << "Start predict input files:" << allFiles[i] << std::endl; + std::string suffix = allFiles[i].substr(allFiles[i].rfind(".")); + if (suffix != ".jpg" && suffix != ".png" && suffix != ".JPG" && suffix != ".PNG") { + std::cout << "wrong file format: " << allFiles[i] << std::endl; + continue; + } + auto img = std::make_shared(); + compose(ReadFileToTensor(allFiles[i]), img.get()); + + inputs.emplace_back(img->Name(), img->DataType(), img->Shape(), + img->Data().get(), img->DataSize()); + + gettimeofday(&start, NULL); + ret = model.Predict(inputs, &outputs); + gettimeofday(&end, NULL); + if (ret != kSuccess) { + std::cout << "Predict " << allFiles[i] << " failed." << std::endl; + return 1; + } + startTime_ms = (1.0 * start.tv_sec * 1000000 + start.tv_usec) / 1000; + endTime_ms = (1.0 * end.tv_sec * 1000000 + end.tv_usec) / 1000; + costTime_map.insert(std::pair(startTime_ms, endTime_ms)); + WriteResult(allFiles[i], outputs); + } + double average = 0.0; + int infer_cnt = 0; + char tmpCh[256] = {0}; + for (auto iter = costTime_map.begin(); iter != costTime_map.end(); iter++) { + double diff = 0.0; + diff = iter->second - iter->first; + average += diff; + infer_cnt++; + } + average = average/infer_cnt; + + snprintf(tmpCh, sizeof(tmpCh), "NN inference cost average time: %4.3f ms of infer_count %d \n", average, infer_cnt); + std::cout << "NN inference cost average time: "<< average << "ms of infer_count " << infer_cnt << std::endl; + std::string file_name = "./time_Result" + std::string("/test_perform_static.txt"); + std::ofstream file_stream(file_name.c_str(), std::ios::trunc); + file_stream << tmpCh; + file_stream.close(); + costTime_map.clear(); + return 0; +} diff --git a/model_zoo/official/cv/crnn/ascend310_infer/src/utils.cc b/model_zoo/official/cv/crnn/ascend310_infer/src/utils.cc new file mode 100644 index 0000000000..b509c57f82 --- /dev/null +++ b/model_zoo/official/cv/crnn/ascend310_infer/src/utils.cc @@ -0,0 +1,130 @@ +/** + * 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 "inc/utils.h" + +#include +#include +#include + +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; +} + +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; +} + +mindspore::MSTensor ReadFileToTensor(const std::string &file) { + if (file.empty()) { + std::cout << "Pointer file is nullptr" << std::endl; + return mindspore::MSTensor(); + } + + std::ifstream ifs(file); + if (!ifs.good()) { + std::cout << "File: " << file << " is not exist" << std::endl; + return mindspore::MSTensor(); + } + + if (!ifs.is_open()) { + std::cout << "File: " << file << "open failed" << std::endl; + return mindspore::MSTensor(); + } + + ifs.seekg(0, std::ios::end); + size_t size = ifs.tellg(); + mindspore::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/crnn/postprocess.py b/model_zoo/official/cv/crnn/postprocess.py new file mode 100644 index 0000000000..f321d70f3b --- /dev/null +++ b/model_zoo/official/cv/crnn/postprocess.py @@ -0,0 +1,81 @@ +# 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 +# +# less 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 + +from src.metric import CRNNAccuracy +from src.config import config1 as config + +parser = argparse.ArgumentParser(description="yolov3_darknet53 inference") +parser.add_argument("--ann_file", type=str, required=True, help="ann file.") +parser.add_argument("--result_path", type=str, required=True, help="image file path.") +parser.add_argument("--dataset", type=str, default="ic03", choices=['ic03', 'ic13', 'svt', 'iiit5k']) +args = parser.parse_args() + +def read_annotation(ann_file): + file = open(ann_file) + + ann = {} + for line in file.readlines(): + img_info = line.rsplit("/")[-1].split(",") + img_path = img_info[0].split('/')[-1] + ann[img_path] = img_info[1].strip() + + return ann + +def read_IC13_annotation(ann_file): + file = open(ann_file) + + ann = {} + for line in file.readlines(): + img_info = line.split(",") + img_path = img_info[0].split('/')[-1] + ann[img_path] = img_info[1].strip().replace('\"', '') + + return ann + +def read_svt_annotation(ann_file): + file = open(ann_file) + + ann = {} + for line in file.readlines(): + img_info = line.split(",") + img_path = img_info[0].split('/')[-1] + ann[img_path] = img_info[1].strip() + + return ann + +def get_eval_result(result_path, ann_file): + metrics = CRNNAccuracy(config) + + if args.dataset == "ic03" or args.dataset == "iiit5k": + ann = read_annotation(args.ann_file) + elif args.dataset == "ic13": + ann = read_IC13_annotation(args.ann_file) + elif args.dataset == "svt": + ann = read_svt_annotation(args.ann_file) + + for img_name, label in ann.items(): + result_file = os.path.join(result_path, img_name[:-4] + "_0.bin") + pred_y = np.fromfile(result_file, dtype=np.float32).reshape(config.num_step, -1, config.class_num) + metrics.update(pred_y, [label]) + + print("result CRNNAccuracy is: ", metrics.eval()) + metrics.clear() + +if __name__ == '__main__': + get_eval_result(args.result_path, args.ann_file) diff --git a/model_zoo/official/cv/crnn/requirements.txt b/model_zoo/official/cv/crnn/requirements.txt index 68d6df0268..a0aafc502d 100644 --- a/model_zoo/official/cv/crnn/requirements.txt +++ b/model_zoo/official/cv/crnn/requirements.txt @@ -1 +1,3 @@ -python-Levenshtein \ No newline at end of file +python-Levenshtein +Pillow +xml-python diff --git a/model_zoo/official/cv/crnn/scripts/run_infer_310.sh b/model_zoo/official/cv/crnn/scripts/run_infer_310.sh new file mode 100755 index 0000000000..fa64118a51 --- /dev/null +++ b/model_zoo/official/cv/crnn/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: sh run_infer_310.sh [MINDIR_PATH] [DATA_PATH] [ANN_FILE_PATH] [DATASET] [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_path=$(get_real_path $2) +ann_file=$(get_real_path $3) +dataset=$4 +if [ $# == 5 ]; then + device_id=$5 +elif [ $# == 4 ]; then + if [ -z $device_id ]; then + device_id=0 + else + device_id=$device_id + fi +fi + +echo $model +echo $data_path +echo $ann_file +echo $device_id + +export ASCEND_HOME=/usr/local/Ascend/ +if [ -d ${ASCEND_HOME}/ascend-toolkit ]; then + export PATH=$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/atc/bin:$PATH + export LD_LIBRARY_PATH=/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=${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/atc/ccec_compiler/bin:$ASCEND_HOME/atc/bin:$PATH + export LD_LIBRARY_PATH=/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/atc/python/site-packages:$PYTHONPATH + export ASCEND_OPP_PATH=$ASCEND_HOME/opp +fi + +function compile_app() +{ + cd ../ascend310_infer + 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 - +} + +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 --mindir_path=$model --dataset_path=$data_path --device_id=$device_id &> infer.log + + if [ $? -ne 0 ]; then + echo "execute inference failed" + exit 1 + fi +} + +function cal_acc() +{ + python ../postprocess.py --ann_file=$ann_file --result_path=result_Files --dataset=$dataset &> acc.log & + if [ $? -ne 0 ]; then + echo "calculate accuracy failed" + exit 1 + fi +} + +compile_app +infer +cal_acc diff --git a/model_zoo/official/cv/crnn/src/metric.py b/model_zoo/official/cv/crnn/src/metric.py index 265e853d6f..eea67c0901 100644 --- a/model_zoo/official/cv/crnn/src/metric.py +++ b/model_zoo/official/cv/crnn/src/metric.py @@ -37,9 +37,12 @@ class CRNNAccuracy(nn.Metric): if len(inputs) != 2: raise ValueError('CRNNAccuracy need 2 inputs (y_pred, y), but got {}'.format(len(inputs))) y_pred = self._convert_data(inputs[0]) - y = self._convert_data(inputs[1]) str_pred = self._ctc_greedy_decoder(y_pred) - str_label = self._convert_labels(y) + if isinstance(inputs[1], list) and isinstance(inputs[1][0], str): + str_label = [x.lower() for x in inputs[1]] + else: + y = self._convert_data(inputs[1]) + str_label = self._convert_labels(y) for pred, label in zip(str_pred, str_label): print(pred, " :: ", label) diff --git a/model_zoo/official/cv/ssd/ascend310_infer/CMakeLists.txt b/model_zoo/official/cv/ssd/ascend310_infer/CMakeLists.txt index 50f1460f0c..ee3c854473 100644 --- a/model_zoo/official/cv/ssd/ascend310_infer/CMakeLists.txt +++ b/model_zoo/official/cv/ssd/ascend310_infer/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.14.1) -project(MindSporeCxxTestcase[CXX]) +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}/)