1 // Copyright (c) 2021 by Rockchip Electronics Co., Ltd. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /*-------------------------------------------
16 Includes
17 -------------------------------------------*/
18 #include <dlfcn.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/time.h>
23
24 #define _BASETSD_H
25
26 #include "RgaUtils.h"
27 #include "im2d.h"
28 #include "opencv2/core/core.hpp"
29 #include "opencv2/imgcodecs.hpp"
30 #include "opencv2/imgproc.hpp"
31 #include "postprocess.h"
32 #include "rga.h"
33 #include "rknn_api.h"
34
35 #define PERF_WITH_POST 1
36 /*-------------------------------------------
37 Functions
38 -------------------------------------------*/
39
dump_tensor_attr(rknn_tensor_attr * attr)40 static void dump_tensor_attr(rknn_tensor_attr* attr)
41 {
42 std::string shape_str = attr->n_dims < 1 ? "" : std::to_string(attr->dims[0]);
43 for (int i = 1; i < attr->n_dims; ++i) {
44 shape_str += ", " + std::to_string(attr->dims[i]);
45 }
46
47 printf(" index=%d, name=%s, n_dims=%d, dims=[%s], n_elems=%d, size=%d, w_stride = %d, size_with_stride=%d, fmt=%s, "
48 "type=%s, qnt_type=%s, "
49 "zp=%d, scale=%f\n",
50 attr->index, attr->name, attr->n_dims, shape_str.c_str(), attr->n_elems, attr->size, attr->w_stride,
51 attr->size_with_stride, get_format_string(attr->fmt), get_type_string(attr->type),
52 get_qnt_type_string(attr->qnt_type), attr->zp, attr->scale);
53 }
54
__get_us(struct timeval t)55 double __get_us(struct timeval t) { return (t.tv_sec * 1000000 + t.tv_usec); }
56
load_data(FILE * fp,size_t ofst,size_t sz)57 static unsigned char* load_data(FILE* fp, size_t ofst, size_t sz)
58 {
59 unsigned char* data;
60 int ret;
61
62 data = NULL;
63
64 if (NULL == fp) {
65 return NULL;
66 }
67
68 ret = fseek(fp, ofst, SEEK_SET);
69 if (ret != 0) {
70 printf("blob seek failure.\n");
71 return NULL;
72 }
73
74 data = (unsigned char*)malloc(sz);
75 if (data == NULL) {
76 printf("buffer malloc failure.\n");
77 return NULL;
78 }
79 ret = fread(data, 1, sz, fp);
80 return data;
81 }
82
load_model(const char * filename,int * model_size)83 static unsigned char* load_model(const char* filename, int* model_size)
84 {
85 FILE* fp;
86 unsigned char* data;
87
88 fp = fopen(filename, "rb");
89 if (NULL == fp) {
90 printf("Open file %s failed.\n", filename);
91 return NULL;
92 }
93
94 fseek(fp, 0, SEEK_END);
95 int size = ftell(fp);
96
97 data = load_data(fp, 0, size);
98
99 fclose(fp);
100
101 *model_size = size;
102 return data;
103 }
104
saveFloat(const char * file_name,float * output,int element_size)105 static int saveFloat(const char* file_name, float* output, int element_size)
106 {
107 FILE* fp;
108 fp = fopen(file_name, "w");
109 for (int i = 0; i < element_size; i++) {
110 fprintf(fp, "%.6f\n", output[i]);
111 }
112 fclose(fp);
113 return 0;
114 }
115
116 /*-------------------------------------------
117 Main Functions
118 -------------------------------------------*/
main(int argc,char ** argv)119 int main(int argc, char** argv)
120 {
121 int status = 0;
122 char* model_name = NULL;
123 rknn_context ctx;
124 size_t actual_size = 0;
125 int img_width = 0;
126 int img_height = 0;
127 int img_channel = 0;
128 const float nms_threshold = NMS_THRESH;
129 const float box_conf_threshold = BOX_THRESH;
130 struct timeval start_time, stop_time;
131 int ret;
132
133 // init rga context
134 rga_buffer_t src;
135 rga_buffer_t dst;
136 im_rect src_rect;
137 im_rect dst_rect;
138 memset(&src_rect, 0, sizeof(src_rect));
139 memset(&dst_rect, 0, sizeof(dst_rect));
140 memset(&src, 0, sizeof(src));
141 memset(&dst, 0, sizeof(dst));
142
143 if (argc != 3) {
144 printf("Usage: %s <rknn model> <jpg> \n", argv[0]);
145 return -1;
146 }
147
148 printf("post process config: box_conf_threshold = %.2f, nms_threshold = %.2f\n", box_conf_threshold, nms_threshold);
149
150 model_name = (char*)argv[1];
151 char* image_name = argv[2];
152
153 printf("Read %s ...\n", image_name);
154 cv::Mat orig_img = cv::imread(image_name, 1);
155 if (!orig_img.data) {
156 printf("cv::imread %s fail!\n", image_name);
157 return -1;
158 }
159 cv::Mat img;
160 cv::cvtColor(orig_img, img, cv::COLOR_BGR2RGB);
161 img_width = img.cols;
162 img_height = img.rows;
163 printf("img width = %d, img height = %d\n", img_width, img_height);
164
165 /* Create the neural network */
166 printf("Loading mode...\n");
167 int model_data_size = 0;
168 unsigned char* model_data = load_model(model_name, &model_data_size);
169 ret = rknn_init(&ctx, model_data, model_data_size, 0, NULL);
170 if (ret < 0) {
171 printf("rknn_init error ret=%d\n", ret);
172 return -1;
173 }
174
175 rknn_sdk_version version;
176 ret = rknn_query(ctx, RKNN_QUERY_SDK_VERSION, &version, sizeof(rknn_sdk_version));
177 if (ret < 0) {
178 printf("rknn_init error ret=%d\n", ret);
179 return -1;
180 }
181 printf("sdk version: %s driver version: %s\n", version.api_version, version.drv_version);
182
183 rknn_input_output_num io_num;
184 ret = rknn_query(ctx, RKNN_QUERY_IN_OUT_NUM, &io_num, sizeof(io_num));
185 if (ret < 0) {
186 printf("rknn_init error ret=%d\n", ret);
187 return -1;
188 }
189 printf("model input num: %d, output num: %d\n", io_num.n_input, io_num.n_output);
190
191 rknn_tensor_attr input_attrs[io_num.n_input];
192 memset(input_attrs, 0, sizeof(input_attrs));
193 for (int i = 0; i < io_num.n_input; i++) {
194 input_attrs[i].index = i;
195 ret = rknn_query(ctx, RKNN_QUERY_INPUT_ATTR, &(input_attrs[i]), sizeof(rknn_tensor_attr));
196 if (ret < 0) {
197 printf("rknn_init error ret=%d\n", ret);
198 return -1;
199 }
200 dump_tensor_attr(&(input_attrs[i]));
201 }
202
203 rknn_tensor_attr output_attrs[io_num.n_output];
204 memset(output_attrs, 0, sizeof(output_attrs));
205 for (int i = 0; i < io_num.n_output; i++) {
206 output_attrs[i].index = i;
207 ret = rknn_query(ctx, RKNN_QUERY_OUTPUT_ATTR, &(output_attrs[i]), sizeof(rknn_tensor_attr));
208 dump_tensor_attr(&(output_attrs[i]));
209 }
210
211 int channel = 3;
212 int width = 0;
213 int height = 0;
214 if (input_attrs[0].fmt == RKNN_TENSOR_NCHW) {
215 printf("model is NCHW input fmt\n");
216 channel = input_attrs[0].dims[1];
217 height = input_attrs[0].dims[2];
218 width = input_attrs[0].dims[3];
219 } else {
220 printf("model is NHWC input fmt\n");
221 height = input_attrs[0].dims[1];
222 width = input_attrs[0].dims[2];
223 channel = input_attrs[0].dims[3];
224 }
225
226 printf("model input height=%d, width=%d, channel=%d\n", height, width, channel);
227
228 rknn_input inputs[1];
229 memset(inputs, 0, sizeof(inputs));
230 inputs[0].index = 0;
231 inputs[0].type = RKNN_TENSOR_UINT8;
232 inputs[0].size = width * height * channel;
233 inputs[0].fmt = RKNN_TENSOR_NHWC;
234 inputs[0].pass_through = 0;
235
236 // You may not need resize when src resulotion equals to dst resulotion
237 void* resize_buf = nullptr;
238
239 if (img_width != width || img_height != height) {
240 printf("resize with RGA!\n");
241 resize_buf = malloc(height * width * channel);
242 memset(resize_buf, 0x00, height * width * channel);
243
244 src = wrapbuffer_virtualaddr((void*)img.data, img_width, img_height, RK_FORMAT_RGB_888);
245 dst = wrapbuffer_virtualaddr((void*)resize_buf, width, height, RK_FORMAT_RGB_888);
246 ret = imcheck(src, dst, src_rect, dst_rect);
247 if (IM_STATUS_NOERROR != ret) {
248 printf("%d, check error! %s", __LINE__, imStrError((IM_STATUS)ret));
249 return -1;
250 }
251 IM_STATUS STATUS = imresize(src, dst);
252
253 // for debug
254 cv::Mat resize_img(cv::Size(width, height), CV_8UC3, resize_buf);
255 cv::imwrite("resize_input.jpg", resize_img);
256
257 inputs[0].buf = resize_buf;
258 } else {
259 inputs[0].buf = (void*)img.data;
260 }
261
262 gettimeofday(&start_time, NULL);
263 rknn_inputs_set(ctx, io_num.n_input, inputs);
264
265 rknn_output outputs[io_num.n_output];
266 memset(outputs, 0, sizeof(outputs));
267 for (int i = 0; i < io_num.n_output; i++) {
268 outputs[i].want_float = 0;
269 }
270
271 ret = rknn_run(ctx, NULL);
272 ret = rknn_outputs_get(ctx, io_num.n_output, outputs, NULL);
273 gettimeofday(&stop_time, NULL);
274 printf("once run use %f ms\n", (__get_us(stop_time) - __get_us(start_time)) / 1000);
275
276 // post process
277 float scale_w = (float)width / img_width;
278 float scale_h = (float)height / img_height;
279
280 detect_result_group_t detect_result_group;
281 std::vector<float> out_scales;
282 std::vector<int32_t> out_zps;
283 for (int i = 0; i < io_num.n_output; ++i) {
284 out_scales.push_back(output_attrs[i].scale);
285 out_zps.push_back(output_attrs[i].zp);
286 }
287 post_process((int8_t*)outputs[0].buf, (int8_t*)outputs[1].buf, (int8_t*)outputs[2].buf, height, width,
288 box_conf_threshold, nms_threshold, scale_w, scale_h, out_zps, out_scales, &detect_result_group);
289
290 // Draw Objects
291 char text[256];
292 for (int i = 0; i < detect_result_group.count; i++) {
293 detect_result_t* det_result = &(detect_result_group.results[i]);
294 sprintf(text, "%s %.1f%%", det_result->name, det_result->prop * 100);
295 printf("%s @ (%d %d %d %d) %f\n", det_result->name, det_result->box.left, det_result->box.top,
296 det_result->box.right, det_result->box.bottom, det_result->prop);
297 int x1 = det_result->box.left;
298 int y1 = det_result->box.top;
299 int x2 = det_result->box.right;
300 int y2 = det_result->box.bottom;
301 rectangle(orig_img, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(255, 0, 0, 255), 3);
302 putText(orig_img, text, cv::Point(x1, y1 + 12), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
303 }
304
305 imwrite("./out.jpg", orig_img);
306 ret = rknn_outputs_release(ctx, io_num.n_output, outputs);
307
308 // loop test
309 int test_count = 10;
310 gettimeofday(&start_time, NULL);
311 for (int i = 0; i < test_count; ++i) {
312 rknn_inputs_set(ctx, io_num.n_input, inputs);
313 ret = rknn_run(ctx, NULL);
314 ret = rknn_outputs_get(ctx, io_num.n_output, outputs, NULL);
315 #if PERF_WITH_POST
316 post_process((int8_t*)outputs[0].buf, (int8_t*)outputs[1].buf, (int8_t*)outputs[2].buf, height, width,
317 box_conf_threshold, nms_threshold, scale_w, scale_h, out_zps, out_scales, &detect_result_group);
318 #endif
319 ret = rknn_outputs_release(ctx, io_num.n_output, outputs);
320 }
321 gettimeofday(&stop_time, NULL);
322 printf("loop count = %d , average run %f ms\n", test_count,
323 (__get_us(stop_time) - __get_us(start_time)) / 1000.0 / test_count);
324
325 deinitPostProcess();
326
327 // release
328 ret = rknn_destroy(ctx);
329
330 if (model_data) {
331 free(model_data);
332 }
333
334 if (resize_buf) {
335 free(resize_buf);
336 }
337
338 return 0;
339 }
340