1 #include <fstream>
2 #include <sstream>
3 
4 #include <opencv2/dnn.hpp>
5 #include <opencv2/imgproc.hpp>
6 #include <opencv2/highgui.hpp>
7 
8 #ifdef CV_CXX11
9 #include <mutex>
10 #include <thread>
11 #include <queue>
12 #endif
13 
14 #include "common.hpp"
15 
16 std::string keys =
17     "{ help  h     | | Print help message. }"
18     "{ @alias      | | An alias name of model to extract preprocessing parameters from models.yml file. }"
19     "{ zoo         | models.yml | An optional path to file with preprocessing parameters }"
20     "{ device      |  0 | camera device number. }"
21     "{ input i     | | Path to input image or video file. Skip this argument to capture frames from a camera. }"
22     "{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
23     "{ classes     | | Optional path to a text file with names of classes to label detected objects. }"
24     "{ thr         | .5 | Confidence threshold. }"
25     "{ nms         | .4 | Non-maximum suppression threshold. }"
26     "{ backend     |  0 | Choose one of computation backends: "
27                          "0: automatically (by default), "
28                          "1: Halide language (http://halide-lang.org/), "
29                          "2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
30                          "3: OpenCV implementation, "
31                          "4: VKCOM, "
32                          "5: CUDA }"
33     "{ target      | 0 | Choose one of target computation devices: "
34                          "0: CPU target (by default), "
35                          "1: OpenCL, "
36                          "2: OpenCL fp16 (half-float precision), "
37                          "3: VPU, "
38                          "4: Vulkan, "
39                          "6: CUDA, "
40                          "7: CUDA fp16 (half-float preprocess) }"
41     "{ async       | 0 | Number of asynchronous forwards at the same time. "
42                         "Choose 0 for synchronous mode }";
43 
44 using namespace cv;
45 using namespace dnn;
46 
47 float confThreshold, nmsThreshold;
48 std::vector<std::string> classes;
49 
50 inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
51                        const Scalar& mean, bool swapRB);
52 
53 void postprocess(Mat& frame, const std::vector<Mat>& out, Net& net, int backend);
54 
55 void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
56 
57 void callback(int pos, void* userdata);
58 
59 #ifdef CV_CXX11
60 template <typename T>
61 class QueueFPS : public std::queue<T>
62 {
63 public:
QueueFPS()64     QueueFPS() : counter(0) {}
65 
push(const T & entry)66     void push(const T& entry)
67     {
68         std::lock_guard<std::mutex> lock(mutex);
69 
70         std::queue<T>::push(entry);
71         counter += 1;
72         if (counter == 1)
73         {
74             // Start counting from a second frame (warmup).
75             tm.reset();
76             tm.start();
77         }
78     }
79 
get()80     T get()
81     {
82         std::lock_guard<std::mutex> lock(mutex);
83         T entry = this->front();
84         this->pop();
85         return entry;
86     }
87 
getFPS()88     float getFPS()
89     {
90         tm.stop();
91         double fps = counter / tm.getTimeSec();
92         tm.start();
93         return static_cast<float>(fps);
94     }
95 
clear()96     void clear()
97     {
98         std::lock_guard<std::mutex> lock(mutex);
99         while (!this->empty())
100             this->pop();
101     }
102 
103     unsigned int counter;
104 
105 private:
106     TickMeter tm;
107     std::mutex mutex;
108 };
109 #endif  // CV_CXX11
110 
main(int argc,char ** argv)111 int main(int argc, char** argv)
112 {
113     CommandLineParser parser(argc, argv, keys);
114 
115     const std::string modelName = parser.get<String>("@alias");
116     const std::string zooFile = parser.get<String>("zoo");
117 
118     keys += genPreprocArguments(modelName, zooFile);
119 
120     parser = CommandLineParser(argc, argv, keys);
121     parser.about("Use this script to run object detection deep learning networks using OpenCV.");
122     if (argc == 1 || parser.has("help"))
123     {
124         parser.printMessage();
125         return 0;
126     }
127 
128     confThreshold = parser.get<float>("thr");
129     nmsThreshold = parser.get<float>("nms");
130     float scale = parser.get<float>("scale");
131     Scalar mean = parser.get<Scalar>("mean");
132     bool swapRB = parser.get<bool>("rgb");
133     int inpWidth = parser.get<int>("width");
134     int inpHeight = parser.get<int>("height");
135     size_t asyncNumReq = parser.get<int>("async");
136     CV_Assert(parser.has("model"));
137     std::string modelPath = findFile(parser.get<String>("model"));
138     std::string configPath = findFile(parser.get<String>("config"));
139 
140     // Open file with classes names.
141     if (parser.has("classes"))
142     {
143         std::string file = parser.get<String>("classes");
144         std::ifstream ifs(file.c_str());
145         if (!ifs.is_open())
146             CV_Error(Error::StsError, "File " + file + " not found");
147         std::string line;
148         while (std::getline(ifs, line))
149         {
150             classes.push_back(line);
151         }
152     }
153 
154     // Load a model.
155     Net net = readNet(modelPath, configPath, parser.get<String>("framework"));
156     int backend = parser.get<int>("backend");
157     net.setPreferableBackend(backend);
158     net.setPreferableTarget(parser.get<int>("target"));
159     std::vector<String> outNames = net.getUnconnectedOutLayersNames();
160 
161     // Create a window
162     static const std::string kWinName = "Deep learning object detection in OpenCV";
163     namedWindow(kWinName, WINDOW_NORMAL);
164     int initialConf = (int)(confThreshold * 100);
165     createTrackbar("Confidence threshold, %", kWinName, &initialConf, 99, callback);
166 
167     // Open a video file or an image file or a camera stream.
168     VideoCapture cap;
169     if (parser.has("input"))
170         cap.open(parser.get<String>("input"));
171     else
172         cap.open(parser.get<int>("device"));
173 
174 #ifdef CV_CXX11
175     bool process = true;
176 
177     // Frames capturing thread
178     QueueFPS<Mat> framesQueue;
179     std::thread framesThread([&](){
180         Mat frame;
181         while (process)
182         {
183             cap >> frame;
184             if (!frame.empty())
185                 framesQueue.push(frame.clone());
186             else
187                 break;
188         }
189     });
190 
191     // Frames processing thread
192     QueueFPS<Mat> processedFramesQueue;
193     QueueFPS<std::vector<Mat> > predictionsQueue;
194     std::thread processingThread([&](){
195         std::queue<AsyncArray> futureOutputs;
196         Mat blob;
197         while (process)
198         {
199             // Get a next frame
200             Mat frame;
201             {
202                 if (!framesQueue.empty())
203                 {
204                     frame = framesQueue.get();
205                     if (asyncNumReq)
206                     {
207                         if (futureOutputs.size() == asyncNumReq)
208                             frame = Mat();
209                     }
210                     else
211                         framesQueue.clear();  // Skip the rest of frames
212                 }
213             }
214 
215             // Process the frame
216             if (!frame.empty())
217             {
218                 preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
219                 processedFramesQueue.push(frame);
220 
221                 if (asyncNumReq)
222                 {
223                     futureOutputs.push(net.forwardAsync());
224                 }
225                 else
226                 {
227                     std::vector<Mat> outs;
228                     net.forward(outs, outNames);
229                     predictionsQueue.push(outs);
230                 }
231             }
232 
233             while (!futureOutputs.empty() &&
234                    futureOutputs.front().wait_for(std::chrono::seconds(0)))
235             {
236                 AsyncArray async_out = futureOutputs.front();
237                 futureOutputs.pop();
238                 Mat out;
239                 async_out.get(out);
240                 predictionsQueue.push({out});
241             }
242         }
243     });
244 
245     // Postprocessing and rendering loop
246     while (waitKey(1) < 0)
247     {
248         if (predictionsQueue.empty())
249             continue;
250 
251         std::vector<Mat> outs = predictionsQueue.get();
252         Mat frame = processedFramesQueue.get();
253 
254         postprocess(frame, outs, net, backend);
255 
256         if (predictionsQueue.counter > 1)
257         {
258             std::string label = format("Camera: %.2f FPS", framesQueue.getFPS());
259             putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
260 
261             label = format("Network: %.2f FPS", predictionsQueue.getFPS());
262             putText(frame, label, Point(0, 30), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
263 
264             label = format("Skipped frames: %d", framesQueue.counter - predictionsQueue.counter);
265             putText(frame, label, Point(0, 45), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
266         }
267         imshow(kWinName, frame);
268     }
269 
270     process = false;
271     framesThread.join();
272     processingThread.join();
273 
274 #else  // CV_CXX11
275     if (asyncNumReq)
276         CV_Error(Error::StsNotImplemented, "Asynchronous forward is supported only with Inference Engine backend.");
277 
278     // Process frames.
279     Mat frame, blob;
280     while (waitKey(1) < 0)
281     {
282         cap >> frame;
283         if (frame.empty())
284         {
285             waitKey();
286             break;
287         }
288 
289         preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
290 
291         std::vector<Mat> outs;
292         net.forward(outs, outNames);
293 
294         postprocess(frame, outs, net, backend);
295 
296         // Put efficiency information.
297         std::vector<double> layersTimes;
298         double freq = getTickFrequency() / 1000;
299         double t = net.getPerfProfile(layersTimes) / freq;
300         std::string label = format("Inference time: %.2f ms", t);
301         putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
302 
303         imshow(kWinName, frame);
304     }
305 #endif  // CV_CXX11
306     return 0;
307 }
308 
preprocess(const Mat & frame,Net & net,Size inpSize,float scale,const Scalar & mean,bool swapRB)309 inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
310                        const Scalar& mean, bool swapRB)
311 {
312     static Mat blob;
313     // Create a 4D blob from a frame.
314     if (inpSize.width <= 0) inpSize.width = frame.cols;
315     if (inpSize.height <= 0) inpSize.height = frame.rows;
316     blobFromImage(frame, blob, 1.0, inpSize, Scalar(), swapRB, false, CV_8U);
317 
318     // Run a model.
319     net.setInput(blob, "", scale, mean);
320     if (net.getLayer(0)->outputNameToIndex("im_info") != -1)  // Faster-RCNN or R-FCN
321     {
322         resize(frame, frame, inpSize);
323         Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
324         net.setInput(imInfo, "im_info");
325     }
326 }
327 
postprocess(Mat & frame,const std::vector<Mat> & outs,Net & net,int backend)328 void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net, int backend)
329 {
330     static std::vector<int> outLayers = net.getUnconnectedOutLayers();
331     static std::string outLayerType = net.getLayer(outLayers[0])->type;
332 
333     std::vector<int> classIds;
334     std::vector<float> confidences;
335     std::vector<Rect> boxes;
336     if (outLayerType == "DetectionOutput")
337     {
338         // Network produces output blob with a shape 1x1xNx7 where N is a number of
339         // detections and an every detection is a vector of values
340         // [batchId, classId, confidence, left, top, right, bottom]
341         CV_Assert(outs.size() > 0);
342         for (size_t k = 0; k < outs.size(); k++)
343         {
344             float* data = (float*)outs[k].data;
345             for (size_t i = 0; i < outs[k].total(); i += 7)
346             {
347                 float confidence = data[i + 2];
348                 if (confidence > confThreshold)
349                 {
350                     int left   = (int)data[i + 3];
351                     int top    = (int)data[i + 4];
352                     int right  = (int)data[i + 5];
353                     int bottom = (int)data[i + 6];
354                     int width  = right - left + 1;
355                     int height = bottom - top + 1;
356                     if (width <= 2 || height <= 2)
357                     {
358                         left   = (int)(data[i + 3] * frame.cols);
359                         top    = (int)(data[i + 4] * frame.rows);
360                         right  = (int)(data[i + 5] * frame.cols);
361                         bottom = (int)(data[i + 6] * frame.rows);
362                         width  = right - left + 1;
363                         height = bottom - top + 1;
364                     }
365                     classIds.push_back((int)(data[i + 1]) - 1);  // Skip 0th background class id.
366                     boxes.push_back(Rect(left, top, width, height));
367                     confidences.push_back(confidence);
368                 }
369             }
370         }
371     }
372     else if (outLayerType == "Region")
373     {
374         for (size_t i = 0; i < outs.size(); ++i)
375         {
376             // Network produces output blob with a shape NxC where N is a number of
377             // detected objects and C is a number of classes + 4 where the first 4
378             // numbers are [center_x, center_y, width, height]
379             float* data = (float*)outs[i].data;
380             for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
381             {
382                 Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
383                 Point classIdPoint;
384                 double confidence;
385                 minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
386                 if (confidence > confThreshold)
387                 {
388                     int centerX = (int)(data[0] * frame.cols);
389                     int centerY = (int)(data[1] * frame.rows);
390                     int width = (int)(data[2] * frame.cols);
391                     int height = (int)(data[3] * frame.rows);
392                     int left = centerX - width / 2;
393                     int top = centerY - height / 2;
394 
395                     classIds.push_back(classIdPoint.x);
396                     confidences.push_back((float)confidence);
397                     boxes.push_back(Rect(left, top, width, height));
398                 }
399             }
400         }
401     }
402     else
403         CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType);
404 
405     // NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample
406     // or NMS is required if number of outputs > 1
407     if (outLayers.size() > 1 || (outLayerType == "Region" && backend != DNN_BACKEND_OPENCV))
408     {
409         std::map<int, std::vector<size_t> > class2indices;
410         for (size_t i = 0; i < classIds.size(); i++)
411         {
412             if (confidences[i] >= confThreshold)
413             {
414                 class2indices[classIds[i]].push_back(i);
415             }
416         }
417         std::vector<Rect> nmsBoxes;
418         std::vector<float> nmsConfidences;
419         std::vector<int> nmsClassIds;
420         for (std::map<int, std::vector<size_t> >::iterator it = class2indices.begin(); it != class2indices.end(); ++it)
421         {
422             std::vector<Rect> localBoxes;
423             std::vector<float> localConfidences;
424             std::vector<size_t> classIndices = it->second;
425             for (size_t i = 0; i < classIndices.size(); i++)
426             {
427                 localBoxes.push_back(boxes[classIndices[i]]);
428                 localConfidences.push_back(confidences[classIndices[i]]);
429             }
430             std::vector<int> nmsIndices;
431             NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices);
432             for (size_t i = 0; i < nmsIndices.size(); i++)
433             {
434                 size_t idx = nmsIndices[i];
435                 nmsBoxes.push_back(localBoxes[idx]);
436                 nmsConfidences.push_back(localConfidences[idx]);
437                 nmsClassIds.push_back(it->first);
438             }
439         }
440         boxes = nmsBoxes;
441         classIds = nmsClassIds;
442         confidences = nmsConfidences;
443     }
444 
445     for (size_t idx = 0; idx < boxes.size(); ++idx)
446     {
447         Rect box = boxes[idx];
448         drawPred(classIds[idx], confidences[idx], box.x, box.y,
449                  box.x + box.width, box.y + box.height, frame);
450     }
451 }
452 
drawPred(int classId,float conf,int left,int top,int right,int bottom,Mat & frame)453 void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
454 {
455     rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));
456 
457     std::string label = format("%.2f", conf);
458     if (!classes.empty())
459     {
460         CV_Assert(classId < (int)classes.size());
461         label = classes[classId] + ": " + label;
462     }
463 
464     int baseLine;
465     Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
466 
467     top = max(top, labelSize.height);
468     rectangle(frame, Point(left, top - labelSize.height),
469               Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
470     putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());
471 }
472 
callback(int pos,void *)473 void callback(int pos, void*)
474 {
475     confThreshold = pos * 0.01f;
476 }
477