Так помогай у меня можно скомпилировать только СИ код
это main.cc
переделай ничего не добавляй
// Copyright (c) 2021 by Rockchip Electronics Co., Ltd. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/-------------------------------------------
Includes
-------------------------------------------/
#include "rknn_api.h"
if (fread(file_data, 1, size, fp) != size)
{
fclose(fp);
free(file_data);
printf("failed to read file data!\n");
return NULL;
}
fclose(fp);
*file_size = size;
return file_data;
}
static unsigned char *load_image(const char *image_path, rknn_tensor_attr *input_attr, int *img_height, int *img_width)
{
int req_height = 0;
int req_width = 0;
int req_channel = 0;
Assistant
User
Assistant
User
Лучшее решение — сделать postprocess.c в стиле С и подключать его к вашему C-коду.
typedef struct _detect_result_group_t
{
int id;
int count;
detect_result_t results[OBJ_NUMB_MAX_SIZE];
} detect_result_group_t;
int post_process(int8_t *input0, int8_t *input1, int8_t *input2, int model_in_h, int model_in_w,
float conf_threshold, float nms_threshold, float scale_w, float scale_h,
std::vector<int32_t> &qnt_zps, std::vector &qnt_scales,
detect_result_group_t *group);
#endif //RKNN_ZERO_COPY_DEMO_POSTPROCESS_H
Assistant
Ниже исправленный postprocess.h, где убраны C++ типы std::vector и заменены на чистые C типы — указатели и размеры. Чтобы было удобно вызывать из чистого C, функция принимает массивы и (указатели на первый элемент).
// Create input tensor memory
rknn_tensor_mem *input_mems[1];
// default input type is int8 (normalize and quantize need compute in outside)
// if set uint8, will fuse normalize and quantize to npu
input_attrs[0].type = input_type;
// default fmt is NHWC, npu only support NHWC in zero copy mode
input_attrs[0].fmt = input_layout;
// Copy input data to input tensor memory
int width = input_attrs[0].dims[2];
int stride = input_attrs[0].w_stride;
if (width == stride)
{
memcpy(input_mems[0]->virt_addr, input_data, width * input_attrs[0].dims[1] * input_attrs[0].dims[3]);
}
else
{
int height = input_attrs[0].dims[1];
int channel = input_attrs[0].dims[3];
// copy from src to dst with stride
uint8_t *src_ptr = input_data;
uint8_t *dst_ptr = (uint8_t *)input_mems[0]->virt_addr;
// width-channel elements
int src_wc_elems = width * channel;
int dst_wc_elems = stride * channel;
for (int h = 0; h < height; ++h)
{
memcpy(dst_ptr, src_ptr, src_wc_elems);
src_ptr += src_wc_elems;
dst_ptr += dst_wc_elems;
}
}
// Create output tensor memory
rknn_tensor_mem *output_mems[io_num.n_output];
for (uint32_t i = 0; i < io_num.n_output; ++i)
{
output_mems[i] = rknn_create_mem(ctx, output_attrs[i].size_with_stride);
}
// Set input tensor memory
ret = rknn_set_io_mem(ctx, input_mems[0], &input_attrs[0]);
if (ret < 0)
{
printf("rknn_set_io_mem fail! ret=%d\n", ret);
return -1;
}
// Set output tensor memory
for (uint32_t i = 0; i < io_num.n_output; ++i)
{
// set output memory and attribute
ret = rknn_set_io_mem(ctx, output_mems[i], &output_attrs[i]);
if (ret < 0)
{
printf("rknn_set_io_mem fail! ret=%d\n", ret);
return -1;
}
}
// Run
printf("Begin perf ...\n");
for (int i = 0; i < loop_count; ++i)
{
uint64_t START = GLOBAL_TIME_START();
//int64_t start_us = getCurrentTimeUs();
ret = rknn_run(ctx, NULL);
//int64_t elapse_us = getCurrentTimeUs() - start_us;
if (ret < 0)
{
printf("rknn run error %d\n", ret);
return -1;
}
printf("%s: длительность: %s %.3f\n", GLOBAL_TIME_PRINT(), GLOBAL_TIME_END_PRNT(START), GLOBAL_TIME_END(START));
// printf("%4d: Elapse Time = %.2fms, FPS = %.2f\n", i, elapse_us / 1000.f, 1000.f * 1000.f / elapse_us);
}
int model_width = 0;
int model_height = 0;
if (input_attrs[0].fmt == RKNN_TENSOR_NCHW)
{
printf("model is NCHW input fmt\n");
model_width = input_attrs[0].dims[2];
model_height = input_attrs[0].dims[3];
}
else
{
printf("model is NHWC input fmt\n");
model_width = input_attrs[0].dims[1];
model_height = input_attrs[0].dims[2];
}
// post process
float scale_w = (float)model_width / img_width;
float scale_h = (float)model_height / img_height;
detect_result_group_t detect_result_group;
std::vector out_scales;
std::vector<int32_t> out_zps;
for (int i = 0; i < io_num.n_output; ++i)
{
out_scales.push_back(output_attrs[i].scale);
out_zps.push_back(output_attrs[i].zp);
}
// Destroy rknn memory
rknn_destroy_mem(ctx, input_mems[0]);
for (uint32_t i = 0; i < io_num.n_output; ++i)
{
rknn_destroy_mem(ctx, output_mems[i]);
}
// destroy
rknn_destroy(ctx);
free(input_data);
return 0;
}
Вот исправленный файл main.cc, конвертированный в совместимый с чистым C код без добавления новой логики, с минимальными изменениями, чтобы можно было скомпилировать его как C:
Убран #include <vector> и все операции с std::vector заменены на обычные C массивы.
Заменены объявления for (uint32_t i = 0; i < io_num.n_input; i++) на с явным приведением типов, так как в C нет uint32_t как loop counter.
Убраны ключевые слова C++ (static inline → static, переменные объявлены в начале блоков).
Использованы только C стилевые строки и функции.
Убраны конструкции C++ (например, std::vector, // комментарии заменены на /* ... */)
Для detect_result_group и out_scales и out_zps используем статические массивы (здесь размеры максимально заданные исходя из 10 выходов).
c
// Copyright (c) 2021 by Rockchip Electronics Co., Ltd. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*-------------------------------------------
Includes
-------------------------------------------*/
#include "rknn_api.h"
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>
#include "luckfox_time.h"
#include "postprocess.h"
#define PERF_WITH_POST 1
/*-------------------------------------------
Functions
-------------------------------------------*/
static int64_t getCurrentTimeUs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return ((int64_t)tv.tv_sec) * 1000000 + tv.tv_usec;
}
static void dump_tensor_attr(rknn_tensor_attr *attr)
{
char dims[128] = {0};
int i;
for (i = 0; i < attr->n_dims; ++i)
{
int idx = strlen(dims);
sprintf(&dims[idx], "%d%s", attr->dims[i], (i == attr->n_dims - 1) ? "" : ", ");
}
printf(" index=%d, name=%s, n_dims=%d, dims=[%s], n_elems=%d, size=%d, fmt=%s, type=%s, qnt_type=%s, "
"zp=%d, scale=%f\n",
attr->index, attr->name, attr->n_dims, dims, attr->n_elems, attr->size, get_format_string(attr->fmt),
get_type_string(attr->type), get_qnt_type_string(attr->qnt_type), attr->zp, attr->scale);
}
static void *load_file(const char *file_path, size_t *file_size)
{
FILE *fp = fopen(file_path, "r");
if (fp == NULL)
{
printf("failed to open file: %s\n", file_path);
return NULL;
}
fseek(fp, 0, SEEK_END);
size_t size = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
void *file_data = malloc(size);
if (file_data == NULL)
{
fclose(fp);
printf("failed allocate file size: %zu\n", size);
return NULL;
}
if (fread(file_data, 1, size, fp) != size)
{
fclose(fp);
free(file_data);
printf("failed to read file data!\n");
return NULL;
}
fclose(fp);
*file_size = size;
return file_data;
}
static unsigned char *load_image(const char *image_path, rknn_tensor_attr *input_attr, int *img_height, int *img_width)
{
int req_height = 0;
int req_width = 0;
int req_channel = 0;
int channel = 0;
switch (input_attr->fmt)
{
case RKNN_TENSOR_NHWC:
req_height = input_attr->dims[1];
req_width = input_attr->dims[2];
req_channel = input_attr->dims[3];
break;
case RKNN_TENSOR_NCHW:
req_height = input_attr->dims[2];
req_width = input_attr->dims[3];
req_channel = input_attr->dims[1];
break;
default:
printf("meet unsupported layout\n");
return NULL;
}
unsigned char *image_data = stbi_load(image_path, img_width, img_height, &channel, req_channel);
if (image_data == NULL)
{
printf("load image failed!\n");
return NULL;
}
if (*img_width != req_width || *img_height != req_height)
{
unsigned char *image_resized = (unsigned char *)STBI_MALLOC(req_width * req_height * req_channel);
if (!image_resized)
{
printf("malloc image failed!\n");
STBI_FREE(image_data);
return NULL;
}
if (stbir_resize_uint8(image_data, *img_width, *img_height, 0, image_resized, req_width, req_height, 0, channel) != 1)
{
printf("resize image failed!\n");
STBI_FREE(image_data);
STBI_FREE(image_resized);
return NULL;
}
STBI_FREE(image_data);
image_data = image_resized;
*img_width = req_width;
*img_height = req_height;
}
return image_data;
}
/*-------------------------------------------
Main Functions
-------------------------------------------*/
int main(int argc, char *argv[])
{
if (argc < 3)
{
printf("Usage:%s model_path input_path [loop_count]\n", argv[0]);
return -1;
}
char *model_path = argv[1];
char *input_path = argv[2];
int loop_count = 1;
if (argc > 3)
{
loop_count = atoi(argv[3]);
}
const float nms_threshold = NMS_THRESH;
const float box_conf_threshold = BOX_THRESH;
int img_width = 0;
int img_height = 0;
rknn_context ctx = 0;
/* Load RKNN Model */
#if 1
/* Init rknn from model path */
int ret = rknn_init(&ctx, model_path, 0, 0, NULL);
#else
/* Init rknn from model data */
size_t model_size;
void *model_data = load_file(model_path, &model_size);
if (model_data == NULL)
{
return -1;
}
int ret = rknn_init(&ctx, model_data, model_size, 0, NULL);
free(model_data);
#endif
if (ret < 0)
{
printf("rknn_init fail! ret=%d\n", ret);
return -1;
}
/* Get sdk and driver version */
rknn_sdk_version sdk_ver;
ret = rknn_query(ctx, RKNN_QUERY_SDK_VERSION, &sdk_ver, sizeof(sdk_ver));
if (ret != RKNN_SUCC)
{
printf("rknn_query fail! ret=%d\n", ret);
return -1;
}
printf("rknn_api/rknnrt version: %s, driver version: %s\n", sdk_ver.api_version, sdk_ver.drv_version);
/* Get Model Input Output Info */
rknn_input_output_num io_num;
ret = rknn_query(ctx, RKNN_QUERY_IN_OUT_NUM, &io_num, sizeof(io_num));
if (ret != RKNN_SUCC)
{
printf("rknn_query fail! ret=%d\n", ret);
return -1;
}
printf("model input num: %d, output num: %d\n", io_num.n_input, io_num.n_output);
printf("input tensors:\n");
rknn_tensor_attr *input_attrs = (rknn_tensor_attr*)malloc(io_num.n_input * sizeof(rknn_tensor_attr));
if(!input_attrs)
{
printf("malloc failed for input_attrs\n");
return -1;
}
memset(input_attrs, 0, io_num.n_input * sizeof(rknn_tensor_attr));
{
int i;
for (i = 0; i < (int)io_num.n_input; i++)
{
input_attrs[i].index = i;
/* query info */
ret = rknn_query(ctx, RKNN_QUERY_INPUT_ATTR, &(input_attrs[i]), sizeof(rknn_tensor_attr));
if (ret < 0)
{
printf("rknn_init error! ret=%d\n", ret);
free(input_attrs);
return -1;
}
dump_tensor_attr(&input_attrs[i]);
}
}
printf("output tensors:\n");
rknn_tensor_attr *output_attrs = (rknn_tensor_attr*)malloc(io_num.n_output * sizeof(rknn_tensor_attr));
if(!output_attrs)
{
printf("malloc failed for output_attrs\n");
free(input_attrs);
return -1;
}
memset(output_attrs, 0, io_num.n_output * sizeof(rknn_tensor_attr));
{
int i;
for (i = 0; i < (int)io_num.n_output; i++)
{
output_attrs[i].index = i;
/* query info */
ret = rknn_query(ctx, RKNN_QUERY_NATIVE_NHWC_OUTPUT_ATTR, &(output_attrs[i]), sizeof(rknn_tensor_attr));
if (ret != RKNN_SUCC)
{
printf("rknn_query fail! ret=%d\n", ret);
free(input_attrs);
free(output_attrs);
return -1;
}
dump_tensor_attr(&output_attrs[i]);
}
}
/* Get custom string */
rknn_custom_string custom_string;
ret = rknn_query(ctx, RKNN_QUERY_CUSTOM_STRING, &custom_string, sizeof(custom_string));
if (ret != RKNN_SUCC)
{
printf("rknn_query fail! ret=%d\n", ret);
free(input_attrs);
free(output_attrs);
return -1;
}
printf("custom string: %s\n", custom_string.string);
unsigned char *input_data = NULL;
rknn_tensor_type input_type = RKNN_TENSOR_UINT8;
rknn_tensor_format input_layout = RKNN_TENSOR_NHWC;
/* Load image */
input_data = load_image(input_path, &input_attrs[0], &img_height, &img_width);
if (!input_data)
{
free(input_attrs);
free(output_attrs);
return -1;
}
/* Create input tensor memory */
rknn_tensor_mem *input_mems[1];
/* default input type is int8 (normalize and quantize need compute in outside) */
/* if set uint8, will fuse normalize and quantize to npu */
input_attrs[0].type = input_type;
/* default fmt is NHWC, npu only support NHWC in zero copy mode */
input_attrs[0].fmt = input_layout;
input_mems[0] = rknn_create_mem(ctx, input_attrs[0].size_with_stride);
/* Copy input data to input tensor memory */
{
int width = input_attrs[0].dims[2];
int stride = input_attrs[0].w_stride;
if (width == stride)
{
memcpy(input_mems[0]->virt_addr, input_data, width * input_attrs[0].dims[1] * input_attrs[0].dims[3]);
}
else
{
int height = input_attrs[0].dims[1];
int channel = input_attrs[0].dims[3];
/* copy from src to dst with stride */
uint8_t *src_ptr = input_data;
uint8_t *dst_ptr = (uint8_t *)input_mems[0]->virt_addr;
/* width-channel elements */
int src_wc_elems = width * channel;
int dst_wc_elems = stride * channel;
int h;
for (h = 0; h < height; ++h)
{
memcpy(dst_ptr, src_ptr, src_wc_elems);
src_ptr += src_wc_elems;
dst_ptr += dst_wc_elems;
}
}
}
/* Create output tensor memory */
rknn_tensor_mem **output_mems = (rknn_tensor_mem**)malloc(io_num.n_output * sizeof(rknn_tensor_mem*));
if (!output_mems)
{
printf("malloc failed for output_mems\n");
free(input_attrs);
free(output_attrs);
rknn_destroy_mem(ctx, input_mems[0]);
free(input_data);
return -1;
}
{
int i;
for (i = 0; i < (int)io_num.n_output; i++)
{
output_mems[i] = rknn_create_mem(ctx, output_attrs[i].size_with_stride);
}
}
/* Set input tensor memory */
ret = rknn_set_io_mem(ctx, input_mems[0], &input_attrs[0]);
if (ret < 0)
{
printf("rknn_set_io_mem fail! ret=%d\n", ret);
free(input_attrs);
free(output_attrs);
for (int i = 0; i < (int)io_num.n_output; i++)
rknn_destroy_mem(ctx, output_mems[i]);
free(output_mems);
rknn_destroy_mem(ctx, input_mems[0]);
free(input_data);
return -1;
}
/* Set output tensor memory */
{
int i;
for (i = 0; i < (int)io_num.n_output; i++)
{
/* set output memory and attribute */
ret = rknn_set_io_mem(ctx, output_mems[i], &output_attrs[i]);
if (ret < 0)
{
printf("rknn_set_io_mem fail! ret=%d\n", ret);
free(input_attrs);
free(output_attrs);
for (int j = 0; j < (int)io_num.n_output; j++)
rknn_destroy_mem(ctx, output_mems[j]);
free(output_mems);
rknn_destroy_mem(ctx, input_mems[0]);
free(input_data);
return -1;
}
}
}
/* Run */
printf("Begin perf ...\n");
{
int i;
for (i = 0; i < loop_count; ++i)
{
uint64_t START = GLOBAL_TIME_START();
/* int64_t start_us = getCurrentTimeUs(); */
ret = rknn_run(ctx, NULL);
/* int64_t elapse_us = getCurrentTimeUs() - start_us; */
if (ret < 0)
{
printf("rknn run error %d\n", ret);
free(input_attrs);
free(output_attrs);
for (i = 0; i < (int)io_num.n_output; i++)
rknn_destroy_mem(ctx, output_mems[i]);
free(output_mems);
rknn_destroy_mem(ctx, input_mems[0]);
free(input_data);
return -1;
}
printf("%s: длительность: %s %.3f\n", GLOBAL_TIME_PRINT(), GLOBAL_TIME_END_PRNT(START), GLOBAL_TIME_END(START));
/* printf("%4d: Elapse Time = %.2fms, FPS = %.2f\n", i, elapse_us / 1000.f, 1000.f * 1000.f / elapse_us); */
}
}
int model_width = 0;
int model_height = 0;
if (input_attrs[0].fmt == RKNN_TENSOR_NCHW)
{
printf("model is NCHW input fmt\n");
model_width = input_attrs[0].dims[2];
model_height = input_attrs[0].dims[3];
}
else
{
printf("model is NHWC input fmt\n");
model_width = input_attrs[0].dims[1];
model_height = input_attrs[0].dims[2];
}
/* post process */
{
float scale_w = (float)model_width / img_width;
float scale_h = (float)model_height / img_height;
detect_result_group_t detect_result_group;
float out_scales[10] = {0};
int32_t out_zps[10] = {0};
int i;
/* Защита на случай если io_num.n_output > 10 */
int output_num = (io_num.n_output > 10) ? 10 : io_num.n_output;
for (i = 0; i < output_num; ++i)
{
out_scales[i] = output_attrs[i].scale;
out_zps[i] = output_attrs[i].zp;
}
post_process((int8_t *)output_mems[0]->virt_addr, (int8_t *)output_mems[1]->virt_addr, (int8_t *)output_mems[2]->virt_addr, 640, 640,
box_conf_threshold, nms_threshold, scale_w, scale_h, out_zps, out_scales, &detect_result_group);
{
char text[256];
for (i = 0; i < detect_result_group.count; i++)
{
detect_result_t *det_result = &(detect_result_group.results[i]);
sprintf(text, "%s %.1f%%", det_result->name, det_result->prop * 100);
printf("%s @ (%d %d %d %d) %f\n",
det_result->name,
det_result->box.left, det_result->box.top, det_result->box.right, det_result->box.bottom,
det_result->prop);
}
}
}
/* Destroy rknn memory */
rknn_destroy_mem(ctx, input_mems[0]);
{
int i;
for (i = 0; i < (int)io_num.n_output; ++i)
{
rknn_destroy_mem(ctx, output_mems[i]);
}
}
/* destroy */
rknn_destroy(ctx);
free(output_mems);
free(input_attrs);
free(output_attrs);
free(input_data);
return 0;
}
Если есть вопросы по исправлению — обращайтесь!
P.S. Этот код — C версия вашего C++ кода с минимумом изменений и без добавления логики. Но если какие-то структуры и функции — из C++ (например, std::vector или post_process принимающая C++ типы), может потребоваться доп. адаптация этих библиотек.
вот postproces.cc
// Copyright (c) 2021 by Rockchip Electronics Co., Ltd. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const int anchor0[6] = {10, 13, 16, 30, 33, 23};
const int anchor1[6] = {30, 61, 62, 45, 59, 119};
const int anchor2[6] = {116, 90, 156, 198, 373, 326};
inline static int clamp(float val, int min, int max)
{
return val > min ? (val < max ? val : max) : min;
}
char *readLine(FILE *fp, char *buffer, int *len)
{
int ch;
int i = 0;
size_t buff_len = 0;
code
buffer = (char *)malloc(buff_len + 1);
if (!buffer)
return NULL; // Out of memory
while ((ch = fgetc(fp)) != '\n' && ch != EOF)
{
buff_len++;
void *tmp = realloc(buffer, buff_len + 1);
if (tmp == NULL)
{
free(buffer);
return NULL; // Out of memory
}
buffer = (char *)tmp;
buffer[i] = (char)ch;
i++;
}
buffer[i] = '\0';
*len = buff_len;
// Detect end
if (ch == EOF && (i == 0 || ferror(fp)))
{
free(buffer);
return NULL;
}
return buffer;
}
int readLines(const char *fileName, char *lines[], int max_line)
{
FILE *file = fopen(fileName, "r");
char *s;
int i = 0;
int n = 0;
while ((s = readLine(file, s, &n)) != NULL)
{
lines[i++] = s;
if (i >= max_line)
break;
}
return i;
}
static int process(int8_t *input, int *anchor, int grid_h, int grid_w, int height, int width, int stride,
std::vector &boxes, std::vector &objProbs, std::vector &classId,
float threshold, int32_t zp, float scale)
{
static int process_native_nhwc(int8_t *input, int *anchor, int grid_h, int grid_w, int height, int width, int stride,
std::vector &boxes, std::vector &boxScores, std::vector &classId,
float threshold, int32_t zp, float scale)
{
int validCount = 0;
int8_t thres_i8 = qnt_f32_to_affine(threshold, zp, scale);
В вашем postprocess.cc много используется C++-специфичных конструкций (std::vector, std::set, auto-цикл, включая <vector>, <set>, лямбды и пр). Чтобы сделать этот код компилируемым как чистый C, потребуется существенная переработка.
Вы, судя по всему, ограничены только компиляцией С (C, но не C++). Ниже — основные шаги и пример, как переписать этот postprocess.cc в чистый C (без C++ STL и конструкций):
Основные изменения для чистого C
Убрать #include <vector>, <set>.
Заменить std::vector<T> на обычные С массивы и вручную управлять размером. Для динамических массивов нужны malloc+realloc, либо статические буферы.
Убрать auto и range-based for. Заменить на обычные for с индексами.
Убрать конструкции типа std::set, заменить на массив и простой поиск/фильтрацию.
Убрать inline static в пользу static.
Заменить функции, принимающие вектор, на указатель + длина.
Пример исправления ключевых мест
Ниже я покажу переделанный вариант post_process и смежных функций, где убраны векторы и сет.
Для удобства сделаем статические буферы достаточного размера. Максимальный размер векторов можно взять как OBJ_NUMB_MAX_SIZE*10 (с запасом).
c
#include "postprocess.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#define MAX_BOXES 1024
// Буфер-подмены для векторов
typedef struct {
float data[MAX_BOXES * 4]; // x,y,w,h * кол-во боксов
int count;
} boxes_array_t;
typedef struct {
float data[MAX_BOXES];
int count;
} float_array_t;
typedef struct {
int data[MAX_BOXES];
int count;
} int_array_t;
// Быстрая замена std::vector<int> indexArray;
// и std::set<int> class_set
// Функция сортировки и nms - оставьте Вашу оригинальную логику, только используйте эти структуры
// Пример: перебор уникальных классов (replacing std::set)
void get_unique_classes(int *classIds, int count, int *uniqueClasses, int *uniqueCount)
{
int i, j;
*uniqueCount = 0;
for(i=0; i<count; i++)
{
int c = classIds[i];
int found = 0;
for(j=0; j<*uniqueCount; j++)
{
if(uniqueClasses[j] == c)
{
found = 1;
break;
}
}
if(!found)
{
uniqueClasses[*uniqueCount] = c;
(*uniqueCount)++;
}
}
}
int post_process(int8_t *input0, int8_t *input1, int8_t *input2, int model_in_h, int model_in_w,
float conf_threshold, float nms_threshold, float scale_w, float scale_h,
int32_t *qnt_zps, float *qnt_scales,
detect_result_group_t *group)
{
static int init = -1;
int ret;
(void)conf_threshold; // если не используете, чтоб не ругалось
// Initialization - если надо
if (init == -1)
{
//ret = loadLabelName(LABEL_NALE_TXT_PATH, labels);
//if (ret < 0) return -1;
init = 0;
}
memset(group, 0, sizeof(detect_result_group_t));
boxes_array_t filterBoxes;
float_array_t objProbs;
int_array_t classId;
filterBoxes.count = 0;
objProbs.count = 0;
classId.count = 0;
// stride 8
int stride0 = 8;
int grid_h0 = model_in_h / stride0;
int grid_w0 = model_in_w / stride0;
int validCount0 = process_native_nhwc(input0, (int *)anchor0, grid_h0, grid_w0, model_in_h, model_in_w,
stride0,
filterBoxes.data, &filterBoxes.count,
objProbs.data, &objProbs.count,
classId.data, &classId.count,
conf_threshold, qnt_zps[0], qnt_scales[0]);
// stride 16
int stride1 = 16;
int grid_h1 = model_in_h / stride1;
int grid_w1 = model_in_w / stride1;
int validCount1 = process_native_nhwc(input1, (int *)anchor1, grid_h1, grid_w1, model_in_h, model_in_w,
stride1,
filterBoxes.data, &filterBoxes.count,
objProbs.data, &objProbs.count,
classId.data, &classId.count,
conf_threshold, qnt_zps[1], qnt_scales[1]);
// stride 32
int stride2 = 32;
int grid_h2 = model_in_h / stride2;
int grid_w2 = model_in_w / stride2;
int validCount2 = process_native_nhwc(input2, (int *)anchor2, grid_h2, grid_w2, model_in_h, model_in_w,
stride2,
filterBoxes.data, &filterBoxes.count,
objProbs.data, &objProbs.count,
classId.data, &classId.count,
conf_threshold, qnt_zps[2], qnt_scales[2]);
int validCount = validCount0 + validCount1 + validCount2;
if (validCount <= 0)
return 0;
// Индексы на все боксы
int indexArray[MAX_BOXES];
int i;
for (i = 0; i < validCount; i++)
indexArray[i] = i;
quick_sort_indice_inverse_custom(objProbs.data, 0, validCount - 1, indexArray);
// Уникальные классы
int uniqueClasses[MAX_BOXES];
int uniqueClassCount = 0;
get_unique_classes(classId.data, classId.count, uniqueClasses, &uniqueClassCount);
for (i=0; i<uniqueClassCount; i++)
{
int c = uniqueClasses[i];
nms_custom(validCount, filterBoxes.data, classId.data, indexArray, c, nms_threshold);
}
int last_count = 0;
group->count = 0;
for (i = 0; i < validCount; i++)
{
if (indexArray[i] == -1 || last_count >= OBJ_NUMB_MAX_SIZE)
continue;
int n = indexArray[i];
float x1 = filterBoxes.data[n * 4 + 0];
float y1 = filterBoxes.data[n * 4 + 1];
float x2 = x1 + filterBoxes.data[n * 4 + 2];
float y2 = y1 + filterBoxes.data[n * 4 + 3];
int id = classId.data[n];
float obj_conf = objProbs.data[i];
group->results[last_count].box.left = (int)(clamp(x1, 0, model_in_w) / scale_w);
group->results[last_count].box.top = (int)(clamp(y1, 0, model_in_h) / scale_h);
group->results[last_count].box.right = (int)(clamp(x2, 0, model_in_w) / scale_w);
group->results[last_count].box.bottom = (int)(clamp(y2, 0, model_in_h) / scale_h);
group->results[last_count].prop = obj_conf;
last_count++;
}
group->count = last_count;
return 0;
}
// Ниже нужно переписать process_native_nhwc и другие функции, чтобы использовать указатели на массивы C и счетчики,
// наконец quick_sort_indice_inverse_custom и nms_custom - переписать под C, принимая массивы и индексы, а не std::vector.
Общие рекомендации
Замените все std::vector<T> на два параметра: T* data и int* count (счетчик элементов).
Все операции добавления элемента - делайте с учётом счетчика.
Вместо std::set используйте массив и ручной поиск уникальных элементов.
Удалите использование auto, range-for, и замените на обычные for(с индексами).
Если хочется, могу помочь полностью переписать весь файл под C — дайте знать.
Если хотите — могу помочь с полным переписыванием, просто скажите.
Для Вашего main.cc без STL, нельзя использовать такой постпроцессинг без значительной переделки — т.к там post_process зависит от std::vector.
Лучшее решение — сделать postprocess.c в стиле С и подключать его к вашему C-коду.
Понимаю, вы хотите полностью переписать postprocess.cc в чистый C, чтобы подключить к вашему C проекту. Ниже — примерный вариант postprocess.c (исходя из вашего кода), где:
Убраны все std::vector, std::set, C++ конструкции.
Используются статические массивы и счетчики.
Потоково переносится логика из вашего C++ кода.
Файл postprocess.c
c
// Copyright (c) 2021 by Rockchip Electronics Co., Ltd. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#include "postprocess.h"
#define MAX_BOXES 1024
static char *labels[OBJ_CLASS_NUM]; /* если нужно, реализуйте загрузку */
const int anchor0[6] = {10, 13, 16, 30, 33, 23};
const int anchor1[6] = {30, 61, 62, 45, 59, 119};
const int anchor2[6] = {116, 90, 156, 198, 373, 326};
static int clamp_i(float val, int min, int max)
{
if (val < (float)min) return min;
else if (val > (float)max) return max;
else return (int)val;
}
static float CalculateOverlap(float xmin0, float ymin0, float xmax0, float ymax0, float xmin1, float ymin1, float xmax1, float ymax1)
{
float w = fmaxf(0.f, fminf(xmax0, xmax1) - fmaxf(xmin0, xmin1) + 1.0f);
float h = fmaxf(0.f, fminf(ymax0, ymax1) - fmaxf(ymin0, ymin1) + 1.0f);
float i = w * h;
float u = (xmax0 - xmin0 + 1.0f) * (ymax0 - ymin0 + 1.0f) + (xmax1 - xmin1 + 1.0f) * (ymax1 - ymin1 + 1.0f) - i;
return (u <= 0.f) ? 0.f : (i / u);
}
static int qnt_f32_to_affine(float f32, int32_t zp, float scale)
{
float dst_val = (f32 / scale) + zp;
if (dst_val < -128.f) dst_val = -128.f;
else if (dst_val > 127.f) dst_val = 127.f;
return (int)dst_val;
}
static float deqnt_affine_to_f32(int8_t qnt, int32_t zp, float scale)
{
return ((float)qnt - (float)zp) * scale;
}
static void quick_sort_indice_inverse(float *input, int left, int right, int *indices)
{
if (left >= right) return;
int i = left, j = right;
float pivot = input[left];
int pivot_index = indices[left];
while (i < j)
{
while (i < j && input[j] <= pivot) j--;
if (i < j)
{
input[i] = input[j];
indices[i] = indices[j];
i++;
}
while (i < j && input[i] >= pivot) i++;
if (i < j)
{
input[j] = input[i];
indices[j] = indices[i];
j--;
}
}
input[i] = pivot;
indices[i] = pivot_index;
quick_sort_indice_inverse(input, left, i - 1, indices);
quick_sort_indice_inverse(input, i + 1, right, indices);
}
static void nms(int validCount, float *outputLocations, int *classIds, int *order, int filterId, float threshold)
{
int i, j;
for (i = 0; i < validCount; ++i)
{
if (order[i] == -1 || classIds[i] != filterId)
continue;
int n = order[i];
for (j = i + 1; j < validCount; ++j)
{
int m = order[j];
if (m == -1 || classIds[j] != filterId)
continue;
float xmin0 = outputLocations[n * 4 + 0];
float ymin0 = outputLocations[n * 4 + 1];
float xmax0 = xmin0 + outputLocations[n * 4 + 2];
float ymax0 = ymin0 + outputLocations[n * 4 + 3];
float xmin1 = outputLocations[m * 4 + 0];
float ymin1 = outputLocations[m * 4 + 1];
float xmax1 = xmin1 + outputLocations[m * 4 + 2];
float ymax1 = ymin1 + outputLocations[m * 4 + 3];
float iou = CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1, xmax1, ymax1);
if (iou > threshold)
{
order[j] = -1;
}
}
}
}
// process_native_nhwc СКРОМНО переписана, добавьте остальные параметры, как надо
static int process_native_nhwc(int8_t *input, int *anchor, int grid_h, int grid_w, int height, int width, int stride,
float *boxes, int *box_count,
float *boxScores, int *score_count,
int *classIds, int *class_count,
float threshold, int32_t zp, float scale)
{
int validCount = 0;
int8_t thres_i8 = (int8_t)qnt_f32_to_affine(threshold, zp, scale);
int anchor_per_branch = 3;
int align_c = PROP_BOX_SIZE * anchor_per_branch;
int h, w, a, k;
for (h = 0; h < grid_h; ++h)
{
for (w = 0; w < grid_w; ++w)
{
for (a = 0; a < anchor_per_branch; ++a)
{
int hw_offset = h * grid_w * align_c + w * align_c + a * PROP_BOX_SIZE;
int8_t *hw_ptr = input + hw_offset;
int8_t box_confidence = hw_ptr[4];
if (box_confidence >= thres_i8)
{
int8_t maxClassProbs = hw_ptr[5];
int maxClassId = 0;
for (k = 1; k < OBJ_CLASS_NUM; ++k)
{
int8_t prob = hw_ptr[5 + k];
if (prob > maxClassProbs)
{
maxClassId = k;
maxClassProbs = prob;
}
}
float box_conf_f32 = deqnt_affine_to_f32(box_confidence, zp, scale);
float class_prob_f32 = deqnt_affine_to_f32(maxClassProbs, zp, scale);
float limit_score = box_conf_f32 * class_prob_f32;
if (limit_score > threshold)
{
float box_x = deqnt_affine_to_f32(hw_ptr[0], zp, scale) * 2.0f - 0.5f;
float box_y = deqnt_affine_to_f32(hw_ptr[1], zp, scale) * 2.0f - 0.5f;
float box_w = deqnt_affine_to_f32(hw_ptr[2], zp, scale) * 2.0f;
float box_h = deqnt_affine_to_f32(hw_ptr[3], zp, scale) * 2.0f;
box_w = box_w * box_w;
box_h = box_h * box_h;
box_x = (box_x + (float)w) * (float)stride;
box_y = (box_y + (float)h) * (float)stride;
box_w *= (float)anchor[a * 2];
box_h *= (float)anchor[a * 2 + 1];
box_x -= (box_w / 2.0f);
box_y -= (box_h / 2.0f);
if ((*box_count) < MAX_BOXES && (*score_count) < MAX_BOXES && (*class_count) < MAX_BOXES)
{
boxes[(*box_count) * 4 + 0] = box_x;
boxes[(*box_count) * 4 + 1] = box_y;
boxes[(*box_count) * 4 + 2] = box_w;
boxes[(*box_count) * 4 + 3] = box_h;
(*box_count)++;
boxScores[*score_count] = limit_score;
(*score_count)++;
classIds[*class_count] = maxClassId;
(*class_count)++;
validCount++;
}
}
}
}
}
}
return validCount;
}
int post_process(int8_t *input0, int8_t *input1, int8_t *input2, int model_in_h, int model_in_w,
float conf_threshold, float nms_threshold, float scale_w, float scale_h,
int32_t *qnt_zps, float *qnt_scales,
detect_result_group_t *group)
{
static int init = -1;
(void)init; // если нужна загрузка labels реализуйте, на данном этапе игнорируем
memset(group, 0, sizeof(detect_result_group_t));
float filterBoxes[MAX_BOXES * 4];
float objProbs[MAX_BOXES];
int classId[MAX_BOXES];
int validBoxesCount = 0;
int objProbsCount = 0;
int classIdCount = 0;
int stride0 = 8;
int grid_h0 = model_in_h / stride0;
int grid_w0 = model_in_w / stride0;
int validCount0 = process_native_nhwc(input0, (int *)anchor0, grid_h0, grid_w0, model_in_h, model_in_w,
stride0, filterBoxes, &validBoxesCount,
objProbs, &objProbsCount,
classId, &classIdCount,
conf_threshold, qnt_zps[0], qnt_scales[0]);
int stride1 = 16;
int grid_h1 = model_in_h / stride1;
int grid_w1 = model_in_w / stride1;
int validCount1 = process_native_nhwc(input1, (int *)anchor1, grid_h1, grid_w1, model_in_h, model_in_w,
stride1, filterBoxes, &validBoxesCount,
objProbs, &objProbsCount,
classId, &classIdCount,
conf_threshold, qnt_zps[1], qnt_scales[1]);
int stride2 = 32;
int grid_h2 = model_in_h / stride2;
int grid_w2 = model_in_w / stride2;
int validCount2 = process_native_nhwc(input2, (int *)anchor2, grid_h2, grid_w2, model_in_h, model_in_w,
stride2, filterBoxes, &validBoxesCount,
objProbs, &objProbsCount,
classId, &classIdCount,
conf_threshold, qnt_zps[2], qnt_scales[2]);
int totalValidCount = validCount0 + validCount1 + validCount2;
if (totalValidCount <= 0)
return 0;
int indexArray[MAX_BOXES];
for (int i = 0; i < totalValidCount; i++)
indexArray[i] = i;
quick_sort_indice_inverse(objProbs, 0, totalValidCount - 1, indexArray);
// Уникальные классы массива classId
int uniqueClasses[MAX_BOXES];
int uniqueCount = 0;
for (int i = 0; i < classIdCount; i++)
{
int c = classId[i];
int found = 0;
for (int j = 0; j < uniqueCount; j++)
{
if (uniqueClasses[j] == c)
{
found = 1;
break;
}
}
if (!found)
{
uniqueClasses[uniqueCount++] = c;
}
}
// Выполнить NMS для каждого класса
for (int cIdx = 0; cIdx < uniqueCount; cIdx++)
{
int cid = uniqueClasses[cIdx];
nms(totalValidCount, filterBoxes, classId, indexArray, cid, nms_threshold);
}
int last_count = 0;
for (int i = 0; i < totalValidCount && last_count < OBJ_NUMB_MAX_SIZE; i++)
{
if (indexArray[i] == -1)
continue;
int n = indexArray[i];
float x1 = filterBoxes[n * 4 + 0];
float y1 = filterBoxes[n * 4 + 1];
float x2 = x1 + filterBoxes[n * 4 + 2];
float y2 = y1 + filterBoxes[n * 4 + 3];
int id = classId[n];
float obj_conf = objProbs[i];
group->results[last_count].box.left = clamp_i(x1 / scale_w, 0, model_in_w);
group->results[last_count].box.top = clamp_i(y1 / scale_h, 0, model_in_h);
group->results[last_count].box.right = clamp_i(x2 / scale_w, 0, model_in_w);
group->results[last_count].box.bottom = clamp_i(y2 / scale_h, 0, model_in_h);
group->results[last_count].prop = obj_conf;
// Можно установить group->results[last_count].name из labels[id] если нужно
last_count++;
}
group->count = last_count;
return 0;
}
Ключевые моменты
Все операции с динамическими массивами сделаны на статических массивах с ограничением MAX_BOXES.
Векторы и множества заменены на ручную работу с массивами и уникализацией.
Переписана сортировка и nms под работу с C массивами.
Все функции принимают явные указатели и размеры.
Для post_process проброс параметров qnt_zps и qnt_scales — обычные указатели на int32_t и float.
Что сделать дальше
Проверьте, чтобы в postprocess.h функции и структуры были объявлены в виде C-конструкций (не C++), и их можно было подключить в ваш C код.
Скорректируйте по необходимости пути заголовков.
Если используете функции из postprocess.h, проверьте, что они теперь принимают именно C-массивы, а не std::vector.
Сборка: компилируйте postprocess.c обычным C-компилятором, линковка с вашим main.c.
Если хотите — могу помочь с адаптацией заголовочного файла и/или с остальными вспомогательными функциями для C. Просто напишите.
post_process
int32_t* qnt_zps
float* qnt_scales
c
#ifndef _RKNN_ZERO_COPY_DEMO_POSTPROCESS_H_
#define _RKNN_ZERO_COPY_DEMO_POSTPROCESS_H_
#include <stdint.h>
#define OBJ_NAME_MAX_SIZE 16
#define OBJ_NUMB_MAX_SIZE 64
#define OBJ_CLASS_NUM 37
#define NMS_THRESH 0.75f
#define BOX_THRESH 0.70f
#define PROP_BOX_SIZE (5+OBJ_CLASS_NUM)
typedef struct _BOX_RECT
{
int left;
int right;
int top;
int bottom;
} BOX_RECT;
typedef struct __detect_result_t
{
char name[OBJ_NAME_MAX_SIZE];
BOX_RECT box;
float prop;
} detect_result_t;
typedef struct _detect_result_group_t
{
int id;
int count;
detect_result_t results[OBJ_NUMB_MAX_SIZE];
} detect_result_group_t;
/**
* Построенный в C постпроцессинг.
*
* @param input0, input1, input2 - указатели на данные выходных тензоров int8_t
* @param model_in_h, model_in_w - размер входа модели
* @param conf_threshold, nms_threshold - пороги конфиденций и nms
* @param scale_w, scale_h - масштабные коэффициенты по ширине и высоте
* @param qnt_zps - массив int32_t нулевых смещений (zero points) квантования, размер 3
* @param qnt_scales - массив float масштабов квантования, размер 3
* @param group - указатель на структуру с результатом (output)
*
* @return 0 при успехе, иначе < 0
*/
int post_process(int8_t *input0, int8_t *input1, int8_t *input2, int model_in_h, int model_in_w,
float conf_threshold, float nms_threshold, float scale_w, float scale_h,
int32_t *qnt_zps, float *qnt_scales,
detect_result_group_t *group);
#endif // _RKNN_ZERO_COPY_DEMO_POSTPROCESS_H_
Теперь в вашем C-коде можете вызывать примерно так:
Если нужно, могу помочь и с другим заголовочным файлом или дальнейшей интеграцией.
Да, подходы отличаются из-за особенностей языков:
В C++ std::vector<float> boxes; — это динамический массив, туда push_back() добавляет один scalar элемент за раз. В вашем коде четыре push_back подряд дописывают поэлементно координаты бокса, так что фактически для одного бокса добавляется 4 float подряд (x,y,w,h).
В C аналог std::vector — это одномерный массив, в вашем примере boxes — одномерный массив float, размером (например) MAX_BOXES * 4 элементов — то есть с запасом, где каждые 4 элемента — это полный бокс.
Это равноценно четырём вызовам push_back в C++, потому что мы вручную копируем эти 4 компоненты непосредственно в массив на позицию с индексом (*box_count).
Потом увеличиваем счётчик боксов (box_count++) — то есть для следующего бокса всё записывается в следующем блоке из 4 элементов.
Для плоского одномерного массива такой код — правильный и правильнее, чем аппроксимация push_back с помощью индексации.
Почему так сделано — особенности C:
В С нет готовой контейнерной обертки,
Нужна явная индексация, чтобы знать куда писать новые элементы,
Хранить данные боксов в одномерном массиве с шагом 4 (x,y,w,h) — классика для С.
Ваш C++ код — хранит боксы так же: четыре значения идут подряд, но добавляет их элементно.
Мой C код этот push_backзаменяет записью 4 значений подряд в фиксированную позицию массива, что эквивалентно. Это нормальная практика в C.
При чтении или обработке боксов в обоих вариантах — можно брать блоки по 4 float подряд.
Если интересно, могу подсказать, как переписать с хранением данных в структурах с массивом из 4 значений (struct box { float x,y,w,h; }), будет чуть понятнее, но в любом случае std::vector<float> — плоский массив.
Если хотите, проверю конкретный фрагмент или помогу переписать другие места — пишите :)