Генерируем код из свёрточной нейросети
Автор
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <dirent.h>
#include <string.h>
#include <dlfcn.h>
#include "neural_net.h"
int read_rgb8(const char* filename, float* output, int expected_size) {
FILE *fp = fopen(filename, "rb");
if (!fp) {
printf("Cannot open file: %s\n", filename);
return 0;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
int expected_bytes = expected_size * 3;
if (file_size != expected_bytes) {
if (file_size < expected_bytes) {
printf("Error: File too small\n");
fclose(fp);
return 0;
}
}
unsigned char* rgb = malloc(expected_bytes);
size_t bytes_read = fread(rgb, 1, expected_bytes, fp);
fclose(fp);
if (bytes_read != expected_bytes) {
printf("Error: Expected %zu bytes, read %zu\n", (size_t)expected_bytes, bytes_read);
free(rgb);
return 0;
}
for(int i = 0; i < expected_size * 3; i++) {
output[i] = rgb[i] / 127.5f - 1.0f;
}
free(rgb);
return 1;
}
void softmax(float* x, int n) {
float max = x[0];
for(int i = 1; i < n; i++) if(x[i] > max) max = x[i];
float sum = 0;
for(int i = 0; i < n; i++) {
x[i] = exp(x[i] - max);
sum += x[i];
}
for(int i = 0; i < n; i++) x[i] /= sum;
}
int main() {
void* handle = dlopen("./libneuralnet.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "Error loading library: %s\n", dlerror());
return 1;
}
typedef void (*neural_net_t)(float*, const float*);
neural_net_t neural_net = (neural_net_t)dlsym(handle, "neural_net");
if (!neural_net) {
fprintf(stderr, "Error loading symbol: %s\n", dlerror());
dlclose(handle);
return 1;
}
DIR* dir = opendir("неизвестно_rgb8");
if(!dir) {
printf("Folder 'неизвестно_rgb8' not found\n");
dlclose(handle);
return 1;
}
printf("%-20s %-15s %s\n", "File", "Prediction", "Confidence");
printf("------------------------------------------------\n");
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
char* name = entry->d_name;
if(strstr(name, ".rgb") == NULL) continue;
char path[256];
snprintf(path, sizeof(path), "неизвестно_rgb8/%s", name);
float input[64 * 64 * 3];
if(!read_rgb8(path, input, 64 * 64)) {
printf("Error loading: %s\n", name);
continue;
}
float output[3];
neural_net(output, input);
softmax(output, 3);
int pred = 0;
float prob = output[0];
for(int i = 1; i < 3; i++) {
if(output[i] > prob) {
prob = output[i];
pred = i;
}
}
const char* classes[] = {"квадрат", "круг", "треугольник"};
printf("%-20s %-15s %.3f\n", name, classes[pred], prob);
}
closedir(dir);
dlclose(handle);
return 0;
}