Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/segmentation.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. }"
18
"{ colors | | Optional path to a text file with colors for an every class. "
19
"An every color is represented with three values from 0 to 255 in BGR channels order. }"
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
using namespace cv;
32
using namespace dnn;
33
34
std::vector<std::string> classes;
35
std::vector<Vec3b> colors;
36
37
void showLegend();
38
39
void colorizeSegmentation(const Mat &score, Mat &segm);
40
41
int main(int argc, char** argv)
42
{
43
CommandLineParser parser(argc, argv, keys);
44
45
const std::string modelName = parser.get<String>("@alias");
46
const std::string zooFile = parser.get<String>("zoo");
47
48
keys += genPreprocArguments(modelName, zooFile);
49
50
parser = CommandLineParser(argc, argv, keys);
51
parser.about("Use this script to run semantic segmentation deep learning networks using OpenCV.");
52
if (argc == 1 || parser.has("help"))
53
{
54
parser.printMessage();
55
return 0;
56
}
57
58
float scale = parser.get<float>("scale");
59
Scalar mean = parser.get<Scalar>("mean");
60
bool swapRB = parser.get<bool>("rgb");
61
int inpWidth = parser.get<int>("width");
62
int inpHeight = parser.get<int>("height");
63
String model = findFile(parser.get<String>("model"));
64
String config = findFile(parser.get<String>("config"));
65
String framework = parser.get<String>("framework");
66
int backendId = parser.get<int>("backend");
67
int targetId = parser.get<int>("target");
68
69
// Open file with classes names.
70
if (parser.has("classes"))
71
{
72
std::string file = parser.get<String>("classes");
73
std::ifstream ifs(file.c_str());
74
if (!ifs.is_open())
75
CV_Error(Error::StsError, "File " + file + " not found");
76
std::string line;
77
while (std::getline(ifs, line))
78
{
79
classes.push_back(line);
80
}
81
}
82
83
// Open file with colors.
84
if (parser.has("colors"))
85
{
86
std::string file = parser.get<String>("colors");
87
std::ifstream ifs(file.c_str());
88
if (!ifs.is_open())
89
CV_Error(Error::StsError, "File " + file + " not found");
90
std::string line;
91
while (std::getline(ifs, line))
92
{
93
std::istringstream colorStr(line.c_str());
94
95
Vec3b color;
96
for (int i = 0; i < 3 && !colorStr.eof(); ++i)
97
colorStr >> color[i];
98
colors.push_back(color);
99
}
100
}
101
102
if (!parser.check())
103
{
104
parser.printErrors();
105
return 1;
106
}
107
108
CV_Assert(!model.empty());
109
//! [Read and initialize network]
110
Net net = readNet(model, config, framework);
111
net.setPreferableBackend(backendId);
112
net.setPreferableTarget(targetId);
113
//! [Read and initialize network]
114
115
// Create a window
116
static const std::string kWinName = "Deep learning semantic segmentation in OpenCV";
117
namedWindow(kWinName, WINDOW_NORMAL);
118
119
//! [Open a video file or an image file or a camera stream]
120
VideoCapture cap;
121
if (parser.has("input"))
122
cap.open(parser.get<String>("input"));
123
else
124
cap.open(parser.get<int>("device"));
125
//! [Open a video file or an image file or a camera stream]
126
127
// Process frames.
128
Mat frame, blob;
129
while (waitKey(1) < 0)
130
{
131
cap >> frame;
132
if (frame.empty())
133
{
134
waitKey();
135
break;
136
}
137
138
//! [Create a 4D blob from a frame]
139
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, false);
140
//! [Create a 4D blob from a frame]
141
142
//! [Set input blob]
143
net.setInput(blob);
144
//! [Set input blob]
145
//! [Make forward pass]
146
Mat score = net.forward();
147
//! [Make forward pass]
148
149
Mat segm;
150
colorizeSegmentation(score, segm);
151
152
resize(segm, segm, frame.size(), 0, 0, INTER_NEAREST);
153
addWeighted(frame, 0.1, segm, 0.9, 0.0, frame);
154
155
// Put efficiency information.
156
std::vector<double> layersTimes;
157
double freq = getTickFrequency() / 1000;
158
double t = net.getPerfProfile(layersTimes) / freq;
159
std::string label = format("Inference time: %.2f ms", t);
160
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
161
162
imshow(kWinName, frame);
163
if (!classes.empty())
164
showLegend();
165
}
166
return 0;
167
}
168
169
void colorizeSegmentation(const Mat &score, Mat &segm)
170
{
171
const int rows = score.size[2];
172
const int cols = score.size[3];
173
const int chns = score.size[1];
174
175
if (colors.empty())
176
{
177
// Generate colors.
178
colors.push_back(Vec3b());
179
for (int i = 1; i < chns; ++i)
180
{
181
Vec3b color;
182
for (int j = 0; j < 3; ++j)
183
color[j] = (colors[i - 1][j] + rand() % 256) / 2;
184
colors.push_back(color);
185
}
186
}
187
else if (chns != (int)colors.size())
188
{
189
CV_Error(Error::StsError, format("Number of output classes does not match "
190
"number of colors (%d != %zu)", chns, colors.size()));
191
}
192
193
Mat maxCl = Mat::zeros(rows, cols, CV_8UC1);
194
Mat maxVal(rows, cols, CV_32FC1, score.data);
195
for (int ch = 1; ch < chns; ch++)
196
{
197
for (int row = 0; row < rows; row++)
198
{
199
const float *ptrScore = score.ptr<float>(0, ch, row);
200
uint8_t *ptrMaxCl = maxCl.ptr<uint8_t>(row);
201
float *ptrMaxVal = maxVal.ptr<float>(row);
202
for (int col = 0; col < cols; col++)
203
{
204
if (ptrScore[col] > ptrMaxVal[col])
205
{
206
ptrMaxVal[col] = ptrScore[col];
207
ptrMaxCl[col] = (uchar)ch;
208
}
209
}
210
}
211
}
212
213
segm.create(rows, cols, CV_8UC3);
214
for (int row = 0; row < rows; row++)
215
{
216
const uchar *ptrMaxCl = maxCl.ptr<uchar>(row);
217
Vec3b *ptrSegm = segm.ptr<Vec3b>(row);
218
for (int col = 0; col < cols; col++)
219
{
220
ptrSegm[col] = colors[ptrMaxCl[col]];
221
}
222
}
223
}
224
225
void showLegend()
226
{
227
static const int kBlockHeight = 30;
228
static Mat legend;
229
if (legend.empty())
230
{
231
const int numClasses = (int)classes.size();
232
if ((int)colors.size() != numClasses)
233
{
234
CV_Error(Error::StsError, format("Number of output classes does not match "
235
"number of labels (%zu != %zu)", colors.size(), classes.size()));
236
}
237
legend.create(kBlockHeight * numClasses, 200, CV_8UC3);
238
for (int i = 0; i < numClasses; i++)
239
{
240
Mat block = legend.rowRange(i * kBlockHeight, (i + 1) * kBlockHeight);
241
block.setTo(colors[i]);
242
putText(block, classes[i], Point(0, kBlockHeight / 2), FONT_HERSHEY_SIMPLEX, 0.5, Vec3b(255, 255, 255));
243
}
244
namedWindow("Legend", WINDOW_NORMAL);
245
imshow("Legend", legend);
246
}
247
}
248
249