Update src/preview_mnist.c

This commit is contained in:
augustin64 2022-03-19 16:54:16 +01:00
parent 3606e29d17
commit 02c4591d44

View File

@ -4,6 +4,12 @@
#include <inttypes.h> #include <inttypes.h>
uint32_t swap_endian(uint32_t val) {
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void print_image(unsigned int width, unsigned int height, FILE* ptr, int start) { void print_image(unsigned int width, unsigned int height, FILE* ptr, int start) {
unsigned char buffer[width*height+start]; unsigned char buffer[width*height+start];
@ -19,37 +25,53 @@ void print_image(unsigned int width, unsigned int height, FILE* ptr, int start)
} }
printf("\n"); printf("\n");
} }
printf("\t\t---\n");
} }
void read_mnist_images(char* filename) {
void print_bytes(char* filename) {
unsigned char buffer[4]; unsigned char buffer[4];
FILE *ptr; FILE *ptr;
ptr = fopen(filename, "rb"); ptr = fopen(filename, "rb");
fread(buffer, sizeof(buffer), 1, ptr); uint32_t magic_number;
uint32_t number_of_images;
unsigned int height;
unsigned int width;
uint32_t magic_number = buffer[0]; fread(&magic_number, sizeof(uint32_t), 1, ptr);
uint32_t number_of_images = (int)buffer[1]; magic_number = swap_endian(magic_number);
unsigned int height = buffer[2];
unsigned int width = buffer[3];
if (magic_number != 2051){
printf("Incorrect magic number !\n");
exit(1);
}
printf("magic number: %" PRIu32 "\n", magic_number); fread(&number_of_images, sizeof(uint32_t), 1, ptr);
printf("number of images: %" PRIu32 "\n", number_of_images); number_of_images = swap_endian(number_of_images);
printf("%x x %x\n\n", width, height);
for (int i=0; i < number_of_images; i++) fread(&height, sizeof(unsigned int), 1, ptr);
print_image(width, height, ptr, (i*width*height)+4); height = swap_endian(height);
fread(&width, sizeof(unsigned int), 1, ptr);
width = swap_endian(width);
//printf("magic number: %" PRIu32 "\n", magic_number);
//printf("number of images: %" PRIu32 "\n", number_of_images);
//printf("%u x %u\n\n", width, height);
for (int i=0; i < number_of_images; i++) {
printf("--- Number %d ---\n", i);
print_image(width, height, ptr, (i*width*height));
}
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
if (argc == 1) { if (argc == 1) {
printf("Utilisation: %s [FILE]\n", argv[0]); printf("Utilisation: %s [FILE]\n", argv[0]);
return 1; return 1;
} }
print_bytes(argv[1]); read_mnist_images(argv[1]);
return 0; return 0;
} }