First off, this is a snippet of code from my larger project, so please excuse the lack of error checks and other minor details. I excluded these details for readability.
This snippet is supposed to read a .raw
file and store the data into a uint16_t *
then convert it into a 2D array which needs to be written back as an identical file using fwrite()
.
I know for a fact that the data being written into image_ptr
is correct. I believe my problem is occuring when I am attempting to save the variable image_ptr
into the 2D array named image
in the main
function or it is occurring within the fwrite()
statement in my save_image
function.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX_ROW 2560
#define MAX_COL 2160
uint16_t image[MAX_ROW][MAX_COL];
uint16_t* get_image_data(uint32_t image_index)
{
int result;
char filename[32];
sprintf(filename, "image%d.raw", image_index);
FILE *image_raw = fopen(filename, "rb");
fseek(image_raw, 0, SEEK_END);
long filesize = ftell(image_raw);
rewind(image_raw);
long num_samples = filesize / sizeof(uint16_t);
/*READ IMAGE DATA*/
uint16_t *image_data_ptr = (uint16_t*) malloc(filesize);
size_t num_read = fread(image_data_ptr, sizeof(uint16_t), num_samples, image_raw);
fclose(image_raw);
return image_data_ptr;
}
int save_image()
{
int row, col, pixel_index = 0;
int data_size = MAX_ROW * MAX_COL;
uint16_t * image_data = malloc((sizeof *image_data)*data_size);
image_data = image[0];
FILE *ptr_image_file;
ptr_image_file = fopen("image21.raw", "wb");
for(col = 0; col < MAX_COL; col++)
{
if(**(image + col) != 0)
{
if (fwrite(*(image + col), sizeof(uint16_t), MAX_ROW, ptr_image_file) != MAX_ROW)
{
fprintf(stderr, "Can't write to output file\n");
fclose(ptr_image_file);
return -1;
}
}
}
fclose(ptr_image_file);
return 0;
}
int main()
{
uint16_t * image_ptr = malloc((sizeof *image_ptr)*MAX_ROW*MAX_COL);
//Get Image Data
image_ptr = get_image_data(1);
int row, col, pixel_index = 0;
for(col = 0; col < MAX_COL; col++)
{
for(row = 0; row < MAX_ROW; row++)
{
*(*(image + col) + row) = *(image_ptr + pixel_index);
pixel_index++;
}
}
save_image();
return 0;
}