Skip to content

Commit 3109f65

Browse files
authored
Merge pull request #3435 from ivikhrev/fix-code-style-model-api-demos
Fix code style for cpp model api demos
2 parents 06b1d1d + fce7ed3 commit 3109f65

File tree

69 files changed

+2795
-1970
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+2795
-1970
lines changed
Lines changed: 46 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
1-
// Copyright (C) 2018-2019 Intel Corporation
1+
// Copyright (C) 2018-2022 Intel Corporation
22
// SPDX-License-Identifier: Apache-2.0
33
//
44

55
#pragma once
66

77
#include <algorithm>
8+
#include <queue>
89
#include <set>
910
#include <string>
1011
#include <vector>
11-
#include <queue>
12+
13+
#include <opencv2/core.hpp>
14+
#include <opencv2/imgproc.hpp>
1215

1316
#include <monitors/presenter.h>
1417
#include <utils/ocv_common.hpp>
1518

16-
#include <opencv2/imgproc.hpp>
17-
#include <opencv2/core.hpp>
18-
19-
enum class PredictionResult { Correct,
20-
Incorrect,
21-
Unknown };
19+
enum class PredictionResult { Correct, Incorrect, Unknown };
2220

2321
class GridMat {
2422
public:
@@ -27,9 +25,8 @@ class GridMat {
2725
explicit GridMat(Presenter& presenter,
2826
const cv::Size maxDisp = cv::Size{1920, 1080},
2927
const cv::Size aspectRatio = cv::Size{16, 9},
30-
double targetFPS = 60
31-
):
32-
currSourceId{0} {
28+
double targetFPS = 60)
29+
: currSourceId{0} {
3330
cv::Size size(static_cast<int>(std::round(sqrt(1. * targetFPS * aspectRatio.width / aspectRatio.height))),
3431
static_cast<int>(std::round(sqrt(1. * targetFPS * aspectRatio.height / aspectRatio.width))));
3532
if (size.width == 0 || size.height == 0) {
@@ -45,12 +42,13 @@ class GridMat {
4542
}
4643

4744
outImg.create((cellSize.height * size.height) + presenter.graphSize.height,
48-
cellSize.width * size.width, CV_8UC3);
45+
cellSize.width * size.width,
46+
CV_8UC3);
4947
outImg.setTo(0);
5048

5149
textSize = cv::getTextSize("", fontType, fontScale, thickness, &baseline);
5250
accuracyMessageSize = cv::getTextSize("Accuracy (top 0): 0.000", fontType, fontScale, thickness, &baseline);
53-
testMessageSize = cv::getTextSize(testMessage, fontType, fontScale, thickness, &baseline);
51+
testMessageSize = cv::getTextSize(GridMat::testMessage, fontType, fontScale, thickness, &baseline);
5452
}
5553

5654
void textUpdate(PerformanceMetrics& metrics,
@@ -60,28 +58,37 @@ class GridMat {
6058
bool isFpsTest,
6159
bool showAccuracy,
6260
Presenter& presenter) {
63-
rectangle(outImg,
64-
{0, 0}, {outImg.cols, presenter.graphSize.height},
65-
cv::Scalar(0, 0, 0), cv::FILLED);
61+
rectangle(outImg, {0, 0}, {outImg.cols, presenter.graphSize.height}, cv::Scalar(0, 0, 0), cv::FILLED);
6662

6763
presenter.drawGraphs(outImg);
6864

69-
metrics.update(lastRequestStartTime, outImg, cv::Point(textPadding, textSize.height + textPadding),
70-
fontType, fontScale, cv::Scalar(255, 100, 100), thickness);
65+
metrics.update(lastRequestStartTime,
66+
outImg,
67+
cv::Point(textPadding, textSize.height + textPadding),
68+
fontType,
69+
fontScale,
70+
cv::Scalar(255, 100, 100),
71+
thickness);
7172

7273
if (showAccuracy) {
7374
cv::putText(outImg,
7475
cv::format("Accuracy (top %d): %.3f", nTop, accuracy),
7576
cv::Point(outImg.cols - accuracyMessageSize.width - textPadding, textSize.height + textPadding),
76-
fontType, fontScale, cv::Scalar(255, 255, 255), thickness);
77+
fontType,
78+
fontScale,
79+
cv::Scalar(255, 255, 255),
80+
thickness);
7781
}
7882

7983
if (isFpsTest) {
80-
cv::putText(outImg,
81-
testMessage,
82-
cv::Point(outImg.cols - testMessageSize.width - textPadding,
83-
(textSize.height + textPadding) * 2),
84-
fontType, fontScale, cv::Scalar(50, 50, 255), thickness);
84+
cv::putText(
85+
outImg,
86+
GridMat::testMessage,
87+
cv::Point(outImg.cols - testMessageSize.width - textPadding, (textSize.height + textPadding) * 2),
88+
fontType,
89+
fontScale,
90+
cv::Scalar(50, 50, 255),
91+
thickness);
8592
}
8693
}
8794

@@ -94,21 +101,28 @@ class GridMat {
94101
cv::Scalar textColor;
95102
switch (predictionResul) {
96103
case PredictionResult::Correct:
97-
textColor = cv::Scalar(75, 255, 75); break; // green
104+
textColor = cv::Scalar(75, 255, 75); // green
105+
break;
98106
case PredictionResult::Incorrect:
99-
textColor = cv::Scalar(50, 50, 255); break; // red
107+
textColor = cv::Scalar(50, 50, 255); // red
108+
break;
100109
case PredictionResult::Unknown:
101-
textColor = cv::Scalar(200, 10, 10); break; // blue
110+
textColor = cv::Scalar(200, 10, 10); // blue
111+
break;
102112
default:
103113
throw std::runtime_error("Undefined type of prediction result");
104114
}
105115
int labelThickness = cellSize.width / 20;
106116
cv::Size labelTextSize = cv::getTextSize(label, fontType, 1, 2, &baseline);
107117
double labelFontScale = static_cast<double>(cellSize.width - 2 * labelThickness) / labelTextSize.width;
108118
cv::resize(mat, prevImg, cellSize);
109-
putHighlightedText(prevImg, label,
110-
cv::Point(labelThickness, cellSize.height - labelThickness - labelTextSize.height),
111-
fontType, labelFontScale, textColor, 2);
119+
putHighlightedText(prevImg,
120+
label,
121+
cv::Point(labelThickness, cellSize.height - labelThickness - labelTextSize.height),
122+
fontType,
123+
labelFontScale,
124+
textColor,
125+
2);
112126
cv::Mat cell = outImg(cv::Rect(points[currSourceId], cellSize));
113127
prevImg.copyTo(cell);
114128
cv::rectangle(cell, {0, 0}, {cell.cols, cell.rows}, {255, 50, 50}, labelThickness); // draw a border
@@ -129,11 +143,11 @@ class GridMat {
129143
static constexpr double fontScale = 1.5;
130144
static const int thickness = 2;
131145
static const int textPadding = 10;
132-
static const std::string testMessage;
146+
static constexpr const char testMessage[] = "Testing, please wait...";
133147
int baseline;
134148
cv::Size textSize;
135149
cv::Size accuracyMessageSize;
136150
cv::Size testMessageSize;
137151
};
138152

139-
const std::string GridMat::testMessage = "Testing, please wait...";
153+
constexpr const char GridMat::testMessage[];

demos/classification_benchmark_demo/cpp/main.cpp

Lines changed: 57 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,38 @@
22
// SPDX-License-Identifier: Apache-2.0
33
//
44

5+
#include <stddef.h>
6+
7+
#include <algorithm>
58
#include <chrono>
9+
#include <exception>
610
#include <fstream>
711
#include <iostream>
812
#include <limits>
13+
#include <map>
14+
#include <memory>
15+
#include <ratio>
16+
#include <stdexcept>
917
#include <string>
18+
#include <utility>
1019
#include <vector>
1120

1221
#include <gflags/gflags.h>
13-
#include <opencv2/opencv.hpp>
22+
#include <opencv2/core.hpp>
23+
#include <opencv2/highgui.hpp>
24+
#include <opencv2/imgcodecs.hpp>
1425
#include <openvino/openvino.hpp>
1526

1627
#include <models/classification_model.h>
28+
#include <models/input_data.h>
29+
#include <models/model_base.h>
1730
#include <models/results.h>
31+
#include <monitors/presenter.h>
1832
#include <pipelines/async_pipeline.h>
1933
#include <pipelines/metadata.h>
20-
2134
#include <utils/args_helper.hpp>
2235
#include <utils/common.hpp>
23-
#include <utils/ocv_common.hpp>
36+
#include <utils/config_factory.h>
2437
#include <utils/performance_metrics.hpp>
2538
#include <utils/slog.hpp>
2639

@@ -88,7 +101,7 @@ static void showUsage() {
88101
std::cout << " -u " << utilization_monitors_message << std::endl;
89102
}
90103

91-
bool ParseAndCheckCommandLine(int argc, char *argv[]) {
104+
bool ParseAndCheckCommandLine(int argc, char* argv[]) {
92105
// ---------------------------Parsing and validation of input args--------------------------------------
93106
gflags::ParseCommandLineNonHelpFlags(&argc, &argv, true);
94107
if (FLAGS_h) {
@@ -119,7 +132,7 @@ cv::Mat centerSquareCrop(const cv::Mat& image) {
119132
return image(cv::Rect(0, (image.rows - image.cols) / 2, image.cols, image.cols));
120133
}
121134

122-
int main(int argc, char *argv[]) {
135+
int main(int argc, char* argv[]) {
123136
try {
124137
PerformanceMetrics metrics, readerMetrics, renderMetrics;
125138

@@ -132,7 +145,8 @@ int main(int argc, char *argv[]) {
132145
std::vector<std::string> imageNames;
133146
std::vector<cv::Mat> inputImages;
134147
parseInputFilesArguments(imageNames);
135-
if (imageNames.empty()) throw std::runtime_error("No images provided");
148+
if (imageNames.empty())
149+
throw std::runtime_error("No images provided");
136150
std::sort(imageNames.begin(), imageNames.end());
137151
for (size_t i = 0; i < imageNames.size(); i++) {
138152
const std::string& name = imageNames[i];
@@ -194,18 +208,20 @@ int main(int argc, char *argv[]) {
194208

195209
//------------------------------ Running routines ----------------------------------------------
196210
std::vector<std::string> labels = ClassificationModel::loadLabels(FLAGS_labels);
197-
for (const auto & classIndex : classIndices) {
211+
for (const auto& classIndex : classIndices) {
198212
if (classIndex >= labels.size()) {
199-
throw std::runtime_error("Class index " + std::to_string(classIndex)
200-
+ " is outside the range supported by the model.");
201-
}
213+
throw std::runtime_error("Class index " + std::to_string(classIndex) +
214+
" is outside the range supported by the model.");
215+
}
202216
}
203217

204218
slog::info << ov::get_openvino_version() << slog::endl;
205219
ov::Core core;
206220

207-
AsyncPipeline pipeline(std::unique_ptr<ModelBase>(new ClassificationModel(FLAGS_m, FLAGS_nt, FLAGS_auto_resize, labels, FLAGS_layout)),
208-
ConfigFactory::getUserConfig(FLAGS_d, FLAGS_nireq, FLAGS_nstreams, FLAGS_nthreads), core);
221+
AsyncPipeline pipeline(std::unique_ptr<ModelBase>(
222+
new ClassificationModel(FLAGS_m, FLAGS_nt, FLAGS_auto_resize, labels, FLAGS_layout)),
223+
ConfigFactory::getUserConfig(FLAGS_d, FLAGS_nireq, FLAGS_nstreams, FLAGS_nthreads),
224+
core);
209225

210226
Presenter presenter(FLAGS_u, 0);
211227
int width;
@@ -238,9 +254,11 @@ int main(int argc, char *argv[]) {
238254
if (isTestMode && elapsedSeconds >= testDuration) {
239255
isTestMode = false;
240256
typedef std::chrono::duration<double, std::chrono::seconds::period> Sec;
241-
gridMat = GridMat(presenter, cv::Size(width, height), cv::Size(16, 9),
242-
(framesNum - framesNumOnCalculationStart) / std::chrono::duration_cast<Sec>(
243-
fpsCalculationDuration).count());
257+
gridMat = GridMat(presenter,
258+
cv::Size(width, height),
259+
cv::Size(16, 9),
260+
(framesNum - framesNumOnCalculationStart) /
261+
std::chrono::duration_cast<Sec>(fpsCalculationDuration).count());
244262
metrics = PerformanceMetrics();
245263
startTime = std::chrono::steady_clock::now();
246264
framesNum = 0;
@@ -252,14 +270,17 @@ int main(int argc, char *argv[]) {
252270
auto imageStartTime = std::chrono::steady_clock::now();
253271

254272
pipeline.submitData(ImageInputData(inputImages[nextImageIndex]),
255-
std::make_shared<ClassificationImageMetaData>(inputImages[nextImageIndex], imageStartTime, classIndices[nextImageIndex]));
273+
std::make_shared<ClassificationImageMetaData>(inputImages[nextImageIndex],
274+
imageStartTime,
275+
classIndices[nextImageIndex]));
256276
nextImageIndex++;
257277
if (nextImageIndex == imageNames.size()) {
258278
nextImageIndex = 0;
259279
}
260280
}
261281

262-
//--- Waiting for free input slot or output data available. Function will return immediately if any of them are available.
282+
//--- Waiting for free input slot or output data available. Function will return immediately if any of them
283+
// are available.
263284
pipeline.waitForData(false);
264285

265286
//--- Checking for results and rendering data if it's ready
@@ -269,8 +290,8 @@ int main(int argc, char *argv[]) {
269290
if (!classificationResult.metaData) {
270291
throw std::invalid_argument("Renderer: metadata is null");
271292
}
272-
const ClassificationImageMetaData& classificationImageMetaData
273-
= classificationResult.metaData->asRef<const ClassificationImageMetaData>();
293+
const ClassificationImageMetaData& classificationImageMetaData =
294+
classificationResult.metaData->asRef<const ClassificationImageMetaData>();
274295

275296
auto outputImg = classificationImageMetaData.img;
276297

@@ -295,8 +316,13 @@ int main(int argc, char *argv[]) {
295316
framesNum++;
296317
gridMat.updateMat(outputImg, label, predictionResult);
297318
accuracy = static_cast<double>(correctPredictionsCount) / framesNum;
298-
gridMat.textUpdate(metrics, classificationResult.metaData->asRef<ImageMetaData>().timeStamp, accuracy, FLAGS_nt, isTestMode,
299-
!FLAGS_gt.empty(), presenter);
319+
gridMat.textUpdate(metrics,
320+
classificationResult.metaData->asRef<ImageMetaData>().timeStamp,
321+
accuracy,
322+
FLAGS_nt,
323+
isTestMode,
324+
!FLAGS_gt.empty(),
325+
presenter);
300326
renderMetrics.update(renderingStart);
301327
elapsedSeconds = std::chrono::steady_clock::now() - startTime;
302328
if (!FLAGS_no_show) {
@@ -305,17 +331,16 @@ int main(int argc, char *argv[]) {
305331
int key = cv::waitKey(1);
306332
if (27 == key || 'q' == key || 'Q' == key) { // Esc
307333
keepRunning = false;
308-
}
309-
else if (32 == key || 'r' == key || 'R' == key) { // press space or r to restart testing if needed
334+
} else if (32 == key || 'r' == key ||
335+
'R' == key) { // press space or r to restart testing if needed
310336
isTestMode = true;
311337
framesNum = 0;
312338
framesNumOnCalculationStart = 0;
313339
correctPredictionsCount = 0;
314340
accuracy = 0;
315341
elapsedSeconds = std::chrono::steady_clock::duration(0);
316342
startTime = std::chrono::steady_clock::now();
317-
}
318-
else {
343+
} else {
319344
presenter.handleKey(key);
320345
}
321346
}
@@ -328,16 +353,16 @@ int main(int argc, char *argv[]) {
328353

329354
slog::info << "Metrics report:" << slog::endl;
330355
metrics.logTotal();
331-
logLatencyPerStage(readerMetrics.getTotal().latency, pipeline.getPreprocessMetrics().getTotal().latency,
332-
pipeline.getInferenceMetircs().getTotal().latency, pipeline.getPostprocessMetrics().getTotal().latency,
333-
renderMetrics.getTotal().latency);
356+
logLatencyPerStage(readerMetrics.getTotal().latency,
357+
pipeline.getPreprocessMetrics().getTotal().latency,
358+
pipeline.getInferenceMetircs().getTotal().latency,
359+
pipeline.getPostprocessMetrics().getTotal().latency,
360+
renderMetrics.getTotal().latency);
334361
slog::info << presenter.reportMeans() << slog::endl;
335-
}
336-
catch (const std::exception& error) {
362+
} catch (const std::exception& error) {
337363
slog::err << error.what() << slog::endl;
338364
return 1;
339-
}
340-
catch (...) {
365+
} catch (...) {
341366
slog::err << "Unknown/internal exception happened." << slog::endl;
342367
return 1;
343368
}

0 commit comments

Comments
 (0)