diff --git a/imageInput.c b/imageInput.c index 9302a3d..37936dc 100644 --- a/imageInput.c +++ b/imageInput.c @@ -48,6 +48,83 @@ static int readHeader(FILE *file, unsigned int *count, unsigned int *width, unsi GrayScaleImageSeries *readImages(const char *path) { GrayScaleImageSeries *series = NULL; + FILE *file = NULL; + unsigned int count = 0; + unsigned int width = 0; + unsigned int height = 0; + + file = fopen(path, "rb"); + if (file == NULL) + { + return NULL; + } + + if (!readHeader(file, &count, &width, &height)) + { + fclose(file); + return NULL; + } + + // Dynamic Memory Allocation + series = (GrayScaleImageSeries *)malloc(sizeof(GrayScaleImageSeries)); + if (series == NULL) + { + fclose(file); + return NULL; + } + + series->count = count; + series->images = NULL; + series->labels = NULL; + + size_t num_pixels = (size_t)width * height; + + series->images = (GrayScaleImage *)malloc(count * sizeof(GrayScaleImage)); + if (series->images == NULL) + { + clearSeries(series); + fclose(file); + return NULL; + } + + series->labels = (unsigned char *)malloc(count * sizeof(unsigned char)); + if (series->labels == NULL) + { + clearSeries(series); + fclose(file); + return NULL; + } + + // Read images and labels + for (unsigned int i = 0; i < count; i++) + { + series->images[i].width = width; + series->images[i].height = height; + + series->images[i].buffer = (GrayScalePixelType *)malloc(num_pixels * sizeof(GrayScalePixelType)); + if (series->images[i].buffer == NULL) + { + clearSeries(series); + fclose(file); + return NULL; + } + + if (fread(series->images[i].buffer, sizeof(GrayScalePixelType), num_pixels, file) != num_pixels) + { + clearSeries(series); + fclose(file); + return NULL; + } + + if (fread(&series->labels[i], sizeof(unsigned char), 1, file) != 1) + { + clearSeries(series); + fclose(file); + return NULL; + } + } + + fclose(file); return series; }