Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/classification.cpp
16337 views
1
#include <fstream>
2
#include <sstream>
3
4
#include <opencv2/dnn.hpp>
5
#include <opencv2/imgproc.hpp>
6
#include <opencv2/highgui.hpp>
7
8
#include "common.hpp"
9
10
std::string keys =
11
"{ help h | | Print help message. }"
12
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
13
"{ zoo | models.yml | An optional path to file with preprocessing parameters }"
14
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera.}"
15
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
16
"{ classes | | Optional path to a text file with names of classes. }"
17
"{ backend | 0 | Choose one of computation backends: "
18
"0: automatically (by default), "
19
"1: Halide language (http://halide-lang.org/), "
20
"2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
21
"3: OpenCV implementation }"
22
"{ target | 0 | Choose one of target computation devices: "
23
"0: CPU target (by default), "
24
"1: OpenCL, "
25
"2: OpenCL fp16 (half-float precision), "
26
"3: VPU }";
27
28
using namespace cv;
29
using namespace dnn;
30
31
std::vector<std::string> classes;
32
33
int main(int argc, char** argv)
34
{
35
CommandLineParser parser(argc, argv, keys);
36
37
const std::string modelName = parser.get<String>("@alias");
38
const std::string zooFile = parser.get<String>("zoo");
39
40
keys += genPreprocArguments(modelName, zooFile);
41
42
parser = CommandLineParser(argc, argv, keys);
43
parser.about("Use this script to run classification deep learning networks using OpenCV.");
44
if (argc == 1 || parser.has("help"))
45
{
46
parser.printMessage();
47
return 0;
48
}
49
50
float scale = parser.get<float>("scale");
51
Scalar mean = parser.get<Scalar>("mean");
52
bool swapRB = parser.get<bool>("rgb");
53
int inpWidth = parser.get<int>("width");
54
int inpHeight = parser.get<int>("height");
55
String model = findFile(parser.get<String>("model"));
56
String config = findFile(parser.get<String>("config"));
57
String framework = parser.get<String>("framework");
58
int backendId = parser.get<int>("backend");
59
int targetId = parser.get<int>("target");
60
61
// Open file with classes names.
62
if (parser.has("classes"))
63
{
64
std::string file = parser.get<String>("classes");
65
std::ifstream ifs(file.c_str());
66
if (!ifs.is_open())
67
CV_Error(Error::StsError, "File " + file + " not found");
68
std::string line;
69
while (std::getline(ifs, line))
70
{
71
classes.push_back(line);
72
}
73
}
74
75
if (!parser.check())
76
{
77
parser.printErrors();
78
return 1;
79
}
80
CV_Assert(!model.empty());
81
82
//! [Read and initialize network]
83
Net net = readNet(model, config, framework);
84
net.setPreferableBackend(backendId);
85
net.setPreferableTarget(targetId);
86
//! [Read and initialize network]
87
88
// Create a window
89
static const std::string kWinName = "Deep learning image classification in OpenCV";
90
namedWindow(kWinName, WINDOW_NORMAL);
91
92
//! [Open a video file or an image file or a camera stream]
93
VideoCapture cap;
94
if (parser.has("input"))
95
cap.open(parser.get<String>("input"));
96
else
97
cap.open(0);
98
//! [Open a video file or an image file or a camera stream]
99
100
// Process frames.
101
Mat frame, blob;
102
while (waitKey(1) < 0)
103
{
104
cap >> frame;
105
if (frame.empty())
106
{
107
waitKey();
108
break;
109
}
110
111
//! [Create a 4D blob from a frame]
112
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, false);
113
//! [Create a 4D blob from a frame]
114
115
//! [Set input blob]
116
net.setInput(blob);
117
//! [Set input blob]
118
//! [Make forward pass]
119
Mat prob = net.forward();
120
//! [Make forward pass]
121
122
//! [Get a class with a highest score]
123
Point classIdPoint;
124
double confidence;
125
minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
126
int classId = classIdPoint.x;
127
//! [Get a class with a highest score]
128
129
// Put efficiency information.
130
std::vector<double> layersTimes;
131
double freq = getTickFrequency() / 1000;
132
double t = net.getPerfProfile(layersTimes) / freq;
133
std::string label = format("Inference time: %.2f ms", t);
134
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
135
136
// Print predicted class.
137
label = format("%s: %.4f", (classes.empty() ? format("Class #%d", classId).c_str() :
138
classes[classId].c_str()),
139
confidence);
140
putText(frame, label, Point(0, 40), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
141
142
imshow(kWinName, frame);
143
}
144
return 0;
145
}
146
147