注意点:
1、size跟训练时一致;
2、训练时用到Normalize的话,因为blobFromImage不支持方差,需要重写blobFromImage;
3、预测结果的格式,确保读取对应指标正确;
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位转为8位
convertScaleAbs(imgNorm, imgNorm);
Mat imRGB;
cvtColor(imgNorm, imRGB, COLOR_GRAY2BGR);
const int nHight = 400;//需要跟训练时transforms的Resize保持一致
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++) //分为两类,所以这里为2
{
vecScore.push_back(pdata[i]);
}
auto maxPosition = max_element(vecScore.begin(), vecScore.end());
int nMaxIndex = maxPosition - vecScore.begin();//vdbAmplitude中的值绝对值最大时的索引
return nMaxIndex;
}
catch (const std::exception&) {
return -1;
}
}