当前位置:网站首页>The DNN of OpenCV is used to read onnx as the prediction end to realize classification

The DNN of OpenCV is used to read onnx as the prediction end to realize classification

2022-04-23 21:57:00 Three stone orders

Be careful :
1、size Consistent with training ;
2、 Used in training Normalize Words , because blobFromImage Variance is not supported , Need to rewrite blobFromImage;
3、 Format of prediction results , Ensure that the corresponding indicators are read correctly ;

class ModelFlipClass
{
    
private:
	Net net;
public:
	bool Read(string pathNet);
	int Detect(string strImgPath);
};

bool ModelFlipClass::Read(string pathNet)
{
    
	try {
    
		net = readNet(pathNet);
	}
	catch (const std::exception&) {
    
		return false;
	}
	net.setPreferableBackend(cv::dnn::DNN_BACKEND_DEFAULT);
	net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
	return true;
}

int ModelXRayFlipClass::Detect(string strImgPath)
{
    
	try 
	{
    
		Mat imgInput = imread(strImgPath, IMREAD_UNCHANGED);
		Mat imgNorm;
		normalize(imgInput, imgNorm, 0, 255, NORM_MINMAX);//16 The bit changes to 8 position 
		convertScaleAbs(imgNorm, imgNorm);
		Mat imRGB;
		cvtColor(imgNorm, imRGB, COLOR_GRAY2BGR);
		const int nHight = 400;// When training is needed transforms Of Resize bring into correspondence with 
		const int nWight = 200;
		Mat blob;
		blobFromImage(imRGB, blob, 1 / 255.0, cv::Size(nWight, nHight), Scalar(), true, false);
		net.setInput(blob);
		vector<cv::Mat> netOutputImg;
		net.forward(netOutputImg, net.getUnconnectedOutLayersNames());
		float* pdata = (float*)netOutputImg[0].data;
		vector<float> vecScore;
		for (size_t i = 0; i < 2; i++) // There are two kinds of , So here is 2
		{
    
			vecScore.push_back(pdata[i]);
		}
		auto maxPosition = max_element(vecScore.begin(), vecScore.end());
		int nMaxIndex = maxPosition - vecScore.begin();//vdbAmplitude The index when the absolute value of the value in is the largest 
		return nMaxIndex;
	}
	catch (const std::exception&) {
    
		return -1;
	}
}

版权声明
本文为[Three stone orders]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204200615437287.html