c++读取mnn模型

之前写了一篇文章训练了一个模型,并转换成mnn模型 ,并且使用了python进行调用

不过并没有使用c++进行调用

模型还是使用那篇文章的模型,调用代码如下:

#include <iostream>
#include<opencv2/core.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>
#include<MNN/Interpreter.hpp>
#include<MNN/ImageProcess.hpp>

using namespace std;
using namespace cv;
using namespace MNN;
int main()
{   auto net = std::shared_ptr<MNN::Interpreter>(MNN::Interpreter::createFromFile("E:\\vs2019\\first\\first\\model-flow.mnn"));//创建解释器
	cout << "Interpreter created" << endl;
	ScheduleConfig config;
	config.numThread = 8;
	config.type = MNN_FORWARD_CPU;
	auto session = net->createSession(config);//创建session
	cout << "session created" << endl;
	//读取图片
	cv::Mat image = cv::imread("C:\\Users\\Administrator\\Pictures\\397.jpg");
	cv::Mat img_resized;
	cv::resize(image, img_resized, cv::Size(180,180));

	auto inTensor = net->getSessionInput(session, NULL);
	auto outTensor = net->getSessionInput(session, NULL);
	auto _Tensor = MNN::Tensor::create<float>(inTensor->shape(), NULL, MNN::Tensor::TENSORFLOW);
	//cout << _Tensor->elementSize() << endl;
	for (int i = 0; i < _Tensor->elementSize(); i++) {
		_Tensor->host<float>()[i] = image.data[i];
	}
	inTensor->copyFromHostTensor(_Tensor);
	inTensor->printShape();
	//cout << *(inTensor->host<float>()+1) << endl;
	//_Tensor->print();
	_Tensor->printShape();
	//推理
	net->runSession(session);
    auto output= net->getSessionOutput(session, NULL);
	MNN::Tensor feat_tensor(output, output->getDimensionType());
	output->copyToHostTensor(&feat_tensor);
	feat_tensor.print();
	waitKey(0);
	return 0;
}

运行结果如下:

注意的是,数据结果和之前使用python调用的结果并不一致,应该是赋值数据的时候rgb的顺序颠倒了

之所以不是使用很多文章使用memcpy的方式读取input张量,因为这个在我的机器一直memcpy拷贝不成功 ,数据为系统自动初始化的数值,会导致每次的结果不一致,是随机数

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/111869497