Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/object_detection.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
"{ device | 0 | camera device number. }"
15
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera. }"
16
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
17
"{ classes | | Optional path to a text file with names of classes to label detected objects. }"
18
"{ thr | .5 | Confidence threshold. }"
19
"{ nms | .4 | Non-maximum suppression threshold. }"
20
"{ backend | 0 | Choose one of computation backends: "
21
"0: automatically (by default), "
22
"1: Halide language (http://halide-lang.org/), "
23
"2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
24
"3: OpenCV implementation }"
25
"{ target | 0 | Choose one of target computation devices: "
26
"0: CPU target (by default), "
27
"1: OpenCL, "
28
"2: OpenCL fp16 (half-float precision), "
29
"3: VPU }";
30
31
32
using namespace cv;
33
using namespace dnn;
34
35
float confThreshold, nmsThreshold;
36
std::vector<std::string> classes;
37
38
void postprocess(Mat& frame, const std::vector<Mat>& out, Net& net);
39
40
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
41
42
void callback(int pos, void* userdata);
43
44
std::vector<String> getOutputsNames(const Net& net);
45
46
int main(int argc, char** argv)
47
{
48
CommandLineParser parser(argc, argv, keys);
49
50
const std::string modelName = parser.get<String>("@alias");
51
const std::string zooFile = parser.get<String>("zoo");
52
53
keys += genPreprocArguments(modelName, zooFile);
54
55
parser = CommandLineParser(argc, argv, keys);
56
parser.about("Use this script to run object detection deep learning networks using OpenCV.");
57
if (argc == 1 || parser.has("help"))
58
{
59
parser.printMessage();
60
return 0;
61
}
62
63
confThreshold = parser.get<float>("thr");
64
nmsThreshold = parser.get<float>("nms");
65
float scale = parser.get<float>("scale");
66
Scalar mean = parser.get<Scalar>("mean");
67
bool swapRB = parser.get<bool>("rgb");
68
int inpWidth = parser.get<int>("width");
69
int inpHeight = parser.get<int>("height");
70
CV_Assert(parser.has("model"));
71
std::string modelPath = findFile(parser.get<String>("model"));
72
std::string configPath = findFile(parser.get<String>("config"));
73
74
// Open file with classes names.
75
if (parser.has("classes"))
76
{
77
std::string file = parser.get<String>("classes");
78
std::ifstream ifs(file.c_str());
79
if (!ifs.is_open())
80
CV_Error(Error::StsError, "File " + file + " not found");
81
std::string line;
82
while (std::getline(ifs, line))
83
{
84
classes.push_back(line);
85
}
86
}
87
88
// Load a model.
89
Net net = readNet(modelPath, configPath, parser.get<String>("framework"));
90
net.setPreferableBackend(parser.get<int>("backend"));
91
net.setPreferableTarget(parser.get<int>("target"));
92
std::vector<String> outNames = net.getUnconnectedOutLayersNames();
93
94
// Create a window
95
static const std::string kWinName = "Deep learning object detection in OpenCV";
96
namedWindow(kWinName, WINDOW_NORMAL);
97
int initialConf = (int)(confThreshold * 100);
98
createTrackbar("Confidence threshold, %", kWinName, &initialConf, 99, callback);
99
100
// Open a video file or an image file or a camera stream.
101
VideoCapture cap;
102
if (parser.has("input"))
103
cap.open(parser.get<String>("input"));
104
else
105
cap.open(parser.get<int>("device"));
106
107
// Process frames.
108
Mat frame, blob;
109
while (waitKey(1) < 0)
110
{
111
cap >> frame;
112
if (frame.empty())
113
{
114
waitKey();
115
break;
116
}
117
118
// Create a 4D blob from a frame.
119
Size inpSize(inpWidth > 0 ? inpWidth : frame.cols,
120
inpHeight > 0 ? inpHeight : frame.rows);
121
blobFromImage(frame, blob, scale, inpSize, mean, swapRB, false);
122
123
// Run a model.
124
net.setInput(blob);
125
if (net.getLayer(0)->outputNameToIndex("im_info") != -1) // Faster-RCNN or R-FCN
126
{
127
resize(frame, frame, inpSize);
128
Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
129
net.setInput(imInfo, "im_info");
130
}
131
std::vector<Mat> outs;
132
net.forward(outs, outNames);
133
134
postprocess(frame, outs, net);
135
136
// Put efficiency information.
137
std::vector<double> layersTimes;
138
double freq = getTickFrequency() / 1000;
139
double t = net.getPerfProfile(layersTimes) / freq;
140
std::string label = format("Inference time: %.2f ms", t);
141
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
142
143
imshow(kWinName, frame);
144
}
145
return 0;
146
}
147
148
void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net)
149
{
150
static std::vector<int> outLayers = net.getUnconnectedOutLayers();
151
static std::string outLayerType = net.getLayer(outLayers[0])->type;
152
153
std::vector<int> classIds;
154
std::vector<float> confidences;
155
std::vector<Rect> boxes;
156
if (net.getLayer(0)->outputNameToIndex("im_info") != -1) // Faster-RCNN or R-FCN
157
{
158
// Network produces output blob with a shape 1x1xNx7 where N is a number of
159
// detections and an every detection is a vector of values
160
// [batchId, classId, confidence, left, top, right, bottom]
161
CV_Assert(outs.size() == 1);
162
float* data = (float*)outs[0].data;
163
for (size_t i = 0; i < outs[0].total(); i += 7)
164
{
165
float confidence = data[i + 2];
166
if (confidence > confThreshold)
167
{
168
int left = (int)data[i + 3];
169
int top = (int)data[i + 4];
170
int right = (int)data[i + 5];
171
int bottom = (int)data[i + 6];
172
int width = right - left + 1;
173
int height = bottom - top + 1;
174
classIds.push_back((int)(data[i + 1]) - 1); // Skip 0th background class id.
175
boxes.push_back(Rect(left, top, width, height));
176
confidences.push_back(confidence);
177
}
178
}
179
}
180
else if (outLayerType == "DetectionOutput")
181
{
182
// Network produces output blob with a shape 1x1xNx7 where N is a number of
183
// detections and an every detection is a vector of values
184
// [batchId, classId, confidence, left, top, right, bottom]
185
CV_Assert(outs.size() == 1);
186
float* data = (float*)outs[0].data;
187
for (size_t i = 0; i < outs[0].total(); i += 7)
188
{
189
float confidence = data[i + 2];
190
if (confidence > confThreshold)
191
{
192
int left = (int)(data[i + 3] * frame.cols);
193
int top = (int)(data[i + 4] * frame.rows);
194
int right = (int)(data[i + 5] * frame.cols);
195
int bottom = (int)(data[i + 6] * frame.rows);
196
int width = right - left + 1;
197
int height = bottom - top + 1;
198
classIds.push_back((int)(data[i + 1]) - 1); // Skip 0th background class id.
199
boxes.push_back(Rect(left, top, width, height));
200
confidences.push_back(confidence);
201
}
202
}
203
}
204
else if (outLayerType == "Region")
205
{
206
for (size_t i = 0; i < outs.size(); ++i)
207
{
208
// Network produces output blob with a shape NxC where N is a number of
209
// detected objects and C is a number of classes + 4 where the first 4
210
// numbers are [center_x, center_y, width, height]
211
float* data = (float*)outs[i].data;
212
for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
213
{
214
Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
215
Point classIdPoint;
216
double confidence;
217
minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
218
if (confidence > confThreshold)
219
{
220
int centerX = (int)(data[0] * frame.cols);
221
int centerY = (int)(data[1] * frame.rows);
222
int width = (int)(data[2] * frame.cols);
223
int height = (int)(data[3] * frame.rows);
224
int left = centerX - width / 2;
225
int top = centerY - height / 2;
226
227
classIds.push_back(classIdPoint.x);
228
confidences.push_back((float)confidence);
229
boxes.push_back(Rect(left, top, width, height));
230
}
231
}
232
}
233
}
234
else
235
CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType);
236
237
std::vector<int> indices;
238
NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
239
for (size_t i = 0; i < indices.size(); ++i)
240
{
241
int idx = indices[i];
242
Rect box = boxes[idx];
243
drawPred(classIds[idx], confidences[idx], box.x, box.y,
244
box.x + box.width, box.y + box.height, frame);
245
}
246
}
247
248
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
249
{
250
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));
251
252
std::string label = format("%.2f", conf);
253
if (!classes.empty())
254
{
255
CV_Assert(classId < (int)classes.size());
256
label = classes[classId] + ": " + label;
257
}
258
259
int baseLine;
260
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
261
262
top = max(top, labelSize.height);
263
rectangle(frame, Point(left, top - labelSize.height),
264
Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
265
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());
266
}
267
268
void callback(int pos, void*)
269
{
270
confThreshold = pos * 0.01f;
271
}
272
273