Last active
November 21, 2017 16:41
-
-
Save anael-seghezzi/757ab4dfa574dd0d22ea4857fd8c2593 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct mnist_images | |
{ | |
unsigned char *data; | |
float *dataf; | |
int count; | |
int w, h; | |
}; | |
struct mnist_labels | |
{ | |
unsigned char *data; | |
int count; | |
}; | |
int32_t endian_swap32(int32_t val) | |
{ | |
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF); | |
return (val << 16) | ((val >> 16) & 0xFFFF); | |
} | |
void mnist_labels_destroy(struct mnist_labels *dest) | |
{ | |
free(dest->data); | |
} | |
void mnist_images_destroy(struct mnist_images *dest) | |
{ | |
free(dest->data); | |
free(dest->dataf); | |
} | |
int mnist_labels_read(struct mnist_labels *dest, const char *filename) | |
{ | |
FILE *file = fopen(filename, "rb"); | |
int header; | |
if(! file) { | |
printf("MNIST ERROR: can't read file %s\n", filename); | |
return 0; | |
} | |
fread(&header, sizeof(int), 1, file); | |
fread(&dest->count, sizeof(int), 1, file); | |
dest->count = endian_swap32(dest->count); | |
dest->data = (unsigned char *)malloc(dest->count * sizeof(char)); | |
fread(dest->data, sizeof(char), dest->count, file); | |
fclose(file); | |
return 1; | |
} | |
int mnist_images_read(struct mnist_images *dest, const char *filename) | |
{ | |
FILE *file = fopen(filename, "rb"); | |
int header, size, i; | |
if(! file) { | |
printf("MNIST ERROR: can't read file %s\n", filename); | |
return 0; | |
} | |
fread(&header, sizeof(int), 1, file); | |
fread(&dest->count, sizeof(int), 1, file); | |
fread(&dest->w, sizeof(int), 1, file); | |
fread(&dest->h, sizeof(int), 1, file); | |
dest->count = endian_swap32(dest->count); | |
dest->w = endian_swap32(dest->w); | |
dest->h = endian_swap32(dest->h); | |
size = dest->count * dest->w * dest->h; | |
dest->data = (unsigned char *)malloc(size * sizeof(char)); | |
dest->dataf = (float *)malloc(size * sizeof(float)); | |
fread(dest->data, sizeof(char), size, file); | |
for (i = 0; i < size; i++) | |
dest->dataf[i] = (dest->data[i] / 255.0) * 2.0 - 1.0; | |
fclose(file); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment