USER
Теперь тут на чистом СИ
// 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 <math.h>
#include <string.h>
#include <sys/time.h>
#include <vector>
#include <set>
#include "postprocess.h"
#include <stdint.h>
#define LABEL_NALE_TXT_PATH "./model/coco_80_labels_list.txt"
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};
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;
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;
}
int loadLabelName(const char *locationFilename, char *label[])
{
printf("loadLabelName %s\n", locationFilename);
readLines(locationFilename, label, OBJ_CLASS_NUM);
return 0;
}
static float CalculateOverlap(float xmin0, float ymin0, float xmax0, float ymax0, float xmin1, float ymin1, float xmax1, float ymax1)
{
float w = fmax(0.f, fmin(xmax0, xmax1) - fmax(xmin0, xmin1) + 1.0);
float h = fmax(0.f, fmin(ymax0, ymax1) - fmax(ymin0, ymin1) + 1.0);
float i = w * h;
float u = (xmax0 - xmin0 + 1.0) * (ymax0 - ymin0 + 1.0) + (xmax1 - xmin1 + 1.0) * (ymax1 - ymin1 + 1.0) - i;
return u <= 0.f ? 0.f : (i / u);
}
static int nms(int validCount, std::vector<float> &outputLocations, std::vector<int> classIds, std::vector<int> &order,int filterId, float threshold)
{
for (int i = 0; i < validCount; ++i)
{
if (order[i] == -1|| classIds[i] != filterId)
{
continue;
}
int n = order[i];
for (int j = i + 1; j < validCount; ++j)
{
int m = order[j];
if (m == -1 || classIds[i] != filterId)
{
continue;
}
float xmin0 = outputLocations[n * 4 + 0];
float ymin0 = outputLocations[n * 4 + 1];
float xmax0 = outputLocations[n * 4 + 0] + outputLocations[n * 4 + 2];
float ymax0 = outputLocations[n * 4 + 1] + outputLocations[n * 4 + 3];
float xmin1 = outputLocations[m * 4 + 0];
float ymin1 = outputLocations[m * 4 + 1];
float xmax1 = outputLocations[m * 4 + 0] + outputLocations[m * 4 + 2];
float ymax1 = outputLocations[m * 4 + 1] + outputLocations[m * 4 + 3];
float iou = CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1, xmax1, ymax1);
if (iou > threshold)
{
order[j] = -1;
}
}
}
return 0;
}
static int quick_sort_indice_inverse(
std::vector<float> &input,
int left,
int right,
std::vector<int> &indices)
{
float key;
int key_index;
int low = left;
int high = right;
if (left < right)
{
key_index = indices[left];
key = input[left];
while (low < high)
{
while (low < high && input[high] <= key)
{
high--;
}
input[low] = input[high];
indices[low] = indices[high];
while (low < high && input[low] >= key)
{
low++;
}
input[high] = input[low];
indices[high] = indices[low];
}
input[low] = key;
indices[low] = key_index;
quick_sort_indice_inverse(input, left, low - 1, indices);
quick_sort_indice_inverse(input, low + 1, right, indices);
}
return low;
}
static float sigmoid(float x)
{
return 1.0 / (1.0 + expf(-x));
}
static float unsigmoid(float y)
{
return -1.0 * logf((1.0 / y) - 1.0);
}
inline static int32_t __clip(float val, float min, float max)
{
float f = val <= min ? min : (val >= max ? max : val);
return f;
}
static int8_t qnt_f32_to_affine(float f32, int32_t zp, float scale)
{
float dst_val = (f32 / scale) + zp;
int8_t res = (int8_t)__clip(dst_val, -128, 127);
return res;
}
static float deqnt_affine_to_f32(int8_t qnt, int32_t zp, float scale)
{
return ((float)qnt - (float)zp) * scale;
}
static int process(int8_t *input, int *anchor, int grid_h, int grid_w, int height, int width, int stride,
std::vector<float> &boxes, std::vector<float> &objProbs, std::vector<int> &classId,
float threshold, int32_t zp, float scale)
{
int validCount = 0;
int grid_len = grid_h * grid_w;
int8_t thres_i8 = qnt_f32_to_affine(threshold, zp, scale);
for (int a = 0; a < 3; a++)
{
for (int i = 0; i < grid_h; i++)
{
for (int j = 0; j < grid_w; j++)
{
int8_t box_confidence = input[(PROP_BOX_SIZE * a + 4) * grid_len + i * grid_w + j];
if (box_confidence >= thres_i8)
{
int offset = (PROP_BOX_SIZE * a) * grid_len + i * grid_w + j;
int8_t *in_ptr = input + offset;
float box_x = (deqnt_affine_to_f32(*in_ptr, zp, scale)) * 2.0 - 0.5;
float box_y = (deqnt_affine_to_f32(in_ptr[grid_len], zp, scale)) * 2.0 - 0.5;
float box_w = (deqnt_affine_to_f32(in_ptr[2 * grid_len], zp, scale)) * 2.0;
float box_h = (deqnt_affine_to_f32(in_ptr[3 * grid_len], zp, scale)) * 2.0;
box_x = (box_x + j) * (float)stride;
box_y = (box_y + i) * (float)stride;
box_w = box_w * box_w * (float)anchor[a * 2];
box_h = box_h * box_h * (float)anchor[a * 2 + 1];
box_x -= (box_w / 2.0);
box_y -= (box_h / 2.0);
int8_t maxClassProbs = in_ptr[5 * grid_len];
int maxClassId = 0;
for (int k = 1; k < OBJ_CLASS_NUM; ++k)
{
int8_t prob = in_ptr[(5 + k) * grid_len];
if (prob > maxClassProbs)
{
maxClassId = k;
maxClassProbs = prob;
}
}
if (maxClassProbs>thres_i8){
boxes.push_back(box_x);
boxes.push_back(box_y);
boxes.push_back(box_w);
boxes.push_back(box_h);
objProbs.push_back((deqnt_affine_to_f32(maxClassProbs, zp, scale))* (deqnt_affine_to_f32(box_confidence, zp, scale)));
classId.push_back(maxClassId);
validCount++;
}
}
}
}
}
return validCount;
}
static int process_native_nhwc(int8_t *input, int *anchor, int grid_h, int grid_w, int height, int width, int stride,
std::vector<float> &boxes, std::vector<float> &boxScores, std::vector<int> &classId,
float threshold, int32_t zp, float scale)
{
int validCount = 0;
int8_t thres_i8 = qnt_f32_to_affine(threshold, zp, scale);
int anchor_per_branch = 3;
// 新驱动不再有对齐要求
// int align_c = get_align(PROP_BOX_SIZE*anchor_per_branch, 16);
int align_c = PROP_BOX_SIZE*anchor_per_branch;
// printf("align_c %d\n", align_c);
for (int h=0; h < grid_h; h++){
for (int w=0; w < grid_w; w++){
for (int a=0; a < anchor_per_branch; a++){
int hw_offset = h*grid_w*align_c + w*align_c + a*PROP_BOX_SIZE;
// int hw_offset = h*grid_w*anchor_per_branch*PROP_BOX_SIZE + w*anchor_per_branch*PROP_BOX_SIZE + a*PROP_BOX_SIZE;
int8_t *hw_ptr = input + hw_offset;
int8_t box_confidence = hw_ptr[4];
if (box_confidence >= thres_i8){
// printf("box_conf %d, thres_i8 %d\n", box_confidence, thres_i8);
int8_t maxClassProbs = hw_ptr[5];
int maxClassId = 0;
for (int k = 1; k < OBJ_CLASS_NUM; ++k)
{
int8_t prob = hw_ptr[5 + k];
if (prob > maxClassProbs)
{
maxClassId = k;
maxClassProbs = prob;
}
}
// printf("box_conf %d, thres_i8 %d, maxClassProbs %d\n", box_confidence, thres_i8, maxClassProbs);
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, box_y, box_w, box_h;
box_x = deqnt_affine_to_f32(hw_ptr[0], zp, scale) * 2.0 - 0.5;
box_y = deqnt_affine_to_f32(hw_ptr[1], zp, scale) * 2.0 - 0.5;
box_w = deqnt_affine_to_f32(hw_ptr[2], zp, scale) * 2.0;
box_h = deqnt_affine_to_f32(hw_ptr[3], zp, scale) * 2.0;
box_w = box_w * box_w;
box_h = box_h * box_h;
box_x = (box_x + w) * (float)stride;
box_y = (box_y + h) * (float)stride;
box_w *= (float)anchor[a * 2];
box_h *= (float)anchor[a * 2 + 1];
box_x -= (box_w / 2.0);
box_y -= (box_h / 2.0);
boxes.push_back(box_x);
boxes.push_back(box_y);
boxes.push_back(box_w);
boxes.push_back(box_h);
boxScores.push_back(limit_score);
classId.push_back(maxClassId);
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,
std::vector<int32_t> &qnt_zps, std::vector<float> &qnt_scales,
detect_result_group_t *group)
{
static int init = -1;
if (init == -1)
{
int ret = 0;
ret = loadLabelName(LABEL_NALE_TXT_PATH, labels);
if (ret < 0)
{
return -1;
}
init = 0;
}
memset(group, 0, sizeof(detect_result_group_t));
std::vector<float> filterBoxes;
std::vector<float> objProbs;
std::vector<int> classId;
// stride 8
int stride0 = 8;
int grid_h0 = model_in_h / stride0;
int grid_w0 = model_in_w / stride0;
int validCount0 = 0;
validCount0 = process_native_nhwc(input0, (int *)anchor0, grid_h0, grid_w0, model_in_h, model_in_w,
stride0, filterBoxes, objProbs, classId, 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 = 0;
validCount1 = process_native_nhwc(input1, (int *)anchor1, grid_h1, grid_w1, model_in_h, model_in_w,
stride1, filterBoxes, objProbs, classId, 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 = 0;
validCount2 = process_native_nhwc(input2, (int *)anchor2, grid_h2, grid_w2, model_in_h, model_in_w,
stride2, filterBoxes, objProbs, classId, conf_threshold, qnt_zps[2], qnt_scales[2]);
int validCount = validCount0 + validCount1 + validCount2;
// no object detect
if (validCount <= 0)
{
return 0;
}
std::vector<int> indexArray;
for (int i = 0; i < validCount; ++i)
{
indexArray.push_back(i);
}
quick_sort_indice_inverse(objProbs, 0, validCount - 1, indexArray);
std::set<int> class_set(std::begin(classId),std::end(classId));
for(auto c : class_set){
nms(validCount, filterBoxes, classId, indexArray, c, nms_threshold);
}
int last_count = 0;
group->count = 0;
/* box valid detect target */
for (int i = 0; i < validCount; ++i)
{
if (indexArray[i] == -1 || last_count >= OBJ_NUMB_MAX_SIZE)
{
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 = (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;
char *label = labels[id];
strncpy(group->results[last_count].name, label, OBJ_NAME_MAX_SIZE);
// printf("result %2d: (%4d, %4d, %4d, %4d), %s\n", i, group->results[last_count].box.left, group->results[last_count].box.top,
// group->results[last_count].box.right, group->results[last_count].box.bottom, label);
last_count++;
}
group->count = last_count;
return 0;
}
ASSISTANT
Ниже представлен пример перевода вашего кода (который использует std::vector, std::set и другие C++ конструкции) в **чистый C** без STL, с использованием динамических массивов через malloc/realloc и наивной реализации множества классов для NMS.
---
# Ключевые идеи перехода на чистый C:
- Заменяем `std::vector<float>` на динамический массив `float*` с контролем размера и длины.
- Заменяем `std::vector<int>` на `int*`.
- Вместо `std::set<int>` можно использовать простой массив с проверкой уникальности.
- Рекурсивный `quick_sort_indice_inverse` реализуем с массивами.
- Убираем использование `inline static` — заменяем на `static` (возможно `inline` поднимается компилятором).
- Используем C-комментарии и строгий стиль C.
- Для `strncpy` выводим просто как есть, убедитесь что `OBJ_NAME_MAX_SIZE` и `OBJ_CLASS_NUM` определены.
---
# Полный пример на чистом C:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#define LABEL_NALE_TXT_PATH "./model/coco_80_labels_list.txt"
#define OBJ_CLASS_NUM 80
#define OBJ_NAME_MAX_SIZE 64
#define OBJ_NUMB_MAX_SIZE 512
#define PROP_BOX_SIZE 85 // Обычно 5 + 80 классов
typedef struct {
int left, top, right, bottom;
} box_t;
typedef struct {
char name[OBJ_NAME_MAX_SIZE];
box_t box;
float prop;
} detect_result_t;
typedef struct {
detect_result_t results[OBJ_NUMB_MAX_SIZE];
int count;
} detect_result_group_t;
static char *labels[OBJ_CLASS_NUM];
// якоря
static const int anchor0[6] = {10, 13, 16, 30, 33, 23};
static const int anchor1[6] = {30, 61, 62, 45, 59, 119};
static const int anchor2[6] = {116, 90, 156, 198, 373, 326};
static int clamp_i(float val, int min, int max)
{
if (val < min) return min;
if (val > max) return max;
return (int)val;
}
// --- динамические массивы ---------------------------------------------------
typedef struct {
float *data;
int count;
int capacity;
} float_array;
typedef struct {
int *data;
int count;
int capacity;
} int_array;
static void float_array_init(float_array *arr)
{
arr->data = NULL;
arr->count = 0;
arr->capacity = 0;
}
static void float_array_free(float_array *arr)
{
if (arr->data) free(arr->data);
arr->data = NULL;
arr->count = 0;
arr->capacity = 0;
}
static int float_array_push(float_array *arr, float val)
{
if (arr->count >= arr->capacity)
{
int new_cap = arr->capacity == 0 ? 64 : arr->capacity * 2;
float *tmp = (float *)realloc(arr->data, new_cap * sizeof(float));
if (!tmp) return -1;
arr->data = tmp;
arr->capacity = new_cap;
}
arr->data[arr->count++] = val;
return 0;
}
static void int_array_init(int_array *arr)
{
arr->data = NULL;
arr->count = 0;
arr->capacity = 0;
}
static void int_array_free(int_array *arr)
{
if (arr->data) free(arr->data);
arr->data = NULL;
arr->count = 0;
arr->capacity = 0;
}
static int int_array_push(int_array *arr, int val)
{
if (arr->count >= arr->capacity)
{
int new_cap = arr->capacity == 0 ? 64 : arr->capacity * 2;
int *tmp = (int *)realloc(arr->data, new_cap * sizeof(int));
if (!tmp) return -1;
arr->data = tmp;
arr->capacity = new_cap;
}
arr->data[arr->count++] = val;
return 0;
}
// --- конец динамических массивов ---------------------------------------------
// Функция чтения строк и загрузки меток в labels - оставляйте вашу реализацию
// CalculateOverlap
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);
}
// NMS с динамическими массивами
static void nms(int validCount, float_array *outputLocations, int_array *classIds, int *order, int filterId, float threshold)
{
for (int i = 0; i < validCount; ++i)
{
if (order[i] == -1 || classIds->data[i] != filterId)
continue;
int n = order[i];
for (int j = i + 1; j < validCount; ++j)
{
int m = order[j];
if (m == -1 || classIds->data[j] != filterId)
continue;
float xmin0 = outputLocations->data[n * 4 + 0];
float ymin0 = outputLocations->data[n * 4 + 1];
float xmax0 = outputLocations->data[n * 4 + 0] + outputLocations->data[n * 4 + 2];
float ymax0 = outputLocations->data[n * 4 + 1] + outputLocations->data[n * 4 + 3];
float xmin1 = outputLocations->data[m * 4 + 0];
float ymin1 = outputLocations->data[m * 4 + 1];
float xmax1 = outputLocations->data[m * 4 + 0] + outputLocations->data[m * 4 + 2];
float ymax1 = outputLocations->data[m * 4 + 1] + outputLocations->data[m * 4 + 3];
float iou = CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1, xmax1, ymax1);
if (iou > threshold)
order[j] = -1;
}
}
}
// Быстрая сортировка с массивами
static void quick_sort_indice_inverse(float_array *input, int left, int right, int *indices)
{
if (left >= right)
return;
float key = input->data[left];
int key_index = indices[left];
int low = left;
int high = right;
while (low < high)
{
while (low < high && input->data[high] <= key) --high;
input->data[low] = input->data[high];
indices[low] = indices[high];
while (low < high && input->data[low] >= key) ++low;
input->data[high] = input->data[low];
indices[high] = indices[low];
}
input->data[low] = key;
indices[low] = key_index;
quick_sort_indice_inverse(input, left, low - 1, indices);
quick_sort_indice_inverse(input, low + 1, right, indices);
}
static int8_t qnt_f32_to_affine(float f32, int32_t zp, float scale)
{
float dst_val = (f32 / scale) + zp;
if (dst_val < -128) dst_val = -128;
if (dst_val > 127) dst_val = 127;
return (int8_t)dst_val;
}
static float deqnt_affine_to_f32(int8_t qnt, int32_t zp, float scale)
{
return ((float)qnt - (float)zp) * scale;
}
// Пример функции process_native_nhwc (адаптация под C, с dynamic arrays).
// Добавляйте аналогично process() и остальные функции по образцу.
static int process_native_nhwc(int8_t *input, int *anchor, int grid_h, int grid_w,
int height, int width, int stride,
float_array *boxes, float_array *boxScores,
int_array *classId,
float threshold, int32_t zp, float scale)
{
int validCount = 0;
int8_t thres_i8 = qnt_f32_to_affine(threshold, zp, scale);
int anchor_per_branch = 3;
int align_c = PROP_BOX_SIZE * anchor_per_branch;
for (int h=0; h < grid_h; h++){
for (int w=0; w < grid_w; w++){
for (int 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 (int 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 + w) * (float)stride;
box_y = (box_y + 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 (float_array_push(boxes, box_x) < 0) return -1;
if (float_array_push(boxes, box_y) < 0) return -1;
if (float_array_push(boxes, box_w) < 0) return -1;
if (float_array_push(boxes, box_h) < 0) return -1;
if (float_array_push(boxScores, limit_score) < 0) return -1;
if (int_array_push(classId, maxClassId) < 0) return -1;
validCount++;
}
}
}
}
}
return validCount;
}
// Аналогично напишите функции process() и остальные...
// Пример реализации post_process
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;
if (init == -1)
{
int ret = loadLabelName(LABEL_NALE_TXT_PATH, labels);
if (ret < 0) return -1;
init = 0;
}
memset(group, 0, sizeof(detect_result_group_t));
// Инициализация динамических массивов
float_array filterBoxes; float_array_init(&filterBoxes);
float_array objProbs; float_array_init(&objProbs);
int_array classId; int_array_init(&classId);
// Обрабатываем выходы (stride 8,16,32)
int grid_h, grid_w;
int validCount0 = 0, validCount1 = 0, validCount2 = 0;
grid_h = model_in_h / 8;
grid_w = model_in_w / 8;
validCount0 = process_native_nhwc(input0, (int *)anchor0, grid_h, grid_w,
model_in_h, model_in_w, 8,
&filterBoxes, &objProbs, &classId,
conf_threshold, qnt_zps[0], qnt_scales[0]);
grid_h = model_in_h / 16;
grid_w = model_in_w / 16;
validCount1 = process_native_nhwc(input1, (int *)anchor1, grid_h, grid_w,
model_in_h, model_in_w, 16,
&filterBoxes, &objProbs, &classId,
conf_threshold, qnt_zps[1], qnt_scales[1]);
grid_h = model_in_h / 32;
grid_w = model_in_w / 32;
validCount2 = process_native_nhwc(input2, (int *)anchor2, grid_h, grid_w,
model_in_h, model_in_w, 32,
&filterBoxes, &objProbs, &classId,
conf_threshold, qnt_zps[2], qnt_scales[2]);
int validCount = validCount0 + validCount1 + validCount2;
if (validCount <= 0)
{
float_array_free(&filterBoxes);
float_array_free(&objProbs);
int_array_free(&classId);
return 0;
}
// Создаем массив индексов для сортировки
int *indexArray = (int *)malloc(validCount * sizeof(int));
if (!indexArray)
{
float_array_free(&filterBoxes);
float_array_free(&objProbs);
int_array_free(&classId);
return -1;
}
for (int i = 0; i < validCount; ++i)
indexArray[i] = i;
// Сортировка
quick_sort_indice_inverse(&objProbs, 0, validCount - 1, indexArray);
// Собираем уникальные классы в массив
int *unique_classes = (int *)malloc(validCount * sizeof(int));
int unique_count = 0;
for (int i = 0; i < validCount; ++i)
{
int c = classId.data[i];
int exists = 0;
for (int j = 0; j < unique_count; ++j)
if (unique_classes[j] == c) {
exists = 1;
break;
}
if (!exists)
unique_classes[unique_count++] = c;
}
// NMS для каждого класса
for (int cidx = 0; cidx < unique_count; ++cidx)
{
nms(validCount, &filterBoxes, &classId, indexArray, unique_classes[cidx], nms_threshold);
}
free(unique_classes);
int last_count = 0;
group->count = 0;
// Копируем результаты
for (int i = 0; i < validCount; ++i)
{
int idx = indexArray[i];
if (idx == -1 || last_count >= OBJ_NUMB_MAX_SIZE)
continue;
float x1 = filterBoxes.data[idx * 4 + 0];
float y1 = filterBoxes.data[idx * 4 + 1];
float x2 = x1 + filterBoxes.data[idx * 4 + 2];
float y2 = y1 + filterBoxes.data[idx * 4 + 3];
int id = classId.data[idx];
float obj_conf = objProbs.data[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;
if (id >= 0 && id < OBJ_CLASS_NUM && labels[id])
strncpy(group->results[last_count].name, labels[id], OBJ_NAME_MAX_SIZE - 1);
group->results[last_count].name[OBJ_NAME_MAX_SIZE-1] = 0;
last_count++;
}
group->count = last_count;
free(indexArray);
float_array_free(&filterBoxes);
float_array_free(&objProbs);
int_array_free(&classId);
return 0;
}
```
---
### Пояснения:
- Заменили `std::vector` на `float_array` и `int_array` — динамические массивы с добавлением/удалением.
- Вместо `std::set` — простой наивный поиск уникальных элементов в массиве.
- Вместо `for(auto c : class_set)` — итерация по массиву уникальных классов.
- Добавлен контроль ошибок при malloc/realloc.
- Стандартные библиотечные функции `malloc`, `realloc`, `free`, `memset`, `strncpy` используются как есть.
- Необходимо реализовать `loadLabelName` и `readLine` отдельно(выше ваш код уже на чистом C).
- Убедитесь, что массивы `labels[]`, `anchor0`, `anchor1`, `anchor2` объявлены глобально и видны.
- Проверьте что `PROP_BOX_SIZE`, `OBJ_CLASS_NUM`, `OBJ_NUMB_MAX_SIZE`, `OBJ_NAME_MAX_SIZE` объявлены и имеют правильные значения.
- Функции `process()` и `process_native_nhwc()` можно привести в аналогичный стиль.
---
Если нужно — могу помочь с доработкой отдельных функций.
Это достаточное и рабочее направление для портирования вашего C++ кода в чистый C с минимально необходимыми изменениями под отсутствие STL.