In this tutorial you will learn how to use opencv_dnn module for image classification by using GoogLeNet trained network from Caffe model zoo.
We will demonstrate results of this example on the following picture.
#include <fstream>
#include <iostream>
#include <cstdlib>
static void getMaxClass(
const Mat &probBlob,
int *classId,
double *classProb)
{
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.
x;
}
static std::vector<String> readClassNames(const char *filename )
{
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;
}
const char* params
= "{ help | false | Sample app for loading googlenet model }"
"{ proto | bvlc_googlenet.prototxt | model configuration }"
"{ model | bvlc_googlenet.caffemodel | model weights }"
"{ label | synset_words.txt | names of ILSVRC2012 classes }"
"{ image | space_shuttle.jpg | path to image file }"
"{ opencl | false | enable OpenCL }"
;
int main(int argc, char **argv)
{
if (parser.get<bool>("help"))
{
parser.printMessage();
return 0;
}
String modelTxt = parser.get<
string>(
"proto");
String modelBin = parser.get<
string>(
"model");
try {
}
std::cerr <<
"Exception: " << e.
what() << std::endl;
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << modelTxt << std::endl;
std::cerr << "caffemodel: " << modelBin << std::endl;
std::cerr << "bvlc_googlenet.caffemodel can be downloaded here:" << std::endl;
std::cerr << "http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel" << std::endl;
exit(-1);
}
}
if (parser.get<bool>("opencl"))
{
}
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
Scalar(104, 117, 123),
false);
net.setInput(inputBlob, "data");
Mat prob = net.forward(
"prob");
for (int i = 0; i < 10; i++)
{
net.setInput(inputBlob, "data");
prob = net.forward("prob");
}
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);
std::vector<String> classNames = readClassNames(classNameFile.c_str());
std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
return 0;
}