c++使用opencv调用caffe框架训练的caffemodel模型,并对数据集图像批量测试,统计分类结果
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/utils/trace.hpp>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace cv;
using namespace cv::dnn;
using namespace std;
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.reshape(1, 1);
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
static std::vector<String> readClassNames(const char *filename = "D:\\Program Files\\caffe\\caffe-master\\caffe-master\\examples\\transfer-water\\data\\mydata\\labels.txt")
{
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open())
{
std::cerr << "File with classes labels not found: " << filename << std::endl;
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back(name.substr(name.find(' ') + 1));
}
fp.close();
return classNames;
}
int main(int argc, char **argv)
{
CV_TRACE_FUNCTION();
String modelTxt = "D://predict//water//deploy_transform.prototxt";
String modelBin = "D:\\Program Files\\caffe\\caffe-master\\caffe-master\\examples\\transfer-water\\data\\mydata\\caffenet_train_transform_iter_500.caffemodel";
String imageFile = "D://predict//water//mirror//*.jpg";
Net net = dnn::readNetFromCaffe(modelTxt, modelBin);
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
exit(-1);
}
cerr << "net read successfully" << endl;
vector<cv::String> image_files;
glob(imageFile, image_files);
if (image_files.size() == 0) {
std::cout << "No image files[jpg]" << std::endl;
return 0;
}
int a = 0, b = 0;
for (unsigned int frame = 0; frame < image_files.size(); ++frame)
{
Mat img = cv::imread(image_files[frame]);
cout << image_files[frame] << endl;
if (img.empty())
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
cerr << "image read sucessfully" << endl;
Mat inputBlob = blobFromImage(img, 1, Size(227, 227), Scalar(103.788, 104.337, 100.518), false);
Mat prob;
cv::TickMeter t;
CV_TRACE_REGION("forward");
net.setInput(inputBlob, "data");
prob = net.forward("prob");
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);
std::vector<String> classNames = readClassNames();
std::cout << "Best class: " << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
if (classId == 0)
{
a = a + 1;
imshow("", img);
}
else
{
b = b + 1;
}
waitKey(0);
}
cout << "无水图片:" << a << endl;
cout << "有水图片:" << b << endl;
system("Pause");
return 0;
}