c++ read mnn model

I wrote an article before, trained a model, and converted it into an mnn model, and used python to call

But it did not use c++ to call

The model still uses the model of that article, and the calling code is as follows:

#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;
}

The results of the operation are as follows:

Note that the data result is not consistent with the result of the previous python call. It should be that the order of rgb is reversed when assigning data.

The reason why I don’t use many articles to read the input tensor using memcpy, because this memcpy copy has been unsuccessful in my machine. The data is the value automatically initialized by the system, which will cause the results to be inconsistent each time, which is a random number.

 

Guess you like

Origin blog.csdn.net/zhou_438/article/details/111869497
Recommended