samedi 2 juillet 2016

Reading a P2 .pgm image into a 2D array in C

I have started learning about image processing and I am trying to read a .pgm file into a 2D array in C. I am testing the input and output, but the program did not work properly so, I tried to make some changes. How could I improve/modify the code to make it work?

#include<stdio.h>
#include<stdlib.h>

struct PGMstructure 
{
    int maxVal;
    int width;
    int height;
    int data[800][800];
};


int main()
{
    FILE *imagein,*imageout;

    int row, col;

    int i,j;
    int ch_int;
    struct PGMstructure *imginfo;   
    char infpath[500],outfpath[500];

    printf("Enter PGM file path:");
    scanf("%s",infpath);
    imagein = fopen(infpath,"r+");

    if(imagein == NULL)
    {
        printf("Error opening first file");
        exit(8);
    }

    while(getc(imagein) != 'n');             

    while (getc(imagein) == '#')              
    {
        while (getc(imagein) != 'n');          
    }

    fseek(imagein, -1, SEEK_CUR);
    fscanf(imagein,"%d", &imginfo->width);
    fscanf(imagein,"%d", &imginfo->height);
    fscanf(imagein,"%d", &imginfo->maxVal);
    printf("n width  = %dn",imginfo->width);
    printf("n height = %dn",imginfo->height);
    printf("n maxVal = %dn",imginfo->maxVal);

    for (row=0; row<imginfo->height; row++){

        for (col=0; col < imginfo->width; col++)
        {    
            fscanf(imagein,"%d", &ch_int);
            imginfo->data[row][col] = ch_int;
        }
    }

    printf("Enter path of output file:");

    scanf("%s",outfpath);
    imageout = fopen(outfpath,"w+");


    for ( i = 0 ; i < row ; i++ )
    {
        for ( j = 0 ; j < col ; j++ )
        {
            fprintf( imageout,"%d" , imginfo->data[row][col] );
        }
        printf( "n" ) ;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire