1. 程式人生 > 其它 >c++讀取mnn模型

c++讀取mnn模型

技術標籤:深度學習mnncpp

之前寫了一篇文章訓練了一個模型,並轉換成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拷貝不成功,資料為系統自動初始化的數值,會導致每次的結果不一致,是隨機數