78 lines
2.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "imageInput.h"
#define BUFFER_SIZE 100
#define FILE_HEADER_STRING "__info2_image_file_format__"
// TODO Implementieren Sie geeignete Hilfsfunktionen für das Lesen der Bildserie aus einer Datei
int checkString (FILE *file){ //Checks if String at the start of File equals expected Format (0 for wrong 1 for right)
if (file == NULL){ //returns 0 for empty file
return 0;
}
char expectedString[] = FILE_HEADER_STRING;
char actualString[BUFFER_SIZE];
rewind(file);
size_t bytesRead = fread(actualString, 1,27 , file); //Stores Bytes of start of File to actualString
if (bytesRead != 27){
return 0;} //Returns 0 if File is to short
actualString[27] = '\0';
if (strcmp(actualString, expectedString) != 0){
return 0;
}
else{
return 1;
}
}
void setParameters(FILE* file, unsigned int* imageCount, unsigned int* width, unsigned int* height);
void allocateMemory(GrayScaleImageSeries *s, const int imageCount, const int width, const int height);
// TODO Vervollständigen Sie die Funktion readImages unter Benutzung Ihrer Hilfsfunktionen
GrayScaleImageSeries *readImages(const char *path)
{
FILE* file = fopen(path, "rb");
// TODO open binary file from file name
GrayScaleImageSeries *series = NULL;
if(!(checkString(file)))
return NULL;
unsigned int* imageCount = &(series->count); // sets a pointer for int variable count in struct
setParameters(file, imageCount, &(series->images->width), &(series->images->height));
allocateMemory(series, *imageCount, series->images->width, series->images->height);
fclose(file);
return series;
}
// TODO Vervollständigen Sie die Funktion clearSeries, welche eine Bildserie vollständig aus dem Speicher freigibt
void clearSeries(GrayScaleImageSeries *series)
{
for(size_t i = series->count - 1; i >= 0; i--)
{
free(series->images+series->count*sizeof(GrayScaleImage)*i);
free(series->labels+series->count*sizeof(unsigned char)*i);
}
series->images = NULL;
series->labels = NULL;
}
void setParameters(FILE* file, unsigned int* imageCount, unsigned int* width, unsigned int* height) { // sets the parameters
char buffer[3];
fseek(file, 27, SEEK_SET);
fread(buffer, 1, 3, file);
*imageCount = (int) buffer[0];
*width = (int) buffer[1];
*height = (int) buffer[2];
}
// change this to createMatrix?
void allocateMemory(GrayScaleImageSeries* s, const int imageCount, const int width, const int height) {
for (int i = 0; i < imageCount; i++) {
s->images[i].buffer = (unsigned char *) malloc(width * height * sizeof(unsigned char)); // allocates memory for every image in the series
}
}