# Ascend310处理器上推理MindIR模型¶

Ascend 进阶 推理应用

## 推理代码介绍¶

namespace ms = mindspore;
namespace ds = mindspore::dataset;


auto context = std::make_shared<ms::Context>();
auto ascend310_info = std::make_shared<ms::Ascend310DeviceInfo>();
ascend310_info->SetDeviceID(0);
context->MutableDeviceInfo().push_back(ascend310_info);


// 加载MindIR模型
ms::Graph graph;
ms::Status ret = ms::Serialization::Load(resnet_file, ms::ModelType::kMindIR, &graph);
// 图编译
ms::Model resnet50;
ret = resnet50.Build(ms::GraphCell(graph), context);


std::vector<ms::MSTensor> model_inputs = resnet50.GetInputs();


ms::MSTensor ReadFile(const std::string &file);


// 对图片进行解码，变为RGB格式，并重设尺寸
std::shared_ptr<ds::TensorTransform> decode(new ds::vision::Decode());
std::shared_ptr<ds::TensorTransform> resize(new ds::vision::Resize({256}));
// 输入归一化
std::shared_ptr<ds::TensorTransform> normalize(new ds::vision::Normalize(
{0.485 * 255, 0.456 * 255, 0.406 * 255}, {0.229 * 255, 0.224 * 255, 0.225 * 255}));
// 剪裁图片
std::shared_ptr<ds::TensorTransform> center_crop(new ds::vision::CenterCrop({224, 224}));
// shape (H, W, C) 变为 shape (C, H, W)
std::shared_ptr<ds::TensorTransform> hwc2chw(new ds::vision::HWC2CHW());

// 定义preprocessor
ds::Execute preprocessor({decode, resize, normalize, center_crop, hwc2chw});

// 调用函数，获取处理后的图像
ret = preprocessor(image, &image);


// 创建输入输出向量
std::vector<ms::MSTensor> outputs;
std::vector<ms::MSTensor> inputs;
inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(),
image.Data().get(), image.DataSize());
// 执行推理
ret = resnet50.Predict(inputs, &outputs);


// 获取推理结果的最大概率
std::cout << "Image: " << image_file << " infer result: " << GetMax(outputs[0]) << std::endl;


## 构建脚本介绍¶

option(MINDSPORE_PATH "mindspore install path" "")
include_directories(${MINDSPORE_PATH}) include_directories(${MINDSPORE_PATH}/include)


find_library(MS_LIB libmindspore.so ${MINDSPORE_PATH}/lib) file(GLOB_RECURSE MD_LIB${MINDSPORE_PATH}/_c_dataengine*)


add_executable(resnet50_sample main.cc)
target_link_libraries(resnet50_sample ${MS_LIB}${MD_LIB})


## 编译并执行推理代码¶

cmake . -DMINDSPORE_PATH=pip3 show mindspore-ascend | grep Location | awk '{print \$2"/mindspore"}' | xargs realpath


make


./resnet50_sample