环境:VS2017+OpenCV3.3+C++
当我们接触一个全新的caffe.model文件,如何快速应用的,今天我将通过一个预测性别和年龄的实例来说明这个问题,首先来下载模型文件,保存到我们指定的自定义的目录,首先我们应该查看模型的描述文件(.prototxt),确定模型需要的输入和输出部分。
name: "CaffeNet"
input: "data" //输入层
input_dim: 10 //数据增广
input_dim: 3 //通道数
input_dim: 227//长宽
input_dim: 227
输出:
layers {
name: "prob" //名称
type: SOFTMAX //特征层
bottom: "fc8"
top: "prob"
}
我们可以知道,输入数据的格式,接下来我们可以通过之前讲过的级联分类器作为图像输入,然后就可以进行性别和年龄的预测了。
//替换成你的对应位置
String model_age_file = "D:/new_cv/opencv/sources/samples/data/age_net.caffemodel";
String model_age_txt = "D:/new_cv/opencv/sources/samples/data/age_deploy.prototxt";
String model_gender_bin ="D:/new_cv/opencv/sources/samples/data/gender_net.caffemodel";
String model_gender_txt ="D:/new_cv/opencv/sources/samples/data/gender_deploy.prototxt";
在进行年龄预测之前,我们先对label进行保存
vector get_age_label()
{
vector age_labels;
age_labels.push_back("0-2");
age_labels.push_back("4-6");
age_labels.push_back("8-13");
age_labels.push_back("15-20");
age_labels.push_back("25-32");
age_labels.push_back("38-43");
age_labels.push_back("48-53");
age_labels.push_back("60-");
return age_labels;
}
年龄预测代码:
void predict_age(Mat &src)
{
Net net = readNetFromCaffe(model_age1_txt, model_age1_file);
if (net.empty())
{
cout << "load net error" << endl;
exit(-1);
}
Mat blobImg = blobFromImage(src, 1.0, Size(227, 227));
net.setInput(blobImg, "data");
Mat probMat = net.forward("prob");
probMat.reshape(1, 1);//1行1通道
Point index;//坐标信息
double objvalue;//最大检测值
minMaxLoc(probMat, NULL, &objvalue, NULL, &index);//忽略最小值,取最大值
size_t objindex = index.x;//label 下标
vectorlabels = get_age_label();
putText(src, format("age:%s", labels[objindex].c_str()), Point(2, 20), FONT_HERSHEY_PLAIN, 0.7, Scalar(1, 12, 3), 1, 8);
}
void predict_gender(Mat &src)
{
Net net = readNetFromCaffe(model_age1_txt, model_age1_file);
if (net.empty())
{
cout << "load net error" << endl;
exit(-1);
}
Mat blobImg = blobFromImage(src, 1.0, Size(227, 227));
net.setInput(blobImg, "data");
Mat probMat = net.forward("prob");
probMat.reshape(1, 1);//1行1通道
putText(src, format("gender:%s", (probMat.size[0] > probMat.size[1] ? "M" : "F")), Point(2, 10), FONT_HERSHEY_PLAIN, 0.7, Scalar(2, 2, 3), 1, 8);
}
源代码:https://github.com/haiqiang2017/open-dnn/blob/master/DNN/net_cas.cpp