-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.cpp
312 lines (290 loc) · 10.4 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
//#include <cuda_provider_factory.h>
#include <onnxruntime_cxx_api.h>
using namespace cv;
using namespace std;
using namespace Ort;
typedef struct BoxInfo
{
float x1;
float y1;
float x2;
float y2;
float score;
int label;
} BoxInfo;
class PicoDet
{
public:
PicoDet(string model_path, string classesFile, float nms_threshold, float objThreshold);
void detect(Mat& cv_image);
private:
float score_threshold = 0.5;
float nms_threshold = 0.5;
vector<string> class_names;
int num_class;
Mat resize_image(Mat srcimg, int *newh, int *neww, int *top, int *left);
vector<float> input_image_;
void normalize_(Mat img);
void softmax_(const float* x, float* y, int length);
void generate_proposal(vector<BoxInfo>& generate_boxes, const int stride_, const float* out_score, const float* out_box);
void nms(vector<BoxInfo>& input_boxes);
const bool keep_ratio = true;
int inpWidth;
int inpHeight;
int num_outs;
int reg_max;
vector<int> stride;
const float mean[3] = { 103.53, 116.28, 123.675 };
const float stds[3] = { 57.375, 57.12, 58.395 };
Env env = Env(ORT_LOGGING_LEVEL_ERROR, "picodet");
Ort::Session *ort_session = nullptr;
SessionOptions sessionOptions = SessionOptions();
vector<char*> input_names;
vector<char*> output_names;
vector<vector<int64_t>> input_node_dims; // >=1 outputs
vector<vector<int64_t>> output_node_dims; // >=1 outputs
};
PicoDet::PicoDet(string model_path, string classesFile, float nms_threshold, float objThreshold)
{
ifstream ifs(classesFile.c_str());
string line;
while (getline(ifs, line)) this->class_names.push_back(line);
this->num_class = class_names.size();
this->nms_threshold = nms_threshold;
this->score_threshold = objThreshold;
std::wstring widestr = std::wstring(model_path.begin(), model_path.end());
//OrtStatus* status = OrtSessionOptionsAppendExecutionProvider_CUDA(sessionOptions, 0);
sessionOptions.SetGraphOptimizationLevel(ORT_ENABLE_BASIC);
ort_session = new Session(env, widestr.c_str(), sessionOptions);
size_t numInputNodes = ort_session->GetInputCount();
size_t numOutputNodes = ort_session->GetOutputCount();
AllocatorWithDefaultOptions allocator;
for (int i = 0; i < numInputNodes; i++)
{
input_names.push_back(ort_session->GetInputName(i, allocator));
Ort::TypeInfo input_type_info = ort_session->GetInputTypeInfo(i);
auto input_tensor_info = input_type_info.GetTensorTypeAndShapeInfo();
auto input_dims = input_tensor_info.GetShape();
input_node_dims.push_back(input_dims);
}
for (int i = 0; i < numOutputNodes; i++)
{
output_names.push_back(ort_session->GetOutputName(i, allocator));
Ort::TypeInfo output_type_info = ort_session->GetOutputTypeInfo(i);
auto output_tensor_info = output_type_info.GetTensorTypeAndShapeInfo();
auto output_dims = output_tensor_info.GetShape();
output_node_dims.push_back(output_dims);
/*for (int j = 0; j < output_dims.size(); j++)
{
cout << output_dims[j] << ",";
}
cout << endl;*/
}
this->inpHeight = input_node_dims[0][2];
this->inpWidth = input_node_dims[0][3];
this->num_outs = int(numOutputNodes * 0.5);
this->reg_max = output_node_dims[this->num_outs][output_node_dims[this->num_outs].size() - 1] / 4 - 1;
for (int i = 0; i < this->num_outs; i++)
{
stride.push_back(int(8 * pow(2, i)));
}
}
Mat PicoDet::resize_image(Mat srcimg, int *newh, int *neww, int *top, int *left)
{
int srch = srcimg.rows, srcw = srcimg.cols;
*newh = this->inpHeight;
*neww = this->inpWidth;
Mat dstimg;
if (this->keep_ratio && srch != srcw) {
float hw_scale = (float)srch / srcw;
if (hw_scale > 1) {
*newh = this->inpHeight;
*neww = int(this->inpWidth / hw_scale);
resize(srcimg, dstimg, Size(*neww, *newh), INTER_AREA);
*left = int((this->inpWidth - *neww) * 0.5);
copyMakeBorder(dstimg, dstimg, 0, 0, *left, this->inpWidth - *neww - *left, BORDER_CONSTANT, 0);
}
else {
*newh = (int)this->inpHeight * hw_scale;
*neww = this->inpWidth;
resize(srcimg, dstimg, Size(*neww, *newh), INTER_AREA);
*top = (int)(this->inpHeight - *newh) * 0.5;
copyMakeBorder(dstimg, dstimg, *top, this->inpHeight - *newh - *top, 0, 0, BORDER_CONSTANT, 0);
}
}
else {
resize(srcimg, dstimg, Size(*neww, *newh), INTER_AREA);
}
return dstimg;
}
void PicoDet::normalize_(Mat img)
{
// img.convertTo(img, CV_32F);
int row = img.rows;
int col = img.cols;
this->input_image_.resize(row * col * img.channels());
for (int c = 0; c < 3; c++)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
float pix = img.ptr<uchar>(i)[j * 3 + c];
this->input_image_[c * row * col + i * col + j] = (pix / 255.0 - mean[c] / 255.0) / (stds[c] / 255.0);
//this->input_image_[c * row * col + i * col + j] = (pix - mean[c]) / stds[c];
}
}
}
}
void PicoDet::softmax_(const float* x, float* y, int length)
{
float sum = 0;
int i = 0;
for (i = 0; i < length; i++)
{
y[i] = exp(x[i]);
sum += y[i];
}
for (i = 0; i < length; i++)
{
y[i] /= sum;
}
}
void PicoDet::generate_proposal(vector<BoxInfo>& generate_boxes, const int stride_, const float* out_score, const float* out_box)
{
const int num_grid_y = (int)ceil((float)this->inpHeight / stride_);
const int num_grid_x = (int)ceil((float)this->inpWidth / stride_);
////cout << "num_grid_x=" << num_grid_x << ",num_grid_y=" << num_grid_y << endl;
const int reg_1max = reg_max + 1;
for (int i = 0; i < num_grid_y; i++)
{
for (int j = 0; j < num_grid_x; j++)
{
const int idx = i * num_grid_x + j;
const float* scores = out_score + idx * num_class;
int max_ind = 0;
float max_score = 0;
for (int k = 0; k < num_class; k++)
{
if (scores[k] > max_score)
{
max_score = scores[k];
max_ind = k;
}
}
if (max_score >= score_threshold)
{
const float* pbox = out_box + idx * reg_1max * 4;
float dis_pred[4];
float* y = new float[reg_1max];
for (int k = 0; k < 4; k++)
{
softmax_(pbox + k * reg_1max, y, reg_1max);
float dis = 0.f;
for (int l = 0; l < reg_1max; l++)
{
dis += l * y[l];
}
dis_pred[k] = dis * stride_;
}
delete[] y;
float pb_cx = (j + 0.5f) * stride_ - 0.5;
float pb_cy = (i + 0.5f) * stride_ - 0.5;
float x0 = pb_cx - dis_pred[0];
float y0 = pb_cy - dis_pred[1];
float x1 = pb_cx + dis_pred[2];
float y1 = pb_cy + dis_pred[3];
generate_boxes.push_back(BoxInfo{ x0, y0, x1, y1, max_score, max_ind });
}
}
}
}
void PicoDet::nms(vector<BoxInfo>& input_boxes)
{
sort(input_boxes.begin(), input_boxes.end(), [](BoxInfo a, BoxInfo b) { return a.score > b.score; });
vector<float> vArea(input_boxes.size());
for (int i = 0; i < int(input_boxes.size()); ++i)
{
vArea[i] = (input_boxes.at(i).x2 - input_boxes.at(i).x1 + 1)
* (input_boxes.at(i).y2 - input_boxes.at(i).y1 + 1);
}
vector<bool> isSuppressed(input_boxes.size(), false);
for (int i = 0; i < int(input_boxes.size()); ++i)
{
if (isSuppressed[i]) { continue; }
for (int j = i + 1; j < int(input_boxes.size()); ++j)
{
if (isSuppressed[j]) { continue; }
float xx1 = (max)(input_boxes[i].x1, input_boxes[j].x1);
float yy1 = (max)(input_boxes[i].y1, input_boxes[j].y1);
float xx2 = (min)(input_boxes[i].x2, input_boxes[j].x2);
float yy2 = (min)(input_boxes[i].y2, input_boxes[j].y2);
float w = (max)(float(0), xx2 - xx1 + 1);
float h = (max)(float(0), yy2 - yy1 + 1);
float inter = w * h;
float ovr = inter / (vArea[i] + vArea[j] - inter);
if (ovr >= this->nms_threshold)
{
isSuppressed[j] = true;
}
}
}
// return post_nms;
int idx_t = 0;
input_boxes.erase(remove_if(input_boxes.begin(), input_boxes.end(), [&idx_t, &isSuppressed](const BoxInfo& f) { return isSuppressed[idx_t++]; }), input_boxes.end());
}
void PicoDet::detect(Mat& srcimg)
{
int newh = 0, neww = 0, top = 0, left = 0;
Mat cv_image = srcimg.clone();
Mat dst = this->resize_image(cv_image, &newh, &neww, &top, &left);
this->normalize_(dst);
array<int64_t, 4> input_shape_{ 1, 3, this->inpHeight, this->inpWidth };
auto allocator_info = MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
Value input_tensor_ = Value::CreateTensor<float>(allocator_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
// ¿ªÊ¼ÍÆÀí
vector<Value> ort_outputs = ort_session->Run(RunOptions{ nullptr }, &input_names[0], &input_tensor_, 1, output_names.data(), output_names.size()); // ¿ªÊ¼ÍÆÀí
/////generate proposals
vector<BoxInfo> generate_boxes;
for (int i = 0; i < this->num_outs; i++)
{
const float* cls_score = ort_outputs[i].GetTensorMutableData<float>();
const float* bbox_pred = ort_outputs[i + this->num_outs].GetTensorMutableData<float>();
generate_proposal(generate_boxes, stride[i], cls_score, bbox_pred);
}
//// Perform non maximum suppression to eliminate redundant overlapping boxes with
//// lower confidences
nms(generate_boxes);
float ratioh = (float)cv_image.rows / newh;
float ratiow = (float)cv_image.cols / neww;
for (size_t i = 0; i < generate_boxes.size(); ++i)
{
int xmin = (int)max((generate_boxes[i].x1 - left)*ratiow, 0.f);
int ymin = (int)max((generate_boxes[i].y1 - top)*ratioh, 0.f);
int xmax = (int)min((generate_boxes[i].x2 - left)*ratiow, (float)cv_image.cols);
int ymax = (int)min((generate_boxes[i].y2 - top)*ratioh, (float)cv_image.rows);
rectangle(srcimg, Point(xmin, ymin), Point(xmax, ymax), Scalar(0, 0, 255), 2);
string label = format("%.2f", generate_boxes[i].score);
label = this->class_names[generate_boxes[i].label] + ":" + label;
putText(srcimg, label, Point(xmin, ymin - 5), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 255, 0), 1);
}
}
int main()
{
PicoDet mynet("coco/picodet_m_416_coco.onnx", "coco/coco.names", 0.5, 0.5); /// choice = ["picodet_m_320_coco.onnx", "picodet_m_416_coco.onnx", "picodet_s_320_coco.onnx", "picodet_s_416_coco.onnx"]
string imgpath = "coco/person.jpg";
Mat srcimg = imread(imgpath);
mynet.detect(srcimg);
static const string kWinName = "Deep learning object detection in ONNXRuntime";
namedWindow(kWinName, WINDOW_NORMAL);
imshow(kWinName, srcimg);
waitKey(0);
destroyAllWindows();
}